From 05ab5ba0cf5b0c45bee6081facfabbb355e1cd73 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 6 Oct 2026 13:46:55 +0200 Subject: [PATCH 001/139] Baseline IrisModule before the IrisApi port --- .gitignore | 2 + README.md | 18 + build.gradle.kts | 42 + gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 48462 bytes gradle/wrapper/gradle-wrapper.properties | 9 + gradlew | 248 ++ gradlew.bat | 82 + settings.gradle.kts | 4 + source-patterns.txt | 18 + .../engine/actuator/IrisBiomeActuator.java | 115 + .../engine/actuator/IrisDecorantActuator.java | 143 + .../actuator/IrisTerrainNormalActuator.java | 261 ++ .../iris/engine/decorator/DecoratorCore.java | 536 ++++ .../decorator/DecoratorPlatformHooks.java | 62 + .../engine/decorator/FloatingDecorator.java | 55 + .../decorator/IrisCeilingDecorator.java | 74 + .../engine/decorator/IrisEngineDecorator.java | 45 + .../decorator/IrisSeaFloorDecorator.java | 84 + .../decorator/IrisSeaSurfaceDecorator.java | 97 + .../decorator/IrisShoreLineDecorator.java | 126 + .../decorator/IrisSurfaceDecorator.java | 96 + .../framework/IrisStructureLocator.java | 1321 +++++++++ .../iris/engine/framework/PlacedObject.java | 37 + .../framework/PlacedStructurePiece.java | 54 + .../engine/framework/StructureAssembler.java | 1357 ++++++++++ .../StructureCaveAnchorResolver.java | 359 +++ .../framework/StructurePlacementGrid.java | 287 ++ .../framework/StructurePlacementMarker.java | 95 + .../framework/StructurePlacementScope.java | 148 + .../framework/StructureReachability.java | 127 + .../framework/StructureVerticalBounds.java | 51 + .../structure/CompiledStructureGraph.java | 101 + .../structure/IrisObjectFrameReader.java | 386 +++ .../structure/JigsawPoolSelection.java | 104 + .../PlanarJigsawWorkcellResolver.java | 139 + .../structure/StructureAssemblyResult.java | 71 + .../structure/StructureAssemblyStatus.java | 17 + .../StructureGraphAssemblySample.java | 30 + .../structure/StructureGraphCatalog.java | 99 + .../structure/StructureGraphCompilation.java | 242 ++ .../structure/StructureGraphCompiler.java | 1264 +++++++++ .../structure/StructureGraphDiagnostic.java | 67 + .../structure/StructureGraphResolver.java | 74 + .../StructureGraphValidationException.java | 11 + .../StructureResourceBundleGraphCompiler.java | 201 ++ .../engine/image/CompiledIrisImageMap.java | 424 +++ .../engine/image/IrisImageMapCompiler.java | 825 ++++++ .../engine/image/IrisImageMapMaskSampler.java | 113 + .../engine/image/IrisImageMapRuntime.java | 386 +++ .../image/IrisImageMapSourceMetadata.java | 18 + .../IrisImageMapValidationException.java | 35 + .../mantle/components/CarveOrphanSweep.java | 313 +++ .../mantle/components/CaveCarveScratch.java | 73 + .../components/CaveFieldModuleState.java | 58 + .../components/CaveFluidSupportPlan.java | 120 + .../CaveObjectPlacementTransaction.java | 286 ++ .../FloatingIslandSampleResolver.java | 74 + .../FloatingObjectPlacementTransaction.java | 211 ++ .../components/GoldenDebugObjectPlacer.java | 159 ++ .../mantle/components/IrisCaveCarver3D.java | 2381 +++++++++++++++++ .../components/IrisStructureComponent.java | 678 +++++ .../mantle/components/IslandObjectPlacer.java | 220 ++ .../components/MantleCarvingComponent.java | 708 +++++ .../MantleFloatingObjectComponent.java | 614 +++++ .../components/MantleObjectComponent.java | 1650 ++++++++++++ .../components/StructureCarveEnvelope.java | 147 + .../components/StructureCarvingFootprint.java | 456 ++++ .../StructureFoundationPlanner.java | 79 + .../components/SurfaceFluidBoundaryPlan.java | 94 + .../iris/engine/mode/ModeEnclosure.java | 38 + .../arcane/iris/engine/mode/ModeIslands.java | 38 + .../iris/engine/mode/ModeOverworld.java | 133 + .../iris/engine/mode/ModeSuperFlat.java | 38 + .../engine/modifier/IrisCarveModifier.java | 777 ++++++ .../engine/modifier/IrisCarveScratch.java | 277 ++ .../engine/modifier/IrisCustomModifier.java | 64 + .../engine/modifier/IrisDepositModifier.java | 357 +++ .../IrisFloatingChildBiomeModifier.java | 406 +++ .../modifier/IrisPerfectionModifier.java | 200 ++ .../engine/modifier/IrisPostModifier.java | 345 +++ .../engine/object/annotations/ArrayType.java | 35 + .../engine/object/annotations/DependsOn.java | 31 + .../iris/engine/object/annotations/Desc.java | 33 + .../engine/object/annotations/MaxNumber.java | 31 + .../engine/object/annotations/MinNumber.java | 31 + .../object/annotations/RegistryListBiome.java | 37 + .../annotations/RegistryListBlockType.java | 33 + .../annotations/RegistryListEnchantment.java | 14 + .../annotations/RegistryListEntityType.java | 33 + .../object/annotations/RegistryListFont.java | 33 + .../annotations/RegistryListFunction.java | 18 + .../annotations/RegistryListItemType.java | 33 + .../RegistryListNativeJigsawPool.java | 14 + .../annotations/RegistryListPotionEffect.java | 14 + .../annotations/RegistryListResource.java | 35 + .../RegistryListSpecialEntity.java | 33 + .../annotations/RegistryListStructure.java | 33 + .../RegistryListVanillaStructure.java | 41 + .../RegistryListVanillaStructureSet.java | 33 + .../annotations/RegistryMapBlockState.java | 12 + .../engine/object/annotations/Required.java | 33 + .../engine/object/annotations/Snippet.java | 31 + .../functions/ComponentFlagFunction.java | 42 + .../functions/LootTableKeyFunction.java | 23 + .../object/compatibility/IrisCompat.java | 381 +++ .../IrisCompatabilityBlockFilter.java | 72 + .../IrisCompatabilityItemFilter.java | 69 + .../object/decoration/IrisDecorationPart.java | 39 + .../object/decoration/IrisDecorationStep.java | 96 + .../object/decoration/IrisDecorator.java | 356 +++ .../IrisImportedFeatureControl.java | 107 + .../NativeFeatureGenerationStatus.java | 28 + .../object/entity/IrisAttributeModifier.java | 154 ++ .../iris/engine/object/entity/IrisEffect.java | 323 +++ .../iris/engine/object/entity/IrisEntity.java | 555 ++++ .../engine/object/entity/IrisEntitySpawn.java | 238 ++ .../object/entity/IrisPotionEffect.java | 102 + .../object/entity/PotionEffectTypes.java | 98 + .../spawn/IrisEngineSpawnerCooldown.java | 38 + .../object/entity/spawn/IrisSpawnGroup.java | 36 + .../object/entity/spawn/IrisSpawner.java | 142 + .../entity/spawn/IrisSpawnerCooldowns.java | 34 + .../object/entity/spawn/IrisSurface.java | 68 + .../iris/engine/object/image/IrisImage.java | 168 ++ .../object/image/IrisImageColorMode.java | 9 + .../engine/object/image/IrisImageMap.java | 120 + .../object/image/IrisImageMapAlpha.java | 11 + .../object/image/IrisImageMapApplication.java | 13 + .../object/image/IrisImageMapBinding.java | 29 + .../engine/object/image/IrisImageMapMask.java | 33 + .../image/IrisImageMapMaskOperation.java | 12 + .../object/image/IrisImageMapOrigin.java | 23 + .../object/image/IrisImageMapOutOfBounds.java | 12 + .../object/image/IrisImageMapRotation.java | 11 + .../object/image/IrisImageMapSampling.java | 10 + .../engine/object/image/IrisImageMapType.java | 13 + .../image/IrisImageMapUnknownColor.java | 10 + .../iris/engine/object/loot/IObjectLoot.java | 14 + .../engine/object/loot/InventorySlotType.java | 38 + .../engine/object/loot/IrisBlockDrops.java | 92 + .../engine/object/loot/IrisEnchantment.java | 105 + .../iris/engine/object/loot/IrisLoot.java | 297 ++ .../iris/engine/object/loot/IrisLootMode.java | 33 + .../engine/object/loot/IrisLootReference.java | 68 + .../engine/object/loot/IrisLootTable.java | 115 + .../engine/object/loot/IrisObjectLoot.java | 82 + .../object/loot/IrisObjectVanillaLoot.java | 57 + .../object/loot/IrisVanillaLootTable.java | 111 + .../engine/object/marker/IrisCommand.java | 86 + .../object/marker/IrisCommandRegistry.java | 94 + .../iris/engine/object/marker/IrisMarker.java | 68 + .../object/marker/IrisObjectMarker.java | 77 + .../object/marker/ObjectMarkerPlacement.java | 108 + .../material/BlockDataMergeSupport.java | 75 + .../engine/object/material/IrisBlockData.java | 237 ++ .../object/material/IrisMaterialPalette.java | 203 ++ .../iris/engine/object/mod/IrisMod.java | 120 + .../object/mod/IrisModBiomeInjector.java | 51 + .../object/mod/IrisModBiomeReplacer.java | 50 + .../object/mod/IrisModNoiseStyleReplacer.java | 49 + .../IrisModObjectPlacementBiomeInjector.java | 50 + .../IrisModObjectPlacementRegionInjector.java | 50 + .../object/mod/IrisModObjectReplacer.java | 50 + .../object/mod/IrisModRegionReplacer.java | 50 + .../object/noise/IrisGeneratorStyle.java | 278 ++ .../engine/object/noise/IrisInterpolator.java | 84 + .../object/noise/IrisNoiseGenerator.java | 212 ++ .../noise/IrisShapedGeneratorStyle.java | 85 + .../engine/object/noise/IrisStyledRange.java | 72 + .../iris/engine/object/noise/NoiseStyle.java | 566 ++++ .../noise/expression/IrisExpression.java | 138 + .../expression/IrisExpressionFunction.java | 110 + .../noise/expression/IrisExpressionLoad.java | 187 ++ .../object/placement/DecayControlPlacer.java | 108 + .../placement/FloatingObjectFootprint.java | 171 ++ .../object/placement/IObjectPlacer.java | 63 + .../object/placement/IPostBlockAccess.java | 38 + .../object/placement/IrisObjectLimit.java | 50 + .../object/placement/IrisObjectPlacement.java | 451 ++++ .../placement/IrisObjectPlacementRunner.java | 43 + .../object/placement/IrisObjectReplace.java | 84 + .../object/placement/IrisObjectVacuum.java | 137 + .../object/placement/IrisSlopeClip.java | 59 + .../object/placement/IrisStiltSettings.java | 47 + .../object/placement/IrisSurfaceSupport.java | 203 ++ .../engine/object/placement/IrisTree.java | 83 + .../engine/object/placement/IrisTreeSize.java | 54 + .../object/placement/IrisVacuumSettings.java | 39 + .../object/placement/ObjectBlockPass.java | 259 ++ .../placement/ObjectModuleCeilingHang.java | 11 + .../object/placement/ObjectPlaceMode.java | 149 ++ .../object/placement/ObjectSpinKernel.java | 165 ++ .../object/placement/PlacementBlock.java | 9 + .../object/placement/PlacementBlockWrite.java | 6 + .../object/placement/PlacementContext.java | 45 + .../object/placement/PlacementFunction.java | 6 + .../object/placement/PlacementLifecycle.java | 35 + .../placement/PlacementLifecycleBuilder.java | 84 + .../PlacementLifecycleDependency.java | 13 + .../object/placement/PlacementLifecycles.java | 43 + .../object/placement/PlacementModule.java | 9 + .../placement/PlacementModuleAnchor.java | 43 + .../placement/PlacementModuleBlocks.java | 18 + .../object/placement/PlacementModuleBore.java | 25 + .../placement/PlacementModuleBounds.java | 43 + .../PlacementModuleCenterHeight.java | 18 + .../placement/PlacementModuleCollision.java | 41 + .../placement/PlacementModuleFloating.java | 10 + .../placement/PlacementModuleHeight.java | 57 + .../placement/PlacementModuleLimits.java | 34 + ...cementModuleNativeStructureProtection.java | 113 + .../placement/PlacementModulePaint.java | 18 + .../placement/PlacementModulePreparation.java | 98 + .../placement/PlacementModuleSlope.java | 72 + .../object/placement/PlacementModuleSnow.java | 45 + .../placement/PlacementModuleStilt.java | 317 +++ .../PlacementModuleSurfaceSupport.java | 67 + .../placement/PlacementModuleVacuum.java | 90 + .../object/placement/PlacementStage.java | 38 + .../object/placement/PlacementState.java | 67 + .../object/prefab/IrisAxisRotationClamp.java | 96 + .../iris/engine/object/prefab/IrisObject.java | 372 +++ .../engine/object/prefab/IrisObjectIO.java | 396 +++ .../IrisObjectPlacementScaleInterpolator.java | 33 + .../object/prefab/IrisObjectRotation.java | 540 ++++ .../engine/object/prefab/IrisObjectScale.java | 417 +++ .../object/prefab/IrisObjectShaping.java | 312 +++ .../object/prefab/IrisObjectTransforms.java | 370 +++ .../object/prefab/IrisObjectTranslate.java | 79 + .../engine/object/prefab/LegacyTileData.java | 476 ++++ .../iris/engine/object/prefab/TileData.java | 278 ++ .../prefab/matter/IrisMatterObject.java | 59 + .../procedural/IrisProceduralBlocks.java | 168 ++ .../procedural/IrisProceduralObjects.java | 93 + .../procedural/IrisProceduralPlacement.java | 48 + .../object/procedural/coral/CoralCanvas.java | 64 + .../procedural/coral/CoralGenerator.java | 263 ++ .../object/procedural/coral/IrisCoral.java | 249 ++ .../coral/IrisCoralBranchAzimuth.java | 33 + .../procedural/coral/IrisCoralForm.java | 39 + .../crystal/CrystalBaseBuilder.java | 49 + .../procedural/crystal/CrystalCanvas.java | 52 + .../procedural/crystal/CrystalGenerator.java | 111 + .../procedural/crystal/CrystalGeometry.java | 84 + .../procedural/crystal/CrystalRole.java | 25 + .../crystal/CrystalShardBuilder.java | 125 + .../procedural/crystal/IrisCrystal.java | 230 ++ .../crystal/IrisCrystalDistribution.java | 30 + .../crystal/IrisCrystalSurface.java | 33 + .../formation/FormationBlockResolver.java | 66 + .../procedural/formation/FormationCanvas.java | 61 + .../formation/FormationGenerator.java | 75 + .../formation/FormationProfiles.java | 57 + .../formation/FormationShapeBuilder.java | 429 +++ .../procedural/formation/IrisFormation.java | 304 +++ .../formation/IrisFormationForm.java | 45 + .../formation/IrisFormationProfile.java | 35 + .../procedural/fungi/FungusCapBuilder.java | 118 + .../procedural/fungi/FungusCellRole.java | 26 + .../procedural/fungi/FungusGenerator.java | 104 + .../procedural/fungi/FungusShelfBuilder.java | 81 + .../procedural/fungi/FungusStemBuilder.java | 95 + .../object/procedural/fungi/IrisFungus.java | 262 ++ .../procedural/fungi/IrisFungusCapShape.java | 35 + .../object/procedural/ruin/IrisRuin.java | 219 ++ .../procedural/ruin/IrisRuinDecorator.java | 60 + .../ruin/IrisRuinDecoratorTarget.java | 31 + .../object/procedural/ruin/IrisRuinForm.java | 35 + .../procedural/ruin/RuinBlockCanvas.java | 107 + .../procedural/ruin/RuinDecoratorApplier.java | 122 + .../object/procedural/ruin/RuinGenerator.java | 199 ++ .../object/procedural/ruin/RuinShapes.java | 146 + .../procedural/tree/IrisProceduralTree.java | 343 +++ .../procedural/tree/IrisTreeAzimuthMode.java | 45 + .../tree/IrisTreeBranchProbability.java | 47 + .../procedural/tree/IrisTreeBranches.java | 131 + .../procedural/tree/IrisTreeCanopy.java | 71 + .../procedural/tree/IrisTreeDecorator.java | 62 + .../tree/IrisTreeDecoratorTarget.java | 45 + .../procedural/tree/IrisTreeFunction.java | 47 + .../object/procedural/tree/IrisTreeLayer.java | 42 + .../procedural/tree/IrisTreeLeafMode.java | 43 + .../object/procedural/tree/IrisTreeModes.java | 30 + .../procedural/tree/IrisTreeProfile.java | 53 + .../procedural/tree/IrisTreeRootStyle.java | 31 + .../tree/IrisTreeSecondaryLeaf.java | 46 + .../procedural/tree/IrisTreeSettings.java | 45 + .../procedural/tree/IrisTreeSubBranches.java | 66 + .../tree/ProceduralTreeGenerator.java | 126 + .../procedural/tree/TreeBlockCanvas.java | 102 + .../procedural/tree/TreeBlockResolver.java | 170 ++ .../procedural/tree/TreeCanopyBuilder.java | 351 +++ .../procedural/tree/TreeDecoratorApplier.java | 280 ++ .../object/procedural/tree/TreeFunctions.java | 197 ++ .../procedural/tree/TreePlausibility.java | 104 + .../object/procedural/tree/TreeProfiles.java | 79 + .../procedural/tree/TreeRootBuilder.java | 154 ++ .../object/procedural/tree/TreeSupport.java | 90 + .../procedural/tree/TreeTrunkBuilder.java | 206 ++ .../engine/object/runtime/IrisEngineData.java | 51 + .../object/runtime/IrisEngineStatistics.java | 67 + .../object/runtime/IrisEngineStreamType.java | 55 + .../object/runtime/IrisEngineValueType.java | 50 + .../engine/object/runtime/StudioMode.java | 67 + .../object/structure/IrisStructure.java | 150 ++ .../structure/IrisStructureAnchorMode.java | 34 + .../structure/IrisStructureCarveShape.java | 36 + .../structure/IrisStructurePlacement.java | 153 ++ .../structure/IrisStructureStiltSettings.java | 33 + .../structure/IrisStructureTerrain.java | 105 + .../structure/IrisStructureTerrainMode.java | 24 + .../object/structure/IrisStructureYBand.java | 34 + .../structure/StructureDistribution.java | 33 + .../jigsaw/IrisJigsawBranchFailurePolicy.java | 12 + .../jigsaw/IrisJigsawCompatibility.java | 12 + .../jigsaw/IrisJigsawConfiguration.java | 71 + .../structure/jigsaw/IrisJigsawConnector.java | 96 + .../structure/jigsaw/IrisJigsawHeightmap.java | 30 + .../jigsaw/IrisJigsawLiquidSettings.java | 15 + .../structure/jigsaw/IrisJigsawMode.java | 12 + .../structure/jigsaw/IrisJigsawPiece.java | 94 + .../jigsaw/IrisJigsawPieceEntry.java | 66 + .../jigsaw/IrisJigsawPieceRules.java | 52 + .../structure/jigsaw/IrisJigsawPool.java | 63 + .../structure/jigsaw/IrisJigsawThemeSet.java | 24 + .../structure/jigsaw/IrisJigsawWorkcell.java | 40 + .../jigsaw/IrisJigsawWorkcellArchetype.java | 88 + .../object/structure/jigsaw/JigsawJoint.java | 30 + .../vanilla/IrisImportedStructureControl.java | 184 ++ .../vanilla/IrisNativeStructure.java | 30 + .../vanilla/IrisNativeStructureDecision.java | 40 + .../IrisStructureSetFrequencyOverride.java | 44 + .../IrisVanillaStructureAdjustment.java | 71 + .../NativeStructureGenerationStatus.java | 26 + .../vanilla/NativeStructureSuppression.java | 12 + .../terrain/IrisBiomeLayerGenerator.java | 360 +++ .../object/terrain/IrisBiomePaletteLayer.java | 165 ++ .../engine/object/terrain/IrisGenerator.java | 258 ++ .../object/terrain/carving/CarveResult.java | 34 + .../object/terrain/carving/CarvingMode.java | 43 + .../object/terrain/carving/CaveResult.java | 36 + .../terrain/carving/IrisCaveAnchorMode.java | 21 + .../terrain/carving/IrisCaveFieldModule.java | 39 + .../terrain/carving/IrisCaveProfile.java | 153 ++ .../carving/IrisCaveProfileSampler.java | 166 ++ .../carving/IrisDimensionCarvingEntry.java | 84 + .../carving/IrisDimensionCarvingResolver.java | 375 +++ .../object/terrain/deposit/IrisBiomeOres.java | 130 + .../deposit/IrisDepositBiomeScope.java | 11 + .../terrain/deposit/IrisDepositGenerator.java | 525 ++++ .../IrisDepositHeightDistribution.java | 13 + .../deposit/IrisDepositPlacementScope.java | 13 + .../terrain/deposit/IrisDepositShape.java | 13 + .../terrain/deposit/IrisDepositVariant.java | 87 + .../terrain/deposit/IrisOreGenerator.java | 81 + .../deposit/IrisOreGeneratorBounds.java | 44 + .../floating/FloatingBottomPaletteMode.java | 33 + .../FloatingIslandBoundarySampler.java | 596 +++++ .../floating/FloatingIslandEdgeProfile.java | 91 + .../floating/FloatingIslandSample.java | 802 ++++++ .../floating/IrisFloatingChildBiomes.java | 376 +++ .../object/terrain/floating/OverrideMode.java | 33 + .../object/terrain/floating/TopShapeMode.java | 33 + .../iris/engine/object/value/IRare.java | 115 + .../iris/engine/object/value/IrisColor.java | 111 + .../engine/object/value/IrisDirection.java | 392 +++ .../engine/object/value/IrisDuration.java | 78 + .../engine/object/value/IrisPosition.java | 69 + .../iris/engine/object/value/IrisRange.java | 59 + .../iris/engine/object/value/IrisRate.java | 57 + .../engine/object/world/IrisEnvironment.java | 36 + .../engine/object/world/IrisTimeBlock.java | 51 + .../iris/engine/object/world/IrisWeather.java | 46 + .../iris/engine/object/world/IrisWorld.java | 65 + .../object/world/IrisWorldBoundary.java | 91 + .../object/world/IrisWorldBoundaryCenter.java | 29 + .../object/world/biome/InferredType.java | 36 + .../engine/object/world/biome/IrisBiome.java | 672 +++++ .../world/biome/IrisBiomeColorRenderer.java | 95 + .../world/biome/IrisBiomeDerivatives.java | 153 ++ .../object/world/biome/IrisBiomeGenLinks.java | 137 + .../world/biome/IrisBiomeGeneratorLink.java | 90 + .../world/biome/custom/IrisBiomeCustom.java | 234 ++ .../biome/custom/IrisBiomeCustomCategory.java | 75 + .../biome/custom/IrisBiomeCustomParticle.java | 69 + .../custom/IrisBiomeCustomPrecipType.java | 33 + .../biome/custom/IrisBiomeCustomSpawn.java | 85 + .../custom/IrisBiomeCustomSpawnType.java | 48 + .../biome/custom/IrisVanillaBiomeTags.java | 185 ++ .../object/world/dimension/IrisDimension.java | 957 +++++++ .../IrisDimensionContractException.java | 25 + .../world/dimension/IrisDimensionMode.java | 43 + .../dimension/IrisDimensionModeType.java | 54 + .../IrisDimensionRuntimeContract.java | 133 + .../world/dimension/IrisDimensionType.java | 104 + .../dimension/IrisDimensionTypeOptions.java | 324 +++ .../object/world/region/IrisRegion.java | 478 ++++ 397 files changed, 56200 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 build.gradle.kts create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle.kts create mode 100644 source-patterns.txt create mode 100644 src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/PlacedObject.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureReachability.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyStatus.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphDiagnostic.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationException.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java create mode 100644 src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java create mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapCompiler.java create mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapMaskSampler.java create mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java create mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java create mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan.java create mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java create mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeIslands.java create mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java create mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/Desc.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFunction.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/Required.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/functions/ComponentFlagFunction.java create mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/functions/LootTableKeyFunction.java create mode 100644 src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompat.java create mode 100644 src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java create mode 100644 src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java create mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationPart.java create mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java create mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java create mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java create mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImage.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMap.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapBinding.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java create mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java create mode 100644 src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java create mode 100644 src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java create mode 100644 src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java create mode 100644 src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java create mode 100644 src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/material/BlockDataMergeSupport.java create mode 100644 src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java create mode 100644 src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeInjector.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeReplacer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModNoiseStyleReplacer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementBiomeInjector.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementRegionInjector.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectReplacer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModRegionReplacer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisInterpolator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisShapedGeneratorStyle.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisStyledRange.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/NoiseStyle.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpression.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionFunction.java create mode 100644 src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionLoad.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/DecayControlPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/FloatingObjectFootprint.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IPostBlockAccess.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectLimit.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/TileData.java create mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/matter/IrisMatterObject.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java create mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java create mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStreamType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineValueType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/StudioMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CarveResult.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IRare.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisColor.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisDuration.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisRange.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisRate.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWorld.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeColorRenderer.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGenLinks.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGeneratorLink.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustom.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionRuntimeContract.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionType.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionTypeOptions.java create mode 100644 src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..9f2a07880 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build/ +.gradle/ diff --git a/README.md b/README.md new file mode 100644 index 000000000..51f9a1f99 --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# Iris default module + +This project owns the 388 built-in Iris feature and setting sources under +`src/main/java/art/arcane/iris/engine`. The files retain their existing packages, behavior, pack +fields and direct dependencies on Iris internals. + +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. + +`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. + +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. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..eae86dccb --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,42 @@ +import org.gradle.jvm.tasks.Jar + +plugins { + base +} + +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) +} + +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", + ) +} + +tasks.named("check") { + dependsOn(checkBuiltins, "builtinSourcesJar") +} + +tasks.named("assemble") { + dependsOn("builtinSourcesJar") +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..b1b8ef56b44f16b14dc800fa8103a6d89abb526f GIT binary patch literal 48462 zcma&NV{|3jwk;gnwr$(CRk3Z`Sy9Ed?Nn^ruGlsztklcC=e7I2x9>aqJFB(1eyu-q z%|3b`eLzVT6buar3JMAc2#EOW{C^)LAZQ?YaW!FjX$1*JIcZUG1yyl%HEd!6f#E+}*Jo*NafvM<-FbE0;-_L#rp}qdn%JEoAVNlEB#J^Oq`mU_#*ev4HLmc> zjXz_hFft^><#omb;Zer-%wm4hxo!wjuX3hBldg(^-RiOleKin`>KHfL3P*{k?(rji(#j2Cc0K509#>qu=-T&B!-5EBi(+ zIuTD-qfcAYgS@`Fb2^-p)4#o6A3z0&fp?~cV=CRsAeCmO4ZQ5kKgC%0el=Q&Rhd#k zaGmAbUW8uKC}-C0s~2);d{;mpsNBx9rn__66W{AhaSvJEK+c0b6ARO+l(CI7E|S5x zhaYP--@F<|99X&)9`q^2(^-Zu^Tzfm)v|gkTJHQ!G*zIg5hzoygeXZoYUEJ;iFkE# zq^r$*c|>Hmn3GapzcDYnjgSFiO^NFyTR5AH#mh%zRToMpEi(r)1$5)h455DuV}0al z!*psWuL@Ke-2gvftfMEGf9YEi^<{B@qru zINgo+YsE&LN?)1qItJoNhISp-fZ86`XR#*6xcvM~_7=JHUX;K9*=Gu5X~ zix|O2d=&C#u_w{=B$eCpJ4L*6i7={j+{Og~`Emz@&98}6s<-p^)`0fXE4cJBP{>)Ltb>JwcqI>yz z0-r-SEhC@p)XOoh|1|XgjFaREHfsu4dAGVz*k#m+V<4 zHqvlud6=;#QWHUoTR_a8Y8+heN?M%n1@0YLiaN@GuOPNd26tik7eKulTx?mM-R!1H znB6+H{^krFXg_b{y=QeCT~qR3T4}l+b!Oz9;~|3*6F<3?#|DYYW&1RtFE)ILZ!`85 zVmvrZkLTzf31unH7Cc5E0iFShqlBE9hgEnRJH1juII*vyp&xd!g`q}X_6WT6E$hhQ`Vdp9k^<)VS?lj!cTh z7FQcQAVA@jL^cXod8cnhKG2TS9+;QU6Kq>}UOY3&TL9gXbl{Fv8@WsF=z7>X0To@$ zY@Oi1uc|MdJ$>Kn{@!g_e`-I&Tpwfg9cr>(iakDX1qciCG_1y!Di#4_)lE!bWJbrp z5aUonb6m-?tiQyR_`P#~SOu+tb_ev6JO>EbEhHK@KbeT0_FDo>dl9bMg)>xmCNB*g zG5NC8ABavuTEZVGW6jP*nAqRt3W?7Iigc-EE~zpNJXRAE z>`~RO9$892j&I1kV;9U)xT8^}IeV`n{}QDtj2o-RBt`DGZUOO;O*lFCb_vpyGh*;95PfeGu!dyrmZ9VJ3Z*upg z6R-3Lr%_55$Hw1^{+KWx0#z`T7O6sXo1h;m?B_ur`X2bFz-SzDrL zpk^@B<+I6imc@7vip za%1jMB7q@1j# zz{u?YojZMW{5j$@h=v4iu2mTu7IzI|)Sxn!74=*J>1a&?Xjt z2%JhSi#4huEcD9qdR9Lj4vwmfnL{%+vQ{f-KgYeqin(OPd8+(g*Uq#TLxQjD4 zLCL%ul(V&PAPlAx8D`@K8Rc`{GPecQ<)d=KWel0ejFeeXGQ6o7601B!!I@RY&eDriADD6wP6DcFKDLZ|lO#YwnrNCZ)zRJpdxX_nPZa4j#$j6v!h|6p!dH}MY6#B`@%6=) z-HigguDACKBULnon^FKzazF|Y1{t(U5rUGnEU|}djVsWT-F>@@mNx?_$kF51QF4C5 zStKR$^3(fw85(4HGs9{mUTtn1)3PwxTN?6}j;32&vJ^BiPHfndLkdU5sOemXKGyCZ z@<7j(k>DNeo~QXyJkFWk!7(y1SB%nA3{v~P2c8ooKa4auM!el!Q_=;lJ$c5ADqE+^ zX8*|A99v;jWPrm(8=h;2ZAj|(vVbx~wQ{N%v;eYLD_BB2LAEWCs@xauyBDl(_HIBvA(XJ7B1E;O zJYCJ8xFJh7f5sr;Y#Wp_`$4Z_H4e9bGiBp?Qu&2!@%Bl2dT5evfFO*^hLDiBu2%Jl z*WAlL5PaQ7skJa(qVysky}DQquZ8U?2@UyJ8zB#=U_E>MgE%XA$CtfL31m$rATJvC zs@!crc0=128PM=Zp zW_5Czv9))n_8Ru?{pxM2F8^r%*O41}RnONbSj*piG%`nyF>6ky=|;B&k8iot(J=kyoU3p<_zaAX(1ijzf*uXA zZ_5jeC{Lks+&QeFIlmzZi3+fsF4fNW^~kvC4Q*T-vrNP!x9xnen12lZQM=1_MdW76LKX(GuW`%T~dM^YX6+ras|Xy4Qhfcq=D+z-P-ea z`T;^gj3+grr3^hwqcNTJErl$z+k>{bYFm6QV%7Opth?9+>|Dn)O@`7F@=j-XSqGPW zjUAu%b3Er@;j1%RZxVDhI3sakg-gvTLOSV7;FV6ED=(5;UG??=WADZw^=$4AyFh#}VMe3afM^pF zFa}-nM8X=K?Jy02*o02@6k{ z%O!hBhjXlXKdhy3A{xGB<##e|j3^dFv~~%v2_H{t(mN7NVeS~51?D&Ozbxa`qwZ_4 z;C#Q#fL1sua%ggucgIEHZtcY=Ag&GgE|h7Q{77D!WUq`;SSGEE0pU;aoj<7-JCAvf zduN=(tx3Mb+EUXKoax|v;8b@#HJ&Q|!g4ryrl|R>WlAv?IH`bk)I24;eE4NIq@SLK31LD4+w~#3iN{=<`<1R!t^$@K5>U6%W=%8_ANuR5 zs(IDuI18ftirTDARnGmF%;iz+4{MlMihJw_l!0Y)NttXC_t+s)V<EY>=Xin*nGX79k6vQ?beRk zy_J>@YSC_gMIG$yjO-y&o>S6xtfT27aSs>e|`x(f2R1bM}*518~%x>1Yct=18b&Z>GiS*>VB$+i2876zL)1cT zN33g=g|>xWE2)dds5m2+8Vy)m-u@NHOlGYxxjam21r1;xWtT0TgqKZrl}*LSkqFt4 zNTI1=3o%C*!-i;iWnlca$stRdwITA1?#fD~5OIqIQAM18BwO_u>hqL&OAANiF|8rG z_IZ9mp?FA-{Gq9+Ky<#NgL1gWJixfO0ziP$4T4G>vsvqC-NQh+A64F4! z-(t<=AbPSG%`mTl6BJtH~3RmvPhQlE-EUkEoBIP(_WMN zK~Fe!siee{M*ns1hkp5(2}vX#%u+T!Abh=<_gEx_QW?h4V@B>uOCEetEe01tl)^`V z(=cOLmuOB;8&&m%_6pcyrt83UXkJ`f9I&0KxY09}RTTs!l^_7~8$tPA%Hm#&$k0;# zF;O0zCGo0IN)X~SyKDoY1DW{Ulce|V9w=ld;U`z$t$>8U!Gu8V?_LAJAudt3eI#*! z2i9~F=kP5m>!bmb%1e~b1!1gz01Py(Yw5gOsFN#o1a&d|=PpgN(#UVreY9^99I0iG zaYE@>(C^V7pnoB~#w$2C1_TIb1N5Je&iao?S2A*TF>@vpHg`31{uk<9{zf_}s&z%dL-Fo)C$yl$%pAdqU!HJgp zh_{m1imk{&{ScyeuziqZHu5cto0{S}^BlXu% z0~;>_yHGd#?Kt8ErxK)z6ojj5SacQobw)-8`c!$HOI*V6eyqou{1Upm%_p!BY^t(D zDtn(oQ!jff`ddGSD;P8Hes!v)OKW-*>mS&#i0ow87;h>(=Cu0>b4)|=EegbN5=Xkh z9Ge13=3z#sk+fT<)PuUUf_%Nx@l!P?t*mni^94p^Ax6b2SVL5U>9dHH!H4DL4}@?@ z?Gpq$C**OmWliYA{5s<|EZ@QI2{-K#brFxfA~AIqq&-WSALHWQ8}%mvaNFasrtnE{ zg=sB4-RF!?)nf{>Wo~kNFgYefoFHBcSr*;iF9B!R=5Np|jv>Uf+mcarG-XGy*kP{z zISVyoPcl_9cOg-@613Qx16OGF#sH&2NTHDa_}vyidmxS~pMfY#AeQvu?AXpWNzi7A z*6&7a7!C9HRU+N{>WYTh0GXoBnXw{lQby^XShgDOw@e8TP}9Y*oFV4MVF#@Ds2A+A zXBEt3a@-IIl)TOcXx;0P;|ihR%Tq@DXeG5p-O{!T7Sg$s1 z8OA4iOx-!>6eK^x{jU-0SvByimK|nZik5zKIvvWVGE)4=x^&5Nx%Qgje!k3VoizaB zip#?$u(R8u{wUFC>tVR8oA%7fs?xEu(gYn>y6BB%vwPR9&RoZE%%RK! zl#Qnkl^+Y*Y4L{Xk(YX&aGj|zSpqO_;C3CTepA!L#4EXO|(eA`Fi+2EQ3!C zo^SpVP?{chQ3uaxu7y>w213e22cdA#l-M2kStPE%sq6vE4M*?3At!S7tIp(tQg(Ml zECjeJw8)*#LYYk_+Txv3rxsH9jJZBRrHp29yJ(^;_PEdn%#U1q`r89}38;XeF{ee& zsZEsUbJ{LtwOjU{vjL(Wvs2!Bx;#^Mzld&TjS@oo3kk=0P36MC-Ie6eHNN&{8b^s z0@jcbdejrrj!>r#Wu=3H1dgjeOI}NkhmE}K+UK&M>%7b!n&{0Zixk%^)6#@=V~IZN zxG>9kl&STQth}qScidfg58d2dF|v_U<@+V^eE@$4x;7oS3)MvWusA?9+%rN>aY#eA_6 zic@S(@e9$9tQM-&-7>X8~#n{5G}nuOu=dSyN+b~jA;_SExZ1H9Q1A}}Rz;XtXUIOP0~ zZzS|~T+%de-nGI$s?wxaJoe+99vmo%xm8o8SNEsAqAE)4LNvHc-1AX24C4k4u3vZmov^_VcxgGxapV(8)_K(^8= z2d{xCrmk(x&514Ly?e{Mf6}h3=oeP7+ZE{%B^c-kK8g0W{tYw3q%zty_Rd@1nbnyHMwabNp-sSyzpV4v>QsnKcQjF67%g~n&3t^1MesVxCzfJ5b=SOI#YfPP^^JGQw=9L1RCMFbrU{8O0LWOUdBK#j&{`tzXX zpe2_{+-8$a+o#%8MUlL4$yK`*--z&3{@Y?jP!m{g5nM+Ht=bD3o}Ok~sBQ_!^!->! z?NDVtyLXzmGYCEmjSCDK*q?Aq1;8fz9l9|z@~l{)R6GfKELc^(nV+TjjI^n0M+S0i z@YOu*Tk>|M6a0_n$(E;#^1Zgif<-CpYiMvyT+Y*9Z?&~IKSwsLa5Q#p_?FqK3lKIw zlp6Hk%lio6)yq>m-`QT2Nj-q!aX7~Hlm^Xh6FNbw z$#ri(Kk*GUHXORu@`aYQU@ zB~S-oIO^~abRPocemkm!W73dbb!j^_xgo_@#W#6p12>w^{){VfeX?U71Xyn9&E zHa1#*!4c;?r}jv7dMN`g#&R_S215)dccDOJr=uz%LIz@zia+LIFjRakROr?P zQ|Xw0Pa8o7&W=fw17`+SqepsQ-Os5v3ncD5|N?N(AHH&`>hLY+CLOluJ z_ErpaT49zK(UcdNmQ%iA-`jS`A_1c|$W86{d_T_T2V-HH3xUqpX0QJSH%i>1i>#vK z&y{;5)^pMB=u;&_DEWakQU>j&+opIrBf~2GUh{`kG{|Z&2Z}5dwG}>Y{W_uQHaR$_ zYH%}$c`CGC-FGCetRdQ@RZ2-%ucC_|R?mHzYEnqC%u9zRBH8wx7po`=EVPMpq+hL2 zTdjVhQn$)++17^cn;<3=bxJy0Z$U;i3AqJMPJO&SuieU&0eVX?eLEEI7Av@#PV_ZQ zsa>I>B5HE996O$z6HyJfhEt^aC><@AnzeN`xs@lv>^pPFtcodrcGyqPSB?#C`Piu0 zh5=hAW|OtT9hs*G?7}@*mG_f7ae@-Nz4{qvne66kco^uD$(JbCo2ttqUm-SMy@kx% z!eDt?5>w5)M!E#C!b#Iu9GqyhUs|QoYWHtR{4espRS-LUt=viY2iygF=-j3kcU#uF z{ka2=zsOuLR}s;&PbbrB`zty&NfZpV*Y;~i*W$EH0JOGS&FMS%VK@)f*%OOrcU3P9 zq4zjhMpx}oc`PWtP!o5Bdlp=(A***TZwVwuZbuB1Pibv5uiHvW{PsE-k5IfCgUz~l z0nMeZU0R>(ajoQ0G%Il)z0BgRR*bsdz5NcqJ<)niF6|PUO0i}<4)q>6wx4K(5>Y_I z4$WMkbCOQFs(krBnl zx85i0*7%Zm(&nKNP?AQ}d~6@?D9dO%@}ouN2paSR;zyUqJuw)1SRy=g%o;g(BD|Bh ztnKV(4fcBgDJ~M@%}n-6ow3xOhnC>C^d?PbS(9=TnO)k5p+W;pu2F4eiG7ts zJVL4M(NiZPQDy*9`H>-P0GWY#=UTnh8feiNF}hCs`8^ZDKy;XIL^9K4Ps&y^#DQSE z-?J z@YOQ9NQi>ZP>^ix5K`R07kWj?`R(B?E*OyR1$Vd;8p%2Y2zEYt4CJM~gVX%MO(E1B zzXhsHn~R1ifq9~dtzuH!*3&W;r`D(Sjrc)m#EI%`Car;CMWcU0c+0r?O!)HpjEvyP zb^;pO-Bn6e-+>dS^o{q&8yEH9v}vuXX`W;NPRlwJdX|59`z?~z{pFE!^u{3k{KkJ55^ zD;F0ldy9W*`d5YP|0(E6|K%}9|D^SIq>wO)4^cJ+yCa&xl*3}hpvcQ1eP_k;@>tz= zOZnw)#fxHc81jPcTM#)jgy|0?n0(jd3IPu-lJ&Tm`#F1)o$GTwYp@dlqy-qiHFCHS zKgikMUx|%x=_%B)>n_y^+HvD2=nP`}-G_0A7)I$yc4`tXS-On8qOkNp>Q^$|Ew%Jm zYx34*(*Z3SF}xw$CA?nG9O3ZH7l)@Dp4EyH>8eXDb}AFz)k*T53iA~gRu&e15u@|% z9Rw?69nQOeJhv^^unjd-VGFwbDzf9K{i(U{xxHyM@-aI+0qP{TU0G~w+Fs>taL#Ik z4+92(Z7n%+okd478;__0GkE`&(C`k8h@?UNnM=F%A~2|TKo)q9F<5`s)KwxJRw~k; z4giS~|8AIVG;rde6I^W6m9fliR^7YT*>&x7wv^?xu(5p45n{|2F>x%?9Jq+~Tqo9# zChbeGm@9!(s;uIKae_4h@`~yIj`Tqct+-M>d>~2PCiQ?UmFUioyy&~h_DTBQ--W|q zqA^UaJMTz4tEggQ*_cQ_LA7j7bLyz8#cpGggy;YBVk!%oSdufoh5-FYAQ)v=d$Bi`G$^~ zm!O;En#M9uCykPzLZ5SHa%?hDHP5P;T4HN0L6J*r9DAvC1WWPOrd{*obfr3yJ?Kl3 z^_6dnXRoi4<$Tr!=4mhHg6ig~BatHR zv%ZMJr-`8w_JyFEzUSQdp0HT>|9QQG?IXj$7Rbx4E)%HauDyY!tedHP ztIbq;D)ckd-eirAHOG7icBH23*ApHA@nG*Jdh}~G?L5C^Xw^+nLWG+>hRi&(fnpY5 z?^hj4si6I{m1u^%i_yk$tco}28X8|}g5*tAEZYF37$f(+xT%XvO^`i^Ig}%cydrwF zlpL!xdO->&@q|8MiJrAxt;z2CP*a+EvV`_2& z<1=p{zjhmmYVkpx#RV=#zuy&7^2Trn=H$nT{OBVF*0z|QH!NxBF%gbqT!BEx zKB!SsSUwSo1Zr?kMM%N)@hG=&m`vRQ6QK6=oIvnUI+|C)dGKM@jNwqG2Xi8;YCUHYRh? zbl@DN-za)+0F9kw>Yv=ioL)01uFp7@AVEB0AH-nmB%j$RC_totFy4BKd;OPCMUMBb zu3oUUK`|{AvkM+@KPZD4Tn$(VlQi&aWV*Uf@DO|FQjLOoVw&C@z~Um*h%Ka-C=n4H z@(Lf&MDJXNS{3Hs@J)11(zo9tGp>wS^b9{Q1WN=Ktn>ZieRZS?k`gb7P4n?cl^7^* zG5-oARAG#i<*z`J0ski%;QCLD-T$AbOHq<{KxIb4=QJRn@MGj=ns0WhZX+uX z=oTjz`o-VviMt1mB0W1vA*7oq1ENz{<*-EU)U;r*ODfV!G-?hdnzhM@rRZ=|qaFTN zX*t~$gc-)M7GS{#34R-n`B)eAPfebN46~61R?j^(Pg3TXR1PyQrO7Mf@xf<3VL0`4 zh(i?-SktJu8Oj?KIy4p@%5ZH;P&p5LB8 z^}7P)9h}vUP+1Hd3nNzNcbR`%1>dSZbWhiXe-CcB+s9e)_w<{bypZ(@cQT`P@ch=d zSOPhExgI31MVFPsClEXe>$~qYQ+d}7(!BE*9y%AjQ47BMDt=#>`1ie)|ES{pFFdHa zI)CK`f3x>)DtZnm!f5=e@g;3iK^jf!RU6hpjYu^V#q0uWLuJ-6={Ua3gDi9#*P7;- z`rm*5)n{2QE{UZ01PVy@_9(amogzzOwYcVgp2>LsJ(}hKbX_!ayZ7=U{!p{BHussVj(W z2z3$zu7h$KK<%}P0YBJ+)0unV*xD&6GusXqs=M=Cl&fP@Ttzfq?>H9TW#qDId+C7? zhD;;HOxDJR4dc_xI7-b6N6nZ@bUWueDk<_9Rju2I*o(i)M0&~%C^ zc)a<25M<^NrsjAccydV2HJu_-1W>b;xrB~Mi@c7FrW-94$-GnKXvF7( zA68!d!gkIo8(URS{(u{zRtrF}B$9@*)KH9POqOW-B$za4Sg-A&PM*on$>$o#L7pH~ z&YW8oJX3T!!@2r4Rr6ac0ZDbtB1b5yc$5}7oZSDvGF0FWTpZ#r7@GfM^MmC-p{9Qj z_JmmlTxO(^(NHqBc$ECU$jQp^;)%xnyr$qvNTd`R@j$8JppDCGQAHQ7?fja9McCUZ^;``VW$1+G#=<;K{_OfH- z_$fp~S3K`;jPNNZnkB@=DFQy3{6+Bq9nOf3~dr4q8zD_t{P4-^%<4kj!U z0aj`=#@G*w?!4fpM? z8Pwb15(Ka*TtDN-2aWK>*hh{R_C}*e*vSTkHdM(ETM!JrJ=1h?(_WL}2p#QXjrKZ_ z0k_yu^;~)#*r>sQP7d_4VBRvWJCzw#TxA{*hktwQI3ST{8{>3$KHJIgMGK6I!d}Q zinmfq&RLRxX8P)_@@vVr0gPu7*)uU<%xS{|Eg;*w1}2=C&?7B zSX?OLt-gZO+<4@tLeF+K0~*|xwMD__KxWgGfsUpj)KyeCM3J-f*uxe|xk;Dlqq%1< zL(PaY@U(>Z#k!C!B45JlmE^~wHSH;r1c^kWTG9_VT~1LN6$a6Yg@kNF?&b0hs+5Dw=0j zR(wcEYmdfgojx+Hzu89*C}4$I7^?^vYKhF(`>=MC)VeeFR}}?j#XeLnp8OhW9%9ND zt6utD8DHnQj5@YJv+$USdN{8apQir2)Z{8_s!BABmG2O#pz5lSh|gf#CI8X4I|U4g zhQwk=VEV+j+-KNxuIk96Bi%^(Sf9}A7o$zHJ5mV~)qP))QQY&^>9}z9z9)PWpw>8T z7#NWNEtnUoUl{DP5(lmy<3;tpLJ3hG|;CGB`3**uH0tf9>;7w;Aq9SRVg1FDpI5y~rY#B|eCNpAXD z9692@_%$t2^nu&4lU~(~_iVf|Cs|mXs-xKlY$-~FZB$!oDK#)JgHZCG)ySDURM=@(i zCpd{Er89|l&)(&5>L6LuWY3yC6)`jPz(Po8pY=AYIBnx3y2Qx6*sT42mpR$zwx!!< zHHCc~tbF^-bje?bo#~Q59Dmw_-VcliCn^FfI*EV)U1NkNA`6Cm=^%j`%M?1Zxa=1U zn#DPNc32&XHHfUfmPx*J+3_GA&g-_pd#wO=Q^5bdhzmm)>s@yO0q|>ROV(hkhJWf@ zqWjI#+9Wx%C+!kp&kxX|XPS5m9CBC&3r>}SwdFd#YF_W78A*CN6mFC)qzOjM);Z&v z#MjdXXMw63v*tbvY+$tDmuHNFunOlRM#qe|eV&|$98!xy{n)-=N?lrkr0_}U^sz|x zs0y);(2Dooa;(9zHzRi=I{GSVcv!6jl%ck@)>JODfR? z%aI)0HvbhzY9K7eYsntq#JvWzj$WCuoyGoPY7;LSPfZlFiWU)X?(-p}s4FXQcpIp00;%Jv;k0t@2vBu4i;rh-?{z}cHTLL9Rz zT8r(1Ws*H~EyH+adP$cGv|7HkeS9p6eOEI*`idH3twkEJ*72|ey4JgISglGV0Vo@qe#)f-=|g%l$S&Onwl@mmdn|sjXXYaQ4MlfzjiK1* zY&hWQyc9?G2}2s1fYnQ}LXpq{!&Kr97d?=a?_xXAU0SXrZE?T+=9os2*v9%Csph*M zW{}m4+PIRmHEI;<=c5$PMrfg#MTs);4Tb_0**o}*cimSWRcxo(;G&&NV+-?W7v*%4ACG#t5J zQP=$g-(mN*;B6s)d9JNkF0#Zz_WA>J;{=2a!IJsiqCV!YLjJ(wUJ`3b$>qcZ!HjDT z2xm;fMSbtJ|3o~tc!jJ+U8a)vX@NcxU8y#u!Puq%R~{sps0msRFO2!GM4}786S7* zxgNmf{q@|Sdnf6_he>gEGX7Hn)uih5nL&&t4`O{?V;;bdl1U~9RAnjNmt~1UPC3mh zrR8ZtHzz1(yOYSK$OjKf;InJ+7mH$WfqI^OG3dhA+S!YmIgRv>2H78?<6A=~%E{ug^P+^b*+f=j32&Nv&Ypq?DcH&Busg^AUDE|p; z8(tQxZs1+0gUX<5~Ah zT0cGckI5%nM~d`uaMJ$o%2bt^##I0UdaQ2>-bpsP4P1Vk8r7EOSr+a!D*Z4shiKFL z35Lvs^i;#;G{%ksUUo8(Nj2DY?u5->J8kqS_#{B`HqS(UkzR|K5&6XI_#FH4?$ znMXeTb$nmr1`|{n*#5H1T%vtU4-H)vrtAchme!ZG#@c+Hrf4uxx$;VU(Dr~N-ich4 zMKpdwot^bPY#kBILFgi?i3W_kV%vn2J+%R5x}TL8I?B~o#VXlmr?i=y`yJi-><;X* zPCDrsU51x;mkr+t18lPs=6)r^gEh2$saaA!qv_< zKQP13J}ptHaUjT_(*x+P}wfV-}57aU3rp#3AB&~e3%y}0ju#22u5@mUIT!GA{* zd%-e2DTmr#$(P6^$&N0oCgR)F9IPR~!Q!x6YI*7dx6LR6n8tj(#1~!0rofeMtT#g* zW%-p@V09>&o>iz0j66K^soJWg(o9#T(8Xx-P3?;J|t~nIDSGPq(?-B zOoNnc5HZhsW(m6!J+yj~kjmjV6GKvhO>%^v5`O2I@4B$Z!~DgelYWdC4P>YfmI$TR zq`atDEhIt5ua)PS;Yz1`FX@3Na6j^uBx_rNKTmgboWGwE6O5;iQiN6Q8>ZX%ApVJS zTEf6oj=@?7klS(JaijG|(gO@dTgxB3#H)4&?+@VWkTc)dl;qK|uv;WRI*cG2`6PiF z4+svy+Bfn&Fs57Jz6i!C(w$w@VWPAbRGak~oN>3vUg|Mmk0NpfURt0*DSJ_e*Gi8I zqshW4F}L&aS8x~4*#{4vOc`gKW99cx*L^69fgPj#?++q9LidItd}<@&#E{ZGz7g|c zFX$uKJ;Qv^NpN*e&EL;l@1br8j8oxO3e`g<911L_jr~Xb0)t$x$A~dFay9(}gt4&L zyb=1<`|)_7(!^xJ14xLBGKXO3`R^_;F01 zG70TiF<5(=pRsJYj!^XjLl_vFJOQPhN#Pkr#G0-m#xG>q)GAHjE4WFhe7Zi83;gte zdDv6+)qrgh3F0}$gPmtb9-Ff1m|xDD$6jX)Dcd5Ms-(@nKM_3)2+hfh6@Cs@-=%Z_ zIinf|ck6rN{EOadGmJ-rzvxZnAL)(mf108HL2v&m)%=a*?3CnX2ZfOQY?ha_11m@UzRqlkhrVbQ@0M(tSSTerx}IH@Dn2={w$iGqU#`v}PuV7I&A9JYNP%sqMn z1bTq*Ok{V>SlVH8H*4X-lO?VzaDQzAaLvc1tTL+To)YOuj^V8mQ?)K-FT(s_!ds-O zeb$rKRR-~g^+_aiGtH6kbJ)!K^ie;ipJ8e;>iy2}73i(1RY-~!(tk2zPj;pwB4k1a zVa~7lF^EE`UH=#eb**88zBH%!WkO0S?_Zu0KpRtXN+XMsAwfT56IZI}&cs+R5N~p3 zlQH7o$(zsQQBPIRmD)i>TfdcgCSKbVVD;VCmO3l1VNbV&rWc9o>Pk>ex!)Nap%NtP z&kKIFMm@k9-HeXj2$((SmG+a-dXvl7q(7n=8)cELHf!@Le+X)=++(}pKC*dcns?>G zVa*fV{2FDIJNaK_jq)WE9MvxiTm6sI%YUn|S=oP0Z`vE#GMZa`4V5byxmv0@8@Zb~ zyBOJuTAG>Im^uIL@!ZrWJy6xL{%n;pEwY87Y^xYSfmmgRcgcEDfz4TJ#{;n|g>8(> zv$(RLnp4oD1Mj>H@ar|0RCy}E{GwvuKOf1FS}O&z-Q)MmCVEK{p~b2xFj@lTn}#s4xg7h+r;n$TZDlT2AXAv z7R^$J?R|*xL^>7HI}e>7{HszA#Y_e8=~8*3zy_J$ejuhByeI0I!w-&%MW7Q-FGMKU z8qPm&IdU3w#^#`d%Vcn&q^w;EEr|w2F@ax^`R;a@p>l`U-T%~f&^`#zG}qdSV)A<0 z^*U=#=#o&gd{o+*s#j$xf+2y^t1Wj9_h}(DNi^aK#jI}z)v1rk-H)gocbgc`wB*?$ zfg~22r!^VEN+n>U8|3{Ebe#!9k|dF8lV*9c&9H~&g|$Ymc-2O^j9w$Q^I)ldd}5zv zQkBFDS2TxDn`p}-{-`br?tUCgyfr0Wbf3QeATbp=9sN|e90U^eVOu0~VT$1A5))@C zPcwzUn7bP^Gd~hLA@8EwiklMmlc^(;uPE%tLecC-iZ$_~jNJnZYn1A%r}=VE(-LG; znh6Q+b;zKz_N7)0SH7t~u#)e>Pr194w7xp;V&CpmJw5j6zBO%yB zjVf*iveYaWlrE~+p8YYym=-QmTd_F!`)ATishn6(oD}hTE2AqnVPF_os`ca^ET@@Z zoo~4YJASOBn<;8#(#3G>n1E)&@JA^3LV7mK^kaJ$((~ASWup3G(%#8O%xFX8XSiN~ zUF0&gDyT`FzIjtA`<-+9RXEKbwu%RtcrG!#-aoN0aj)i z(G|=#b_!z{o1}cIyw#n=j~Ac|NnR@<-CW$c%JFBFTi5JW0BX#4k2o2w{L0EglSN7E zFUcmFVF&U6NBA7!t`Lut>faDk>pW>Lz9BSzsqWvnI<+L#wg=zw+aeL6=70S773#Rq zG@fVM9=1ZibB`>L>hKz>rHG}`pX;dZD>I!_x~u>jsx3;0d$`Q%t7d<8^lkl8w0WZ3 z(HGiok6h^#G2EzIH}G*;!U8FW>@|C+wE+z{@e{wwWEkzUEiT0aDJo2JwZR{zcX$Bz ze2pzE&vKCc6@vE*GIv1LZ=qSg~HR)Jf|ljt#^m2hZF4z|32*7{hd|u`C7{C zjG>}`{SC3Dnc~5%D4yBa!V@}xSBtQ$ZWY^qs3)9jTuIXYMgPF5E0*&A0B(=JEntcVgC%ZO4UKHyuzuSblKNHWJ}OzVpeS z?8|{P8FtkJ=~%YMf1h*@o-YsZkLVQU!43cY~nWEmBt#&Ar%7WClZK8 zSe-!M)B8((tj^wSIm3?e5oe&mQs6BAE#Y7K*^boU^Z#aITL%-H zul5Gx*FKM}n~RnE*Ko3}nXrk8nTw0Ok-d?{|KMda<$n9cFHzkfb4wa&Dp0x>XjayP zg-KZ^Ayey*gb`NecHls@$a-2|Z!Xe^@P`uYYo`Q*jKzDQGPFf^GDQ5rd(-X3n)&f|bD>?`-DktKL<0hWK!cPS>L^@|VH6## zG*0#NtGfzpZpt+e{yL@K$|Lg*JfO%I+hp&kR;NxOJ+y2H49xZA7=^RKObPZi6 zL&R70!l_{PTFcxI#h+WsO^Y<`hE*z1vg9n7nG-6n0xBU8F8yDd}=?${Kl$qim3(S98@^W*vvSs{l zU}!oUIXap-i#nT`er(?avm4Q4-snuM&-cwu#-M{K8n;l1gP$ z3sw?`ls1z%eb%&mNBvLuEci8}-Q`|kUw6;F0-pHb?+A)+BLSn7_@my}6u%J=Ub~(* zU1n~wcfO|73IBZF;|Bhy$0FeO^>lmmZz?ZuZC8$p6<>B{Lsp-*mS05IVU00ergKWv z(LIsLS=?(>QLLQQ?bdTpyO?iiEL`;>(XJw^lA*7FCd|$g@c3VRy#tUf-Lfs*_HNs@ zZQC|>+qT`k+qP}nwz1o`ZNC1_y*J{2=fCentcZ%LwW?M`<;L&dcdwa@4GT@LCkltq=Xfy+OasOLT!lXrqy` zEW9YuDcfQtJ$oJ|Ln|b|q*_a|YPgCbBBfQ|5;-1(P3R`sK~3T`TtVV6yrtDbioJKI zPDV1BAaj#O~V^ll>$# zNC?nv_r5RiH^A2t<)qzcvns9Qd$_UU$`jN;KUSNqMCQiCFCi3A$*D#(v=FXCqz$SB zyC8vjHyJhMy$5kCi}FBy0NdSCJa6{q(|*9I^zwX1NHX*dHOIDB8bsI3_{(*-kkQV@ng|lWd*nWx!(xQ1stGMcRDjH=YUQvY2^uCZuO%-0Jw5az*F1nW_|h zR~z5DT4j&Z7527|#z9b}pmRW}p^|OrU(TWox^&Kn>YUn%%JlZJ^16vzy|O|GnZsf3 zSXEMjOhuYZlh*ikE0&zHt5va@6&GI{1&D+NPop@Tss&f!V4;}nqX@iOvdonoDa}J_ zE-u%qrrUpYVYSGU5NeXJr?#B#3dkObD8uk*U|u*zS;T2YgAk;_kdF0s4A6A*YGO4)#dKwYLQi+*i=C3N85d93 zAe#Lng7EX?@}-FPvIdp0y!`J@^1tg|IHwZ=C-i6LW7u!d>#==7<(?=6?caFCo;)AM zwwV6XHIU7}%D3 z75#&7SiVq=f6k4N*gy{?o~K9`+fsId8Co*62ksPHLm=SB>G)@44I(Fbs1stfE==|e z5WM)k7Hs~OwT#*$%<~0|BEb_6HV0F0=kYy;P zdAZbN(@{*9FL}4bSi-&#J^2;N`G{J?KFD@i^8BEXQq3$Q#~shvw_cx5r%ZlgHz2&Y z*cU<9UD1(G6qg=Yx{LRix``xh^Yi7@j|r7hm00t{(0ei78ZQbt`JV={$XlXvX91YH zxbI<;-YQG@9xrY>Ar~yWklR>hQ-X6TUxD-S!;~b9lu;Tu@f59S=euifnkTO2C*G;S z@TJZ5{$VG<^ThBbq_74=9q9r7DxC6VBngr@olJ}~W87-NEagn(;M*)7Oj2!(TG+}U zsLu!TV4B7DH{}gtanAHawLkpH5_$jk$0~;0`rM1Hjkl;4D-KsjXTl<*z|E`_8Nlb6 zroi&vNu(socja8wZ}9J>;D}esqgs4BR?_u7ZyELz2k%GQjtG%Vx+yeS&QI*AK1Q~e z;1-8)WjT?WqB>et(n%42u5UPI+!F^B7Hx#oW{i;??}{9#vpvk}lwvHPB$=-+pnIAL zGBd3sTO%TRGFw?`Nh>DzU#VeO7C?`w!-QT4ZgBE!WsS1clJ&i=m$ zHn^;?BNx^_wESMCsSKfxi542WFvUJUh%GpT-JP-b+D|wh`H$h4?*AT6uKyK)=>%&^oOXr5Al10+ld z9x<66pEk?hlV|$s!otJ~_Kz3DcB~XFzWq<@HMwvNFc2}VQuS$6g{U$+nN4G0`E zua0)-H1D8k;mm6E{(!pNomCz*qxv$pI3NvG>(+Q4AcJvK#K8 zb9SOKS@GC!pN|JW#<}*37GFj>D1wi~_)k#-N5izNy0%(q7hMm?oL_Ju8jMFGA9bKb zv$!gbC9lC0>Unx?+*3GF(6ZZH<(4j|5-Om02Y2z2IG_&xn+2Z`6;N1An(~^lQwwUQ zOiKj)?fuj7EGlb8nv@wDs4us&o=Bt%l*TAhB{h=R+Pddpm83-ms{V0T&ofYt=D7dS=Kr=V{~wzR|1=j_+3Fh+3mcp0J6k#Z&$+yVt*OJ$s$BYK zRx!5u|IH#%N;9@dV#r@$o(;Dy3GBon{2-)SK+R!>`0yL(nq~lFeelQy_)_BZt2i}m z8rSXb0|MpaMQpG<_IaUCD@=+=`KtLmC}H1)-vV;8Y!fw&`K2B6oou$QOj%XL`Ye$dX*5~GV? zjoCc8{4m*B_lFn=K@#mp@(*Vga>;sjA3Ds|(a_aGGbuFi)9-z>)&hY^h=PM>jvvAt z$Q7Zfbr%lPeu2OFHW3uNyavs`ezAXnB`OuCGx+U1e%!gwF?S3T3XLaG+BzOfiLB-f zLsTI!R2nT{#3)Z+EHpqiKXE$CK-~2S!*Tvgi)l{*o7SZiuHQf&N=jK$gt6|+nF)`Gm z!Txq?dNfctW^}=z-436nDud8w974=Iuf~cqED93ykXqf1w8FZK9fiO>iyHhGH6`Xa zy99CYP)x3@)FSqPdVt-Br1$H%x6;EwpuBzZ?#_D^RUI0KPMzf^_Q2rPhK)0jFB8Xm zlV*;2seylEHqM|s4!E5>k-zx$17R0R2*LcwM(ea^%K>Rf92id$mc6SChy+Lhh?+zh zvO6({dx7GOFjsuW1#TIks9C3Y1NS^K;IL#Bmt5WRAnNcc>QhlO{Vj2vmon)s*asQd z33&IEDekAAXHibwHHW4Kjin6FB;UgbL))#+*%fRgjq!Uy)J$xt^A4P* z=wpGU$DPMXW)DL%DW!nu39E+G5tKB@YM$r#?rOf~PwEaIWOZ?-rZteokPGZsqWYS4;B z|0LjjIbp)2Q9#;HApIi0rAAv&MKYgXU3KhsoOYe|YT)zr{({<}EXL67@nFgE$g8n) zlwsHK7H3m?1l)9j7MVEeKIFU&$Urel=||l_I+%2%vpEWGJ4%Ae=4~9emV-GN((dey zu%{X&7)-JZ@$2L0Yqtni7;-H%fWs%8= z=kT2S6oOA<-_q!hTShh=6tYB`my{cf^+Lx>yzS~3hAy^=8Fn4^M9*a;F$7-pPb`5WTTi>BH<(hQt<2d>L}bEO@qeR~R5CV6M#}U~hOs$t?sI z7o&N-naKA!$TJ z>&^XTo(>zGjv|b*XTI$ut5?7&&KtRH*Xif1`>gBEp7*Joo(B{{&6%EYr?;2euFLC6 zyxINGDCvA&Z9Ke6+p?I9Q!BMcUI`b0h}(?yqWH@VsM zQOR!?^5j*fLK3_B=$34i3+r{u7IgD)M~W2q7y3L-307k;BupXtBuqlRxD3=-rhwa9 z?bS^@iS*Hnd^;p2cOp}nC~VDSN?;3$3z!yI^$)`1W?UAhtCjjqn>M&ph0;8EaiL{z zu|C4KQm1Ko&6~iXk*x&^ph_a+*qDsevtmcT;T0k>1Tvc@2_|YU#phijBjGm~(FAS> zlUlF>J!lV+cX^mbgNt|q+%c)}o#I2L8tL)BII4PpHABevx1oqq4Fk=enLf)lPJppehzt;iO9UQ2qK{ycJZ}25$Em8#QCj@IGeY)Ih;t1C_j5#Indn9> z?q%Mr*&t<`FGYDnXUw!Q9F(&(vc=j2NyA|}`{O%(aBk4&ic|F*CyG^zcJTh7Jbkku znj-MdZ0aPz3?=kXncCW=-<;dP;J9T1y-C;{aJj^)J(P2N6H-0wO?ZvS=U!GHKVCK< z=aWv?u%5>H&8MwXa49`eLmGW<%;nt}*#2=)K*`axE(dLvH|fGa6F34#8tRY?cr_y0 ze3Ys0rp;JgADiP65s|!r+v;Bhhv}`Vm{n>M24Hc%zOJ&UhG2A;(vSJbsM4>fU{u2_ z-6VIhEcV`qxROML_k8tmxBr)-{ z0Nki4Ka!>@`U^UZ)eJ*+dVEKh%hU52puWKbEG44AD>zWsBPQobQCa)OTlz41wS`U5 zA(_e!#MIkQ_D?<^L@2G~TpSiQGc{2i*D?M}9=ed6<%52)rPN_&_Zz}kJyQ*xrss+n z+*}R)Uzw_8MN}8>Nin$jkrHrz;R3n*HT*JD&M9fIRS?wRHq#A#i(f4q5+z;_5Ij)k z55fi>(u^$A=GCiS!o_k6hWVWf;@9>(C^LB-^lw%JYn+7v`}UC04jw=#dbI?>PxGb< z^hYM;a|^$Xv8HwRyEFBlC0EGDeVFD zsI=F15ChE=aHP6tL~Ao9#WHh`H@ZcicgWiJi5Wg12JkaFg6%fLuw^#2^+FGSBYJC) zcLQaBfXhJJeIf<*h>U>kVP9*cRCfKc<$@qO~wd*)<>-)SK6P zJ@I^4#us1Hf$yt#&=?VaIkhDY^^W;!&OFd#L5S3wEK(42b#OVRSI3Yn=DLC>djb3m zOx*FMX7ymI4;B56>=L7Cv?Opmx_j#kUAIX{b-S2c8Z$v=gOMvo?-ij^Qg7+-IsiMdRFM)v7G{O9O zb{zD!lmDA*H)}70ZFQ4xTkLM$F*jknM@CK!9fA;1rEyA1T;kT|rRhl7MQ@3Z8K3<$ zthbXo^c6w1sy3usEhrD|+wtJ{DqW>!SzzMAYG&n5P_48!FI7^!mt^UsJ=Ii%VFz|f zC`{_0n8zVxPB%8P&U9wpG3=awF3lq(pY)ZY+X0iPX>u?nXvOVKqHlZ!kPr!p?==9sB_~DS`Wz) z-C{l?ZU7>v`xhem*b=STWhZXwe7a@WUN>CeYu(sj2^yMe+X__p(O0XKfx z%AXEQxVFsfTzy)ozm#eCQhr*;4iF$jVCn@40VgXeH%1E z29UQ3y$aVZ3TOp-E~*g`Gz^slv`Lf|RO$MFBa@P)tKRuI=cc?XxIqzmXgmw~OWv_3 z79M~sk*g{jtNxD4ShkFGO@d3`N{)-(L`+B$P3o{T)|L%BE`c71nj=koezdtBY4~a%t^5r3-m!3Kj%V`9dB?v%w?BxOI$&~!jUNWa z@o8Q~I6n%f3*aDLLYK<|4FU2X@*``7jnlDRq5+VebLwb4vJVL_1XDYFTUc;$dW3relP0}p?81NZ&{!uRJU{&9)O%uEL4Mkts~ z&T=;)Kjl_c^Tc3YX*8y9Lb`*cpyU^wFHkn{Z--k1SA~|n0bO2_YwyEVv91paW(>>D z5A?fn$`0!!94mEWTUFmE5+yocu&wZDj;aE3+jOFJ95*T%`pKWaqKNiaixt!T^#`@p zHlA$6Fj^5&7!Hb19 zHyE9zQWe<12XmH)8IDIOtwPeM zHRd&LKn-qMRQRtyy5LYzR9#*8JDBD2K-E^^INa=#S{XA+rW5XKtg>7Nn^Of&Vhir! z+P>KycTUF|e~Hw_vAX%ap<+u9o9)jcAVaw~|4zkmS zZa8>nl~i|D8zjQ^%<{;ZR6cbVD>%?nlBzUD&(9h}VOpBkVW!AuVW!MGuz;OfTWE_| z{yi!0mE#74$DH%4$iv357s-5PS(g3aXJUS?=I-+Jz4Y{Czu2{VMepL1!wV0l8b0k) zSH~&|HJ~YYm{WKY&gKO*WNzB=l|JE3C?T`VIh$Fi$wHFx68QWYRy%ziF%z4Zc<{>B zjkGSyv*i{+F*O@tKQ!EDM%7xw!z{Yx)~Woo$kr{Z7+t7ve;X$MoE{R-LVe22TZY;% zOIFYRqSw}4;Mcno^z?O*G8Q`&wbgNV%>E*DX{fnqK*lP#K0dvcU3endLW%GugLOH< z>Y{oG#ECe$UPvO#$t@?@GA5JFE*6oY@?+$jRxnx(BiZ8q{AuRkwymR+;{*D6-bh*) z-5@PC8lo`?K**Ec9*n$U>OJRjK0H$J@vnMoQZa4ti zMegzJ2oft=1Y+aEG$4JE9{t_I{tH*SwKVixk$IyL|hvQq*qu&_4C6X zp>36)v+qAXl|OfXL8koN-RrhNjjA36)N;pjmTkOO>jg}c>35j<2gH)fb7QYv#8VV2-AXJ1-O{Vpi$uIz3lMp3dl`?Wwpp>|6_$}|ROmbQ- z+O3VID2pdMNR%dc(_#%+-P-%bNIb5Irk&d>rOY(_mq8%P;dkWuH0mR4vhl=r?rV5g z%=n2Yz2%@f5#I6!(KxF>D%1-3IyJU|VW-!(l$}cWBQtobb>#9D+>HlD>@kp+qgiCj zU_Y+2nP+9m^gw~vIRygs?R~aXBZ*Vk8cFZj_&b8(pTaY{Y}cTT z*fRuKeL3=89rk16#2TNQ%KL}Ryx)%5M0MHy=A(uL9M*f_;^wBL-FO~J+@|(7I)GQF zGxu8y$fzRDE)xoI0MCR3S^FKd3Mzir$&35HZu)9V$~5*Kk^r{%vt!7ISD#%fswRS1 z7x8ugQ&u(usOPXbN5Z5URhEFc|NLc;g}f4JzVjlUxu&$T#yH-Omy4s=$~b=B<)v}= z;R7RHY}oe#TExRVjM2_)jF*Q3%G{)3ZZqgSTa^}wnjk_InITrx)tW> zN_A5pLZ9CogVv`5^1_9Jm_n4I&Od-1kC6YSPp-Oxyt0!D zIplg&zC_?4NKvoQui_?BUY3EYOP5n0W0#hYf21a%4Fg1xeEs;w-CE2d_X6pd9A`2e zuiIRY)}Lqe0J(eXdpq{`UG}5w@h=I2qwDlnybY&n3-F)3(mWK*z~Y1=sqQ352UCF4 zQlI=T^y5Lp>gG~>1T94`()}Z4=w<|*zIWTL=+#(!PT$k6nPOoI-RVk#s?iWB=$tTc z;v`#9_oLoCy7W1j8Mn^hfr?}kDKcERb3jxH4>hafqve(?N%m6{o48;*Aj`VQb5)Ul zHK-31_Fm*+OH8EXSzh8{$7fljqN=ahTv<75(Rp-SR$Zz#EMGFOcXfT5%J^HHx8x@r zP2)nIWHes~>%OVy%4>O3(0{X?N*ukyQv5>kKb>M|32-D&p%1(V8j7s?3w|Lp63nOV z937ts^a~AioVI92W$?353}~XMK~{A}5JkKH5b=n9Ciq@IDBAB;Z!IUAV+ciiDvH*j zMD^3Dk+a${QM5$azio{#f^OHOx>LnJ+5kbRm4^N`5ii4(4>XD|b?3s1jrWv1Z}MFy zT9v+!?Ds9SiLUpcRnr?JG+C=^SKkC=BwXt~F8Tyir)=)czcAl$Z)2R5pR!H;e=OVl z8*}D=$~ONscK(|=^G~^sSitaqkw<2U?vov$hY7)fa=I8~62|7IuK10w(qZq9BnSjK zt$S9yI^QU{77(-&cteiu27n8-8*tNC&-dMPS#upD2hi$Q=J$O0#Os?xwTN{WtSzZC zp0+5nsTrDO-C3RykP7Y)6z8U{uiQ@973Pg|STBrbPO4R4VU>jA3ZJD%OK)mD`u%Bq zjUA|-$B9L(11X}nY*naJ%@8ESe`WsFWU8vR= z2;2}9@)$?_zbc_riw26%Kg!e8Kd<=z-OEDxpIr0*^LqcyFQ+uzy_6rD_)MF*+Au)L zK+sV!gc8RX!}1A93BeHY86igj>{s@tCS@2Inb@Wg|3Ir$G(TxPHZ`*>y-_zsskEEv zlcqu`YL%;Yn6XuOyEIg6vQ;HLymz>grb&Gw(*q#A5?6USh=@|D2=%(`I*cmsk7f^9^}}P? z?OW5EW$5ivagZURMyiQ!)dSTd0?Cq6Pu{r&OKRfiuu+&nj(M|bhppFk4ze_}sSz1;);PvKNiaE=q^G|5w^Vy2SN zBs0Xts91C^d0dq<=JmXesd8D;1K5UvF9?WTYl6d%lJqXxN`Pj}5LxPgSRE$%)Se9Nn;^;MLmXCiH$)23AiNRlj3 zB5S`@U11=y{xj(rqgS3zSUD^dhUILAwb|IZt>UN#gv=Rm63ig{MK*6HQPQQC{?1ODO*flB7}Q(AO3hFI}(g&O+0tS_v* zssss=fjAF6c7M%h{bJFcbm>-<=R>Xa4X{qGb3|a97zk+R8pO+p(k2^QM<;%(sz0y~ zRB?%#!Lct8vXEtAzqvF2#xo$NsieLB9TCSs^E_?X{@2BD7<@uv#vvJzQhJD^v3!dT zl|$vIA|g+p5nMz|Au5{UAyp|$2kfI)S~hhN0%yOnr(#(o-&bKg$Y+VeF{*sx3Du~N znZWwrE{QHx{GA?2J*uLTQ+AKA)Nbt+N2AXvftlF`pev3SOJ$4`MSDf=HiGkA5i0UO zd~$T7PLbVXMt2^U57wmD5}@X1U>&QO#B&jZ0J18_+exP+Z@5Me9xd0Jbq&L^e7(>X zNNZ(5fx4(0i?cEE=!j+2!b@EfJXIo&j};GwfS*019h#N=Yt|*|0J4`!D5 zN_q7;3^d-)FNmK&7&H^rwGK+yh}q{Hpt?|PFC?Fm#mlG5xknmlrQ>IgB05c3KF~=a zh6K*nAvP~CiOXlXY$wlxYQ8_)WN;>NeiQS5Mb-&Nuox?GER-8$-`li(QhmzUy}Keq zW@+_RPM`C|bx|r{2{VLpv4kQKehI>QOprT%3zknCxVb_F`5u!3W#trOn>06Z6D*XH z=M)M2!jWK4RGLfuttE%E2P@F6hVZljI&jmjn43^ zPJ~{D)br75_H1XB8(ej-Emk3-$#Qk8x9>hEB<9vjxJQ=EG&)&*v=3TD&pvVnxeR-) z?Lb+YlOky39f%jYERz8;%h7@zQH?O%8>!r^nUZ(>IPqq+lbCHA8Ax24#IZ@dwzGe_ zNr{+ocSoD-L2*Xdg%@t^OiJbgq#@1W&4(>T_SLJKpM5HrJSQaRRfbG&uyI9+T~>My zyWR{C12~~%bhg$$vJk%xRx<*^v~v)B^3%hV33i~-tUvA5Sfb|5i=rmc9n>)2!GqKa z^P&<_F>DtK$|77CJ5xuKX-Q%!OtxP3n%EsDQrn82M%6F*?l55XtzSVcMPQG0ZuQjl zmq*Ic&aackwk$S6PqbQ!TT;VJDSX~x&h0RoXfrD8&a{@qUZfVn6$ilU9V(GVzCpk^ zP$Zf;Ui%dnVGK2;ueF6kZ zFhW{mY7j^Tftei%owFtP`AO&4M?tOT( z;Htw$hS6rDA9#f<0l{2DA~U)NOfScqg!^m^q#5Caibizsnh)JfGIIAiSiC=S%J|_X-AWeS|ich7A5v3!>zaS0qG@+}6 zF+61ADkXR}zFbZ1mX?PdOp=@C9DI^|;2Tz^0qedK3>_4z?WYMY85qL(rt=Zq14q`G zmX)L~hGa0K_F1zeK5O`YjYkt&x-#C=rX%}-v%xC}Z95zssU#Mk{YR8Je z@U4Wha=tl!xo6aPg=VsfWT-Uw*s!bATd!Jrcam6JES#?b>09?3j3HtW9zjdZo{@vm z;Qsw!K~TU*LK!uvRJbS;OkNH2Wt%Y^x3I4&v!zodO!!r6#`%hm7yl~tBXG|sE%(t= zztYj^vC$ivB^+7S$l7s@do8-L_omu&g;hi4Q7^#p%DB);DAqKLC_yf{M--fbVCW4Q zpLSAJpyR=Jw|FpZ7!OY9&`o&H;FE5C-006%H7z?V^+c?EUl19l4m+%pxM%W-d$e~- zt(|&Ex@CFK^ihfbnmM|@OUuO+x=YOaa6Up`MZSv=z+ zj&v;Xfs>|(JoZyyf*n#2H&qEvkEBqz1th01TIY?cy1siJEZd%upf04|88q_e^UcqIJI$qO^tX{0Q=;ytn*d0;d>W zpbMg2hvsXQ_P18QOkwPq?4dM+V|(uRBPZ<<$bpw08v0vS$9$VUpbm=Fv(IMqMe~ij zM>0rOq>iZMoC}d%y?jB;97(AMLyv&6Zzi(5LIvB?<#Ywf0)mZ_~Rdangdl z&@8jcCHuwoEo63_;{rqY2HFx=n@YZylX9a} zl&P9Yv{)Lgc|b3Q1o2l|SANshLidoYfmF5?I`bsF`E$9kGP};}K?$qva#L^~CH` z!TFGfb4WF(Bq_ENC#V_OREgx>tR!Qa(Jg2?b%7g;M5AE-&>&(JHfZkcmN2s4eJeN!nCrcl9Way`gTk=o|nGo|BD1pGHLvB0ih$H-WM^@K##RBrgEQ`4$CSNzg z8QjInTy|bpvXE2PqeM9*$mGvZ!Ps7Fn?$@*V_0OIlsGq$7xq#m0A&oC)8WX5OB{I{& z&m4D92ULj=J&5P>4A>lRn(KPS@|aiq-&TfHnOC`uYpkgbZ!za!sgrKX&HmC&DR$Qw znLUwmqe#(ab!;OBsne)NG--Cm>qV#<+25uf(vCyt?AGIMoJse#4t}n3bFn42(girok)X zsLlF0m3f3uPV@^VjN3J zs7vW$dREOUH=t;vnxK-_6qp*ejG&zM*m*>v9wu&xniWe@+eJ-67VZtoVET-b0X5{6 zr(c*Y=7z@KB`=B#zMR8)M_(&sn@t?LtNkyD`lrk0nJapT+`Ued`PVEyOY{v7f2Alh zxP{mY>C3kmqt~@Sx9=weAH3PUD&9e;-4Z?DM%u2JrA~7?nOo3Fg!@?ilHRb~Q9Vh0 zS~k)vttP$Xy9A>{?$-j{oKIM^!~^qOk9nFfO9U;uX<{Z}MGPU&T0}pPw4d7EHF*^c z(1Qo888T#p5hW(|Q-(yg#r6vVzhg0gpd>56bb9oH0wu}%3M)p2fxFLEy>QG4R_-h8 zU+Al?!eBv?3%sHzLA?4>j0E@%7$S|RYf_S$ylY+ z4n%*ot_mG#p83HvVERPUjJRH!Ay-9T%yQe2biJr+b%|?XeE(`??bZyWEqp{h5`F<$ z|26&q>X&o$0crC>TI-zNN~}*w7-kFnefLs z2fQs{{%-wM-9ryBgJ*Iuv&{5yuKy+Eoc^si>??Jju|gyAn_Uf`ajXB1%g`EBtwiQ1 zx^awk%lc*V?-yf2mx&<2oHk?3d{TaxpMu&Sc>d+t2h>+*DNg;iw%P+Pbq56MHt1{8 zuC!j;1YlpBL2hXi-rks7|L=db0Mz7?nWiEF08stMZRP$Sn6!kAqm#as74d%`|J5u1 zZ`hY{-1iNNl z1=2bj@r1^~3~TeQTAAId%fY2ha|!FRU6VMpiAkkk@VViqVwhBxz8SBI0v70InyyD6 z3Bn|Jj3nVomoatTh{xa7jx;yvi_UnW_#l*M<|9E)rOc4j#iVycL>cKHTtp3#k-nKL z+7?|mS#aSINetxl?nE8)%Zyk>!C1k`<{`huyPwZD2`YbK4!99|Okznl56^r1}88nU&cpyn*~f zRP2FGaX0@#FpvKuii!WfqnQ6~#DBA2l_uoxjK6W&?wmdns)%IKg2?m;9KE4d3H+J4 z{P-@21_oU4WQ76zv4`7rf2c8VBqkLlTWX8sn;VP7*r9$|Zvr<123Vyh&st-dNnOt) zxtL4AjW-w3bde9fPrdt&)f0toUJ2&UdD?Duy5Ap7dEF=0V82i93p+Kxkri{*^!QAa z`)V#?MO?Egc}EaN?0rV`N9>*U}noU~6E-WouZiR;Mgh z;i}OVBurvrDpRj7!i%ICbMj)VT&(w5JB7dEWs8$MSfbZaa1D^jw$rlh41JSI!*+g5 zc`HjldKt~dEdKiq-t`OW#SHiFi#h4kU3|pR`S;CF5SvpIp|Cl8#>|qEO zL6o_yj`uN0$wSqXQfj)_qWIKrnS3$j-u8y`GrF8k5xy*m3E_xC>4xG+3@28lsi2dl zG->G?bNPxG)$u+RlKOK*4722EnDvKFTfCP}MVn#i1AP7T_HVVXeMTs4JO zpT_!OPG@)cEQ+es9a7Q~8ZJxuwg`RN6PqI_ZGrR{=g#vc28nWQy+I8dcb5dFR^-u; z&&P%sTVJJ;F`R;9s*$hDbF31St>mkHWdp=P*}5fF!x?lQhPw$TMi}e=#xDm^PWJok zBklIX+F!cN8)z!@No~Er@9ywmEwj?-&7I}xh?Aw0SPtK(3EQ+5LHqwwu+}k1p;#vH zrvh`dw3QgL-4@kIQ!Av--?{@#~s8|+dQ;(;Mo#ndpY6spn{3TJBv8{Ee0%vgX2)N zCCV1=Y(p9TH+hpYR^mG9QF6nF>tHb9wDPpXRlL7F+QvVV*IK(W=+D|wiR-*I;elS7 zY`O=x^{a5b-2CDtug6c%+y!Jb>;Y$1|5k+KbP-$ndnLz+PK~0IJ6_kenCmP!NG!nT z0oX@l4sD#DBU$@kjnc{sh4baeOf!mqY{x0?+@X-P%tFTkGt+fK8Xnl}SW!g#bX7&^ z+2;eo?q}&im*rirs}E*eubvzp8ZZ##(eDL0O^$sfaX!0;rmj^d#vG<0v5$vbadqkM z;c@S>jXq)Rz%lvuo_XtEk0U!0-X%0LG%_Oo&y;sC!y!Vzbv!1e%gjo7+E(!P5CXQg zglw~&%zv|GAITU4^EUXYL*ba5L|+fG{n2f#<$P`;XXQzw!rFG>1xIQtjYXPCx$0Tg z_y1H9*k8*NMu;cG(T9I5k|_z+!6-KvLctWLG?awCF`Wto6>5{_B*kX_J!#TlRfW|Q zTxT2;H#0}=YR;55U1N;$dTp5H%;k}GCmbbyfA00QK5!SnK;wWT_=y7G3YX(F_2ej zekKG-;-FFYlnsInfBS-ue-l(=JyzlnCV;dv+bFa!pd>$1xZyr37BgGGzr|0+^O~0j z15^}t&e-E6dU|#)QNVmuka5beLq1^$=n5hx6Mg@fLV!rjf(f07zjUyE!{MRr^$O81 z9c&-SdtEZ{pn(T}h6ZnUS7wPMBn?d!5HMe!BHRBbb05=@24O?2h_`+1 zSkky=Y6p<;hK&MFs_UV3Pi4-ZFlQ5qOdAaJ4>=1O04Q<~*!bCF?FPS~o{er4?b z@BAktYAQF=_~SF#TF%vAsN~HdgBetV+7Sn}tl<@KS7SOg0f&fC(;da%oL1YWSL+*m zGM#5P_te#*^#`lcd2E#Bzrd<*Ozyihcs6GM{UIN@;iOnS-MRs~qr?3IfIIow<-ibm z1axfeXk3WdOtrvL9~RrkL@RPE27Wm{vO5xg=Y{Si6xRMyB}nHWVL(7VUs(tiyCf+=eFX z^v*e{k1Tj6MkZdZ0LiaYY^zFpCUo+Dxx=bBlNeU*IS#VeeOAzI)Vt^$zh$j^EZMHM z**h+Kz~xZ6N@mz-#ETTbxO`K|Nr-N;@=2jQ#7ZgkFx(W;GWygjB|Jx@jU+qS`t!IrL_@Mh#X_TZx%@ z^4p_*L+-*ol_Bw(5gpCY^}j0qLkVl4eKqJivQEuSwK~_wQU=a?(Pr}B&EB% zySux)K|s1&x?55}O1is2>5>k~O$h(?yyyFj*W>Z~9|mI&_Fz2Mnsd!nbFSyU4NmP* zk_r34gxePNOJ$h6cykvyCw$qW0>}3|r&9U*AFcQWu@^Z90;YM#zVCO^+rx zNH@pXoqevqr|SqP@$wvXr8J@&d_JP>=uXmMSW8G@sN0shx}NXhJ^U;k3^P3*Y9*{X zT_){Q>`WUL%w79gi?=u4Dq=QB^rnC>Qexc!1mCKET58qi_4>ylhJterN@VVP&{9R} zf`VGjgzL=<92XlYXsi4V{!C1%tpasaKFas6LJV)K-=vfm;P_v(pq!FX4Y?&YsVKhO zR%%faHzRDbQ!M3E;64T2WnRzcuczPxKYjJ4E?oK+r6|}!&xa}zY4)CB2A?|sZ9Z0a z|7}5bo3I!eu5axh5J}j*49lzaa_Zc8rw3g>pdb(cSDK@($H8DyJ~4-_*`cwZ$s? ze5h6-?o%Yb`5-tXa|0?FF6Y2tk6?PhbB~VSfa6cTW01)6;9^4dE+jka44m<(+qOx| zS7+%A4{cV1vYAlL_6DE@7TAVxXLfPEJy)0APHnPc=nL6sYxCkc(#=FY#J=VU)@bgA z0_~_L;7&Dz1PtGWxfn&<4}Ma94p>_udw=f*7k4kv58VQ0lC!J^kehlmGtWV4Mi6UiYHz1L*lE`k@;g5_yK$-= zZtu<-NFGqxlm4JpB#T7g%Ex-iNmQO!&y7g$cHfwbO|=&7md}4l4Mn9|n24rEQ^>Ux zYO+gTedMAD(2~_1Q6k*FOpy38A*yn7gLcbXj?+s+U;2tl$BG4xn$@hHmfNzSfuA*V zDR8OI{FbT?yi6r34Q}@hSTAGKo2ggB19-#DmV2x|Zadz2|rHCQV8f=qYq3S-XQKr)V!L{fbjC(JB{i1oZ ziF#JsGKmxT>@0|5a3}*}b2#dWUIr!i`8n>4;r7E*)&qvB!SvEbZkC%_T$i>HF_iTK znSw(apn9nYdcK)KaXd!E__$?es}T}>(H*ztldjGo3~FxJOQHIwDEbA;V7L2u0y+iR zI z`Ta|+1SVzj1fro-ACvhOxw!`lkeVnt+5zUv+2Q>l6W3DEHS!?GkLeUc=jF=*DYi;4 zgAmXvqwtL98S&@oBP*(OL2;6Q!{jJ!x!SIzc(UKP=n25KVnzea3MJKb=3u8Cm>iLlc zo>?@$-95+WQf~)EAZt_5R=Kx&-+eesXf5(h%iWVsgV-k<5sR4Bt?SzA!_Si!Vs17{ z{6tvfF)5Sptk|88Zta~Yi^wNgFB3D>72<4rA$j}O^elvaJgTjo4ShF~YmiNpHeGbr zyKXGp)-!&Ibd!z^zbI+4QbF?)fGbwcwDyLFza9Z}=ghoEC1>_-5DRf*_-4`0`D_3% z-j$9^NUELnMfu|?&hgFGHu3n@;Oi!chfyGFC1tj zysM2L<;pVB&eZILeivP-DG6^E!_0P@Pv$*0)yMcNP8S ztipdgy#t~iDVyOeruzZb?;xzt0NZ53utk9^3ZvN}(iFQco`XI5+!2~Bt*g7s$UI9V zqTk}E=N|5KTZK~u!6+3ngR++0rc2UcL~b2^1ySOpH^5EkBa;19dk^IoLT_D(^eYV? zh)u!~KjQmm97L8GO!T6q$6zM-+4)P@I(QCal||#8B$YWzh+EnD6~{;lGD;KM(2Z~x zbfm^>#(c>3<`9QS(Mb$0_NoT37Om8`p*ft5u4+)-eY&scXqIdG8ph(=r%k3w~PVLOXd zvY%SJgzTUS)}20bSmIE#Ku2ArE#^+hFkz~5s)Jq}y~;DcyBxahE*PlD`+}A(u^rn<&8zczVDn%^A5dk-Vy_mr0qL*uM z+kH(G>dhnCDc>o`r?(AIs+^*rfe)ECTkV3CYD3Q#19fXQhe<>BD4P`WFJ{4fglrGp zMC#o(hLNzR_6BG%EOWFS0kBYlhLR^aX`ly0}L;y&ATq9Kgir+g(JSTR7eC^Kd70rtk@Qwh@u3M8?jc zvgkQ+ER2q@6iY?Es?2yUOPXy52HHmmw09OlCy8i1JSX$cFQ?Kz?WxLaD*;xXXdOZ= zBkjariS2=U=4{ztOD4WdLby%7@-N=%81G7r_onmAC}*~wh&dH`ElcXAaT1YCg!*3c zydPyIQxoLY1}B)t!AYV-sVm|=v@yqXQI~?W4Le?d1`+uZEGOQ|ee*VGf zrT|&74wW?}lFB{`V02N9RseY6=RHwR+vczuOFPU6KW$IutXl`cwNkIGa12qG zrJ%bP3TNk7J?}yS3x6XEWxoN1EKl;n-Jr)OR82@8A-lLcqJ0m!DhivFnJu)P!CIZozRj3Dupfu>UuxP6njtRWN0x(t)#GPjJ(W*QX;@KZebajIc;dm zCW~hL0jRsrD=aVq-P|3Oy{?-lW2lzd!ihrjVFr)oLbOS5oQOiE*S-!;?Lbx&bB@wB zIBCNkoH#5Y8I#5PlHx>EpLUEIfBnTV;pU3R%nfkZ z!YFhE-!>M@7lKEDX})s?nHWmd;*DDNM6GEm7PaY{ePtQ7vU*E6^Yo7t_xmKXg?pIw zLetbL($kGYR?TwDFJ{6?y@??DP->A;k*WI-u5h`r_Fj=a1?c8CaYv_fx+w3Y&sz)# z5l!Eerg8T>?FtY$ym)%@xf}a@V)bx@rCghzp-=;#(K|s@NOO*IZA)NzB23n8Oyp`N z6Y_)!pjq5GpOl;|9mspLVAjuk4Swf>dB>Z+oWGfksTiJHt6LL8{)`TN&}5mlo&S@f zn?k$j;4E88b8ms}U06xznINvR%znonws$*X0nXu~KR;D&0=; zq1MxLBj~1VFmZ3_rpJ&0B|edG0LL4z$TA%JtOE-~IHfCXompV+wy z8-&6rt-RaR;6BG2HZ5IoYkQ!W1K80!*5H1C5|T&@US7!VmLWU9nG%2IR0sf%g(q;p zir%R2#OCiM-FRbfu?u|_l)-Q7I{}F_K#B)nXF9wXSLm-9xO`&}clEL58GaMK6`1Uo zQKob~3zs=o{h-kD;27bhfCkdw{8=X?mD$rB(iIfJLV2z}Inma$btemM>{3VY_dH`c zRmH*W_;0{4Bi*0y!=kq3gCg}!KzsqQv(?<&2%Y|52_E_JZZE7axCF6;pWKz-h9;(1 zFEg|lBDp{TkLtU9pc8X{8!)$h;lT}wYiX`cFvH{sCC$IJ1nrkGsX1R-c54t zLc9jBHVaK(PZqQAK)*w|rQxaCi@4yDsR;BKp_0+QMY4^V@oQdty=y?g5jigp7$EqZ zjDUR~x@7qfAlguTFi<0JZx{E(?05$3ZrE!(`+7JwC(6-O)0zPfL-;9#k~GMZLtGy?nM#)>2+T`kNj ze-Cd%!Vd{3rx0cOIo+1L-plN7F!@)*0?vWum?{xsvwILKF<=UycOWzqNrt^1DAHo{ z&>l4+Ab^}}aY{#leq4;cq6#<-V$Ho7UKVZ81@Wh+CFOY)SxBEZUOMd5^n&4mJBI5y zhiL&%RP$EK=dU%dsx>v_%dKWSAnH{~OU>To6_twC8@+RTFwOV zjN#5sZh{G`WWFrn$+vV8xa_EdxGegTh$iG5fdf8|IkR2eF_u{^F!2%tv7EYty{ytY zfTzxF4)ngPoP_WTG|Fer08u&Q$%>o}_7yWw_VUke{^I-nDIPLL`#{~ep5)0hW*8ez z$=vvIc7ys0bTt^Z4cC$pSAr8jP+)*}S0n5;J4~41b{%cIM*fv_$1_a{7~CzEGF*%a zmo!~DyV(mH=a!>N6aTXY|l>8fd_G+w#(nF|q5jcLBA z13?#dl>PPCA}RNzqD6oVO(@OKym{I-Pa5JmLRwqW$FBiUBnL+P2)@~J(ec|s_sm!R2@$OKicGYN*2GqU(J&T z{Lqn)*=vxuAX1Gv0Dk!C`pCTtlDrGq_gKcHI?^jian>rS^UL?G0{-ilaNK#DTyw56 z{Mo5FbQ?Hew~5Kllovle5o!-n7?EA%~9 z%jQnBip8H@%a9KGo;gZW59-6s%P>_Y62@fk&z9tt_3vec<8wZNl}y-DPVJOG|Iin_ z626Fx(_8z21@R?Y6h3=m$wyZ(m0~u^gGm$C_>_E9bIWd}w}}Fi6`vO0&SEgSdVWB! z70oGSTwI5)%Dq)n3w0Upp_=|g;_;3OZw=}>WJUsdX*M=A4EsAwYD>0ZPrKc^Y`%(P zR4QJgyJNu4aNup&3279U6_ zdbsfLmw#jb+-(ai0SJf=$M4ESh--^XS307Zgwt`pJ8{}aNm%u@LRcdGx zw~H)F7#NIpX{7#kW5V(1H5 zz5AdL#5;!Xs~elu2h{fX{pR6_V=3+&^ruJ{iTx$`s^O_)RYD@?{ol+}(o43PDCFcy z>6@z&ig(9lnQ&Je#^YG*qG0nV5izc-nDi1Oya!vptC5L&xq!LbWas62!Jk9@Hgg$u zcf|NzytpAfC_?Eo)ZG&ywyD+)KyrtAk@F|5=o#Mda4t2W8yW1la)U@5zE9jn2t8L( zX81%5B2%>F4iIQQ*!=|^;t?PSN?@8gFwrSJ@S3$#y8xt&xUbuD-u=7}9#eLWR72-qTT@xu+BTcA6}iClYMq3D|3PS&w~_olnHK zbbUG}X3XIIUV2VpcbYSqR^lWK`E;G4pb|N_JYdhO-P9g;3Pq zx#XGZHE!5Xc?m~}&3$AbIXJZLI=xQV><&VT5CXbQ&*Kz10ue(bo$2A61QOcN*>`p;EOKRNXLPtn*{8w3F-Cleb(>;Dq;Q;C(4 zd?J7xq=(1C&}V+H(IjuWE!QWIPhSF^7YZk!fUfOIo+QzqwU^5k7P>3Y8U%-;?GA!O zHYcntF5ohIP^By2K2uO|W-gA~czK@O*61M(U{K*rXX`j+=FR!L5*bC z8%ZNoC}V;XL!Kpb>sP)JkSj_sf;rwMx2$<+g%bK77T7~8tSw-VD@GV=JA)2g5Hs@& zN(X^2sMAj;J;5fpbBvQ$s%Wr@mKo`t|+60qbQv%_fRc(1N8*2fDS zc~Y)?i3pyo`Y`?2GK=TmHMB1Sk?@)-KhzR}Oj=qWo(Ut-uUx}_lC%xNatZzBfmEBJ zSB2ILfPtS-VxP5RivoeD?|F1}MKFC}S2DXwe+>&i*)@^(pNc<0Ylm@t;ENoizkQkG z#jnpbKyf#qNVcsT*VPwT{GWW9AfDFmg(z^eN2;&JR3~wRYIg?8~`b z6w+Q}ETeZ#j>1Z?z5425VK$AnXI=J;)o?YW1AC@*n=7rc0xy8rmLo~Jcb!bgn3ceG zv1@S2g~rpP*}ia;hD~CRV%Kn2XA_Ux$o_4-22CZ*sM5r!eGy6Peeyw==5WHgAUBr! zfvRYibkq^Pj~pB0`BIi)Xx#xu3H)+%OM`sS+HY@3+2tFUh{#~*CgyA#2A6>lqfn z6S5O{6{Wk3D3`MS+HG^VfwulGBaN;h`#huNIg<4%zjQE;0edb^GBt_26eM9Eg~2<= z%x&8wNd;sz2J(b`T`Vn+b%GZu!pg_&@u44I_b|jc_M^Ast*GX% z~cER`C{E`DzN*%y4r>@ti4A$Le2~6EEK|BE&%nFopIQQ zN!-D9pX<=ija}?3M}Wur)SnR4!Q^=N{TZI>K-5OX+PuZ@ecEdP)O|3 z;Z49IgbEtgSJg(*(Aa^$Aoi=5ZV6^_E4HzP)mn?bbRzqSk-Q@}P! zU^@l7uS{R0FQ1#*uh%#!jP+VDBI7|deK+xz-o;cMwsFQa_N6oU`m|HL^uTLD=QXI? zqFiDND9*>fT!W9Zuh{5;R})jH-(6Au;dQ~kD`bIM)20??E{+DjC_(m7K9a=~L+3%m zmtNX7LSUw(wb78YdD4gQYKDwb0w6BK=Xyc%RRPAvWSvJs>w0h2R385!%w)PxhWr&M01bMie zx>a1ez2u_4;Q$qR#^a%(z`bD;W}PcbW;gZp$;XJ(jj16;20aY3xp5(V_)^EWM`}Gr zK#ADYB0DVWY&9JP_oH)FDL~K(Y0HNT%jo5+7MAC6`q*B*BqP)IfOA zSs1}p4ht#5?g87B?XYTl`HxLvWh($kg4e|Fz2Zvohr;hXR?n)(=s&V%ugp%$J_YTVFooJk<#&j9b704}aM+b!QM* zY2B{6NUDF@2GpzM?B-{6Ghg#rk|qw*Qr=FO%CA^HN`cxwni?*?^I8;o%^2I|#b!@H z!~kFZVrVLm*xR}zG$0!nJB)j{!+gufR3EieNl0$mvb9e%%PXc-huMH^XTw*p?1 zYyBDhW(uaF%N2hMyCTWakzvUi@hY_+R8p{u`b*vcrP^U z_*g|+yWK|d2olI`sQ^ThBwo*25*7;P@yH3tB(f9HU$-isz0RnuWHIEzUyNIb?n@Re zv$Du(b|ul3b3Fq0U>?6%DxBrqHZ@M!(Q9Sr<$XXSD&RZR=lmi8#WaVOpR03FJ!gJX7}xq)vi!L65L~h`COI7w7PQN!xMG^TmKZsOTAK%u z#7EYSymBa>Y&`4@Ffm&lxog|JGhG>BPx$u;Ig zhanra)@5TBV{@8(le)od=MZScTHK2=8cikHIuNW>^0PQLiQ-@U95r?P0sc?spnX8XB-Fwp8ZN9nk*gQNY==j2)0kCP> zDS3wH9LV%ani_3bU2|xy#zAU$rwL<`uAe~6y>{(&G8kQVUiZh>m`rur~bZ0XVL~QQ(q<_ClM)5o8+`+95hA?X0lOj&2f6?i%}xEm~y3R zZA1w3h^*;MJ*GFdRrP9o(a}EeSy$0MRB1H>ND#EI?o(ILX|D1yXsML7Jz;PiQelZ+ zp!i9t0BZQ}Y0c!zH|4A21GdDR7i)Cpg{XY}^=@lm1vWb9>y^p4F^Fj{5|XH~U(`1y zf0U&kUb4c0uQ(#`!MNRwE;%*DP}`saRhM}Q@8)WSInEKkDq_N)ih@A^4cDIuzpTR1 zg1^TRqQx;vVRq~}7XnA(a3&`_p-X}Rp+M!R82&a9yRuU2)qbcH!*(OuBG-ZxL$7^3 zk&b$I^~5I@OdQRRR`nvwa|Z8Ax*#R#RSH|9#$u7?>1oDhG*RHFDlwSr4bi&61QLwz zDLzl|vh{cbR+{+2Riced&uLkYy9`dK_ScE8u`N&ueqg2cUruA%=)P)#35CF58vwV> zIFPBlmMmvWShXzwjAC;X9Q9dnE`&F@@U8Utn=nx1ySEfLX(0((;LiiMhO*{o z332vyIVs;A+_1A?y(oW|?Fl2oUa(^_iON_+oYqiYgd}-iq2eyFl8e*2C7b|Q$7#)w zm1s2=sH^Fdv2u>d+BWU{?4KqFr-5CP>KbEH1xpYDVVij6M-c8AG=ym^@?d!I(P`9u z(W@77VDq{wy0<#R`)C@Tr;x*YPD61$^u=U&KnFrtLk+}c7XYQ}!}&%5t49-o8#I6j z8$BWc@|_PmISg)MZFq}`=(Tu&Y0*gn=!zUT%R6}HnzGC1I3zr#o#GHqMQG@>OzQj7okNAF z(psjhjkl6sE-6TI^GhnVg0K&Qnd~;28l$D{!$=pSZL9m)_hz5f__8{k;McQxsl7yL zoV4+ZL@DetHhsB+u&|Sr*#=j%+t!eitu!F$RMK>tLL_&GeKR_!oe^eQ=FnS3U9fs4 zI?FrCXlH>RT``+eW}G!(+Yec7JR&Y?WJi( zmoa%r*|6?kWI2MyMWFR&UR94W?=gsTJxJ}_*g_YkdUWL!owBrj-lX=Hx;)8+BIbFr zftcCqOWQ7{96mH7cGBrD==xgg7+$j^gyKT_a)O9QZ?{T>TX!jrkd>J#Cm|;2;tO2| z=43{SY5NJhTQKQ*&oeNy$u#WO!de&b$r+usOzH|f+vA&o_9PCcYXVad((7s>b=O!Z zxvTY)LL%1i&SDV@+C7(o`!I)3_ln}{m?q?=Y~@fKh>zj!lY5>N_O3$Ml2U5KPx+(7 zN0LYrf4JaN?NRvbXSVht{+PCc8`(XyfG??_f2D8e;jKH>`WI|T!;WbjqP9zrm*ZR7KW`bM%aMZ4>;lijsSslVlc+pT}&WfxFuQSMv0}uM1%mqJA$7GWa z6pIIode$f6LrBHlm1tMmunGE`=P4W`HIGYvT#t8kYINF0AA{{c=jGrCMA7YO`<&7m znPRW=3T+R(iyAEZD5LAgt+0a^)JQ95Y} zArV<65fxQBr;(Bl?f2HlYs0 ziGdJ%;O|#epl^W;RG_kRG@~>7OHhi=$l8MLJ1b@ZM>7{2pdviba?Qm47dPlXx4gn5 zAS((u#k2^#&-gl#^es}6f5-WyC+g41pS(8g(F7)M06uYiwe0*BfoQ)={+9!*<1+zM zpe4zFKtG#={Y zWh|VWfPQ@cp#n$BpCHi$Fq3A1NJ*f0`j5@bc=iX#zgcbujwXNJ%$8|Sv|Ql8_W^R* zf9Tq6-~sy2ga7Yw^MCDC&}KYbVj#*CIDmc}rk9j|j8g*IG1;2^%l?~tkPAUa! zoPSK-#rj{#|LUpVSk(V~Fn@15{M8crTjX;6d-DGbxPRIH@BK7?9A#=eKOijruWrUa zH|Ben#;-;|-(p?xH>CfwTj$T*@7>LQyk=br|G@pFquD<@LjKJ8-uCLNSK7B=k^Fbg zA3CS~4E^4B>8qpGw|FJ}1N48^U;fBn>u1XM)-XTrI(OM$QvTNt=KtpC^fUK+i;S=aQLge^)V~~G-zzMBoxuDS=O(|*`v;1gKX3c@GJ`*k za60qfF#ev4`Df+EpE=)Gb$=Bt{1(v`f5!Qj&icO6_{Yu)@%|;?4@$*8G>EADkeqE{m7WL`BO#91q`=2-V`_;N1uP(+}zs&l(<<*~)e?RN~b;0jj z5a;|l`5!F*{S5hjw(!SY+EDOI$ls&#chmVlGroU@`a19UEsRQj$M}a?NO>s;-~$;5 R2np~f1o-$>Q}y+){|A@R9n$~+ literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..eb84db68d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..249efbb03 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..a51ec4f58 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 000000000..a480323b7 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +rootProject.name = "IrisModule" + +// Keep the public API discoverable when importing the default module. +includeBuild("../IrisApi") diff --git a/source-patterns.txt b/source-patterns.txt new file mode 100644 index 000000000..149aa02d1 --- /dev/null +++ b/source-patterns.txt @@ -0,0 +1,18 @@ +art/arcane/iris/engine/actuator/** +art/arcane/iris/engine/decorator/** +art/arcane/iris/engine/modifier/** +art/arcane/iris/engine/mode/** +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/StructureAssembler.java +art/arcane/iris/engine/framework/IrisStructureLocator.java +art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +art/arcane/iris/engine/framework/StructureReachability.java +art/arcane/iris/engine/framework/StructurePlacementScope.java +art/arcane/iris/engine/framework/StructurePlacementGrid.java +art/arcane/iris/engine/framework/StructurePlacementMarker.java +art/arcane/iris/engine/framework/StructureVerticalBounds.java +art/arcane/iris/engine/framework/PlacedObject.java +art/arcane/iris/engine/framework/PlacedStructurePiece.java diff --git a/src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java b/src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java new file mode 100644 index 000000000..d420dfc73 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java @@ -0,0 +1,115 @@ +/* + * 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.actuator; + +import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedActuator; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.context.ChunkedDataCache; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterBiomeInject; +import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; +import art.arcane.volmlib.util.scheduling.ChronoLatch; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBiome; + +public class IrisBiomeActuator extends EngineAssignedActuator { + private final RNG rng; + private final ChronoLatch cl = new ChronoLatch(5000); + private final KMap resolvedBiomes = new KMap<>(); + + public IrisBiomeActuator(Engine engine) { + super(engine, "Biome"); + rng = new RNG(engine.getSeedManager().getBiome()); + } + + @BlockCoordinates + @Override + public void onActuate(int x, int z, Hunk h, boolean multicore, ChunkContext context) { + // No catch here: a partial biome write must fail the chunk (EngineAssignedActuator + // rethrows), or the chunk is flagged REAL with default plains columns forever. + PrecisionStopwatch p = PrecisionStopwatch.start(); + int width = h.getWidth(); + int depth = h.getDepth(); + int height = h.getHeight(); + Engine engine = getEngine(); + Mantle mantle = engine.getMantle().getMantle(); + ChunkedDataCache biomeCache = context.getBiome(); + + for (int xf = 0; xf < width; xf++) { + IrisBiome ib; + for (int zf = 0; zf < depth; zf++) { + ib = biomeCache.get(xf, zf); + String key; + + if (ib.isCustom()) { + IrisBiomeCustom custom = ib.getCustomBiome(rng, engine, x + xf, 0, z + zf); + key = getDimension().getLoadKey() + ":" + custom.getId(); + } else { + key = ib.getSkyBiomeKey(rng, engine, x + xf, 0, z + zf); + } + + ResolvedBiome resolved = resolve(key); + PlatformBiome biome = resolved.biome(); + + if (biome != null) { + h.set(xf, 0, zf, xf, height - 1, zf, biome); + } + + mantle.set(x + xf, 0, z + zf, resolved.matter()); + } + } + engine.getMetrics().getBiome().put(p.getMilliseconds()); + } + + /** + * The registry lookup and the biome id only depend on the scatter resolved key, so cache the pair + * instead of paying two string keyed lookups per column. Unresolved biomes are never cached, so a + * biome registered later still resolves. + */ + private ResolvedBiome resolve(String key) { + ResolvedBiome cached = key == null ? null : resolvedBiomes.get(key); + + if (cached != null) { + return cached; + } + + IrisPlatform platform = IrisPlatforms.get(); + PlatformBiome biome = platform.registries().biome(key); + ResolvedBiome resolved = new ResolvedBiome(biome, BiomeInjectMatter.get(platform.biomeWriter().biomeIdFor(key))); + + if (key != null && biome != null) { + resolvedBiomes.put(key, resolved); + } + + return resolved; + } + + private record ResolvedBiome(PlatformBiome biome, MatterBiomeInject matter) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java b/src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java new file mode 100644 index 000000000..2160960ca --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java @@ -0,0 +1,143 @@ +/* + * 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.actuator; + +import art.arcane.iris.engine.decorator.IrisCeilingDecorator; +import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; +import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; +import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedActuator; +import art.arcane.iris.engine.framework.EngineDecorator; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.Getter; + +import java.util.function.Predicate; + +public class IrisDecorantActuator extends EngineAssignedActuator { + private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); + private final RNG rng; + @Getter + private final IrisSurfaceDecorator surfaceDecorator; + @Getter + private final IrisCeilingDecorator ceilingDecorator; + @Getter + private final EngineDecorator seaSurfaceDecorator; + @Getter + private final EngineDecorator seaFloorDecorator; + @Getter + private final EngineDecorator shoreLineDecorator; + private final boolean shouldRay; + + public IrisDecorantActuator(Engine engine) { + super(engine, "Decorant"); + shouldRay = shouldRayDecorate(); + this.rng = new RNG(engine.getSeedManager().getDecorator()); + surfaceDecorator = new IrisSurfaceDecorator(getEngine()); + ceilingDecorator = new IrisCeilingDecorator(getEngine()); + seaSurfaceDecorator = new IrisSeaSurfaceDecorator(getEngine()); + shoreLineDecorator = new IrisShoreLineDecorator(getEngine()); + seaFloorDecorator = new IrisSeaFloorDecorator(getEngine()); + } + + @BlockCoordinates + @Override + public void onActuate(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + if (!getEngine().getDimension().isDecorate()) { + return; + } + + PrecisionStopwatch p = PrecisionStopwatch.start(); + + for (int i = 0; i < output.getWidth(); i++) { + int height; + int realX = Math.round(x + i); + int realZ; + IrisBiome biome, cave; + for (int j = 0; j < output.getDepth(); j++) { + boolean solid; + int emptyFor = 0; + int lastSolid = 0; + realZ = Math.round(z + j); + height = context.getRoundedHeight(i, j); + biome = context.getBiome().get(i, j); + cave = shouldRay ? context.getCave().get(i, j) : null; + + if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) { + continue; + } + + if (height < getDimension().getFluidHeight() && PREDICATE_SOLID.test(output.get(i, height, j)) + && height + 1 < output.getHeight() && B.isWater(output.get(i, height + 1, j))) { + getSeaSurfaceDecorator().decorate(i, j, + realX, Math.round(i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + output, biome, getDimension().getFluidHeight(), getEngine().getHeight()); + getSeaFloorDecorator().decorate(i, j, + realX, realZ, output, biome, height + 1, + getDimension().getFluidHeight() + 1); + } + + if (height == getDimension().getFluidHeight()) { + getShoreLineDecorator().decorate(i, j, + realX, Math.round(x + i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + output, biome, height, getEngine().getHeight()); + } + + if (height >= 0 && height < output.getHeight()) { + getSurfaceDecorator().decorate(i, j, realX, realZ, output, biome, height, getEngine().getHeight() - height); + } + + + if (cave != null && cave.getDecorators().isNotEmpty()) { + for (int k = Math.min(height, output.getHeight() - 1); k > 0; k--) { + solid = PREDICATE_SOLID.test(output.get(i, k, j)); + + if (solid) { + if (emptyFor > 0) { + getSurfaceDecorator().decorate(i, j, realX, realZ, output, cave, k, lastSolid); + getCeilingDecorator().decorate(i, j, realX, realZ, output, cave, lastSolid - 1, emptyFor); + emptyFor = 0; + } + lastSolid = k; + } else { + emptyFor++; + } + } + } + } + } + + getEngine().getMetrics().getDecoration().put(p.getMilliseconds()); + + } + + private boolean shouldRayDecorate() { + return false; // TODO CAVES + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java b/src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java new file mode 100644 index 000000000..879772ed7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java @@ -0,0 +1,261 @@ +/* + * 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.actuator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedActuator; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.util.project.context.ChunkedDataCache; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import lombok.Getter; + +public class IrisTerrainNormalActuator extends EngineAssignedActuator { + private static final PlatformBlockState AIR = B.getState("AIR"); + private static final PlatformBlockState BEDROCK = B.getState("BEDROCK"); + private static final PlatformBlockState LAVA = B.getState("LAVA"); + private static final PlatformBlockState GLASS = B.getState("GLASS"); + private static final PlatformBlockState CAVE_AIR = B.getState("CAVE_AIR"); + @Getter + private final RNG rng; + @Getter + private int lastBedrock = -1; + + public IrisTerrainNormalActuator(Engine engine) { + super(engine, "Terrain"); + rng = new RNG(engine.getSeedManager().getTerrain()); + } + + @BlockCoordinates + @Override + public void onActuate(int x, int z, Hunk h, boolean multicore, ChunkContext context) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + + for (int xf = 0; xf < h.getWidth(); xf++) { + terrainSliver(x, z, xf, h, context); + } + + getEngine().getMetrics().getTerrain().put(p.getMilliseconds()); + } + + /** + * This is calling 1/16th of a chunk x/z slice. It is a plane from sky to bedrock 1 thick in the x direction. + * + * @param x the chunk x in blocks + * @param z the chunk z in blocks + * @param xf the current x slice + * @param h the blockdata + */ + @BlockCoordinates + public void terrainSliver(int x, int z, int xf, Hunk h, ChunkContext context) { + terrainSliverOptimized(x, z, xf, h, context); + } + + @BlockCoordinates + private void terrainSliverOptimized(int x, int z, int xf, Hunk h, ChunkContext context) { + int chunkHeight = h.getHeight(); + int chunkDepth = h.getDepth(); + IrisDimension dimension = getDimension(); + IrisData data = getData(); + IrisComplex complex = getComplex(); + RNG localRng = rng; + int fluidHeight = dimension.getFluidHeight(); + int clampedFluidHeight = Math.min(chunkHeight, fluidHeight); + boolean bedrockEnabled = dimension.isBedrock(); + boolean hideOres = dimension.isHideOresForHiddenOre(); + ChunkedDataCache biomeCache = context.getBiome(); + ChunkedDataCache regionCache = context.getRegion(); + ChunkedDataCache fluidCache = context.getFluid(); + ChunkedDataCache rockCache = context.getRock(); + int realX = xf + x; + UpperDimensionContext upperContext = getEngine().getUpperContext(); + // Dimension-level ore lookups are chunk-invariant; resolving them per column paid + // four accessor chains times 256 per chunk for constants. + KList dimensionSurfaceOres = hideOres ? null : dimension.getSurfaceOreGenerators(); + KList dimensionUndergroundOres = hideOres ? null : dimension.getUndergroundOreGenerators(); + IrisOreGeneratorBounds dimensionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getSurfaceOreGeneratorBounds(); + IrisOreGeneratorBounds dimensionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getUndergroundOreGeneratorBounds(); + + for (int zf = 0; zf < chunkDepth; zf++) { + int realZ = zf + z; + IrisBiome biome = biomeCache.get(xf, zf); + IrisRegion region = regionCache.get(xf, zf); + int he = Math.min(chunkHeight, context.getRoundedHeight(xf, zf)); + int hf = Math.max(clampedFluidHeight, he); + if (hf < 0) { + continue; + } + + int topY = Math.min(hf, chunkHeight - 1); + PlatformBlockState fluid = fluidCache.get(xf, zf); + PlatformBlockState rock = rockCache.get(xf, zf); + PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ); + KList biomeSurfaceOres = hideOres ? null : biome.getSurfaceOreGenerators(); + KList regionSurfaceOres = hideOres ? null : region.getSurfaceOreGenerators(); + KList biomeUndergroundOres = hideOres ? null : biome.getUndergroundOreGenerators(); + KList regionUndergroundOres = hideOres ? null : region.getUndergroundOreGenerators(); + IrisOreGeneratorBounds biomeSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getSurfaceOreGeneratorBounds(); + IrisOreGeneratorBounds regionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getSurfaceOreGeneratorBounds(); + IrisOreGeneratorBounds biomeUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getUndergroundOreGeneratorBounds(); + IrisOreGeneratorBounds regionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getUndergroundOreGeneratorBounds(); + boolean hasSurfaceOres = biomeSurfaceOreBounds.hasOres() || regionSurfaceOreBounds.hasOres() || dimensionSurfaceOreBounds.hasOres(); + boolean hasUndergroundOres = biomeUndergroundOreBounds.hasOres() || regionUndergroundOreBounds.hasOres() || dimensionUndergroundOreBounds.hasOres(); + KList blocks = null; + KList fblocks = null; + + for (int i = topY; i >= 0; i--) { + if (i == 0 && bedrockEnabled) { + h.setRaw(xf, i, zf, BEDROCK); + lastBedrock = i; + continue; + } + + PlatformBlockState ore = null; + if (hasSurfaceOres) { + if (biomeSurfaceOreBounds.contains(i)) { + ore = generateOres(biomeSurfaceOres, realX, i, realZ, localRng, data); + } + if (ore == null && regionSurfaceOreBounds.contains(i)) { + ore = generateOres(regionSurfaceOres, realX, i, realZ, localRng, data); + } + if (ore == null && dimensionSurfaceOreBounds.contains(i)) { + ore = generateOres(dimensionSurfaceOres, realX, i, realZ, localRng, data); + } + } + if (ore != null) { + h.setRaw(xf, i, zf, ore); + continue; + } + + if (i > he && i <= hf) { + int fdepth = hf - i; + if (fblocks == null) { + fblocks = biome.generateSeaLayers(realX, realZ, localRng, hf - he, data); + } + + if (fblocks.hasIndex(fdepth)) { + h.setRaw(xf, i, zf, fblocks.get(fdepth)); + } else { + h.setRaw(xf, i, zf, fluid); + } + continue; + } + + if (i <= he) { + int depth = he - i; + if (depth == 0 && mappedSurfaceBlock != null) { + h.setRaw(xf, i, zf, mappedSurfaceBlock); + continue; + } + if (blocks == null) { + blocks = biome.generateLayers(dimension, realX, realZ, localRng, he, he, data, complex); + } + + if (blocks.hasIndex(depth)) { + h.setRaw(xf, i, zf, blocks.get(depth)); + continue; + } + + if (hasUndergroundOres) { + if (biomeUndergroundOreBounds.contains(i)) { + ore = generateOres(biomeUndergroundOres, realX, i, realZ, localRng, data); + } + if (ore == null && regionUndergroundOreBounds.contains(i)) { + ore = generateOres(regionUndergroundOres, realX, i, realZ, localRng, data); + } + if (ore == null && dimensionUndergroundOreBounds.contains(i)) { + ore = generateOres(dimensionUndergroundOres, realX, i, realZ, localRng, data); + } + } + + if (ore != null) { + h.setRaw(xf, i, zf, ore); + } else { + h.setRaw(xf, i, zf, rock); + } + } + } + + if (upperContext != null) { + int rawUpperSurface = upperContext.getUpperSurfaceY(realX, realZ); + int upperGap = dimension.getUpperDimensionGap(); + int upperSurfaceY = Math.max(rawUpperSurface, he + upperGap); + + if (upperSurfaceY < chunkHeight - 1) { + IrisBiome upperBiome = upperContext.getUpperBiome(realX, realZ); + PlatformBlockState upperRock = upperContext.getRockBlock(realX, realZ); + PlatformBlockState upperMappedSurface = upperContext.getSurfaceBlock(realX, realZ); + int upperThickness = chunkHeight - 1 - upperSurfaceY; + KList upperBlocks = upperBiome != null + ? upperBiome.generateLayers(upperContext.getDimension(), + realX, realZ, localRng, upperThickness, upperThickness, + upperContext.getData(), complex) + : null; + + for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { + if (y == chunkHeight - 1 && bedrockEnabled) { + h.setRaw(xf, y, zf, BEDROCK); + continue; + } + if (y == upperSurfaceY && upperMappedSurface != null) { + h.setRaw(xf, y, zf, upperMappedSurface); + continue; + } + int depthFromFace = y - upperSurfaceY; + if (upperBlocks != null && upperBlocks.hasIndex(depthFromFace)) { + h.setRaw(xf, y, zf, upperBlocks.get(depthFromFace)); + } else { + h.setRaw(xf, y, zf, upperRock); + } + } + } + } + } + } + + private PlatformBlockState generateOres(KList oreGenerators, int x, int y, int z, RNG rng, IrisData data) { + if (oreGenerators == null || oreGenerators.isEmpty()) { + return null; + } + + int oreCount = oreGenerators.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = oreGenerators.get(oreIndex); + PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); + if (ore != null) { + return ore; + } + } + + return null; + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java new file mode 100644 index 000000000..b9407e23b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -0,0 +1,536 @@ +/* + * 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.decorator; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +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.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.math.RNG; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockSupport; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.MultipleFacing; + +final class DecoratorCore { + + private static final long SEED_OFFSET = 29356788L; + private static final long PART_FACTOR = 10439677L; + private static final String WEEPING_VINES = "minecraft:weeping_vines"; + private static final String WEEPING_VINES_PLANT = "minecraft:weeping_vines_plant"; + private static final String TWISTING_VINES = "minecraft:twisting_vines"; + private static final String TWISTING_VINES_PLANT = "minecraft:twisting_vines_plant"; + private static volatile PlatformBlockState weepingVines; + private static volatile PlatformBlockState weepingVinesPlant; + private static volatile PlatformBlockState twistingVines; + private static volatile PlatformBlockState twistingVinesPlant; + + static final ThreadLocal SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new); + + static final class PlaceOpts { + boolean caveSkipFluid; + boolean underwater; + int fluidHeight; + + void reset() { + caveSkipFluid = false; + underwater = false; + fluidHeight = 0; + } + } + + static long partSeed(long baseSeed, int partOrdinal) { + return baseSeed + SEED_OFFSET - (partOrdinal * PART_FACTOR); + } + + static long partSeed(long baseSeed, IrisDecorationPart part) { + return partSeed(baseSeed, part.ordinal()); + } + + static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG, + RNG colRng, IrisData data, double realX, double realZ) { + IrisDecorator[] bucket = biome.getDecoratorBucket(part); + if (bucket.length == 0) { + return null; + } + + IrisDecorator picked = null; + int count = 0; + + for (IrisDecorator d : bucket) { + try { + if (d.passesChanceGate(gRNG, realX, realZ, data)) { + count++; + if (count == 1 || colRng.nextInt(count) == 0) { + picked = d; + } + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + return picked; + } + + private static String topHalfValue(String half) { + return half.equals("upper") || half.equals("lower") ? "upper" : "top"; + } + + private static String bottomHalfValue(String half) { + return half.equals("upper") || half.equals("lower") ? "lower" : "bottom"; + } + + static void placeSurfaceSingle(IrisDecorator decorator, + int x, int z, int realX, int height, int realZ, + Hunk data, RNG rng, IrisData irisData, + boolean underwater, boolean caveSkipFluid, EngineMantle mantle) { + if (height < 0 || height >= data.getHeight()) { + return; + } + + PlatformBlockState bdx = data.get(x, height, z); + PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + + if (!underwater && !canGoOn(bd, bdx) + && !decorator.isForcePlace() && decorator.getForceBlock() == null) { + return; + } + + if (decorator.getForceBlock() != null) { + if (caveSkipFluid && B.isFluid(bdx)) { + return; + } + data.set(x, height, z, fixFacesForHunk( + decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle)); + } + + if (!decorator.isForcePlace()) { + if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) { + return; + } + if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) { + return; + } + } + + String half = bd == null ? null : IrisProceduralBlocks.propertyValue(bd, "half"); + if (half != null) { + int lowerY = height + 1; + int upperY = height + 2; + if (!canPlaceTwoBlockPlant(data, x, z, lowerY, upperY, caveSkipFluid)) { + return; + } + + try { + PlatformBlockState upper = bd.withProperty("half", topHalfValue(half)); + PlatformBlockState lower = fixFacesForHunk( + bd.withProperty("half", bottomHalfValue(half)), + data, x, z, realX, lowerY, realZ, mantle); + data.set(x, lowerY, z, lower); + data.set(x, upperY, z, upper); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + return; + } + + int targetY = height + 1; + if (targetY < data.getHeight() && B.isAir(data.get(x, targetY, z))) { + data.set(x, targetY, z, fixFacesForHunk(bd, data, x, z, realX, targetY, realZ, mantle)); + } + } + + private static boolean matchesPalette(PlatformBlockState[] palette, PlatformBlockState surface) { + for (int i = 0; i < palette.length; i++) { + if (palette[i].equals(surface)) { + return true; + } + } + + return false; + } + + static void placeSingleAt(IrisDecorator decorator, int x, int z, + int realX, int height, int realZ, Hunk data, + RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) { + PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + if (bd == null) { + return; + } + if (applyFixFaces) { + bd = fixFacesForHunk(bd, data, x, z, realX, height, realZ, mantle); + } + data.set(x, height, z, bd); + } + + static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ, + int height, int max, Hunk data, + RNG rng, IrisData irisData, PlaceOpts opts) { + if (height < 0 || height >= data.getHeight()) { + return; + } + + int effectiveMax = max; + if (opts.underwater && height < opts.fluidHeight) { + effectiveMax = opts.fluidHeight; + } + + int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax); + + if (stack == 1) { + int targetY = height + 1; + if (targetY >= data.getHeight()) { + return; + } + + PlatformBlockState existing = data.get(x, targetY, z); + if (!canReplaceStackTarget(existing, opts.underwater) + || (opts.caveSkipFluid && B.isFluid(existing))) { + return; + } + + PlatformBlockState block = decorator.pickBlockDataTop(rng, irisData, realX, realZ); + if (block == null || (!opts.underwater && !canGoOn(block, data.get(x, height, z)))) { + return; + } + + block = stackedVineBlock(block, stack, 0); + data.set(x, targetY, z, block); + return; + } + + PlatformBlockState bdx = data.get(x, height, z); + + for (int i = 0; i < stack; i++) { + int h = height + i; + double threshold = ((double) i) / (stack - 1); + PlatformBlockState bd = threshold >= decorator.getTopThreshold() + ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) + : decorator.pickBlockData(rng, irisData, realX, realZ); + + if (bd == null) { + break; + } + + if (i == 0 && !opts.underwater && !canGoOn(bd, bdx)) { + break; + } + + if (opts.underwater && height + 1 + i > opts.fluidHeight) { + break; + } + + if (height + 1 + i >= data.getHeight()) { + break; + } + + PlatformBlockState existing = data.get(x, height + 1 + i, z); + if (!canReplaceStackTarget(existing, opts.underwater) + || (opts.caveSkipFluid && B.isFluid(existing))) { + break; + } + + if (IrisProceduralBlocks.materialKey(bd).equals("minecraft:pointed_dripstone")) { + bd = dripstoneBlock(stack, i, "up"); + } + + bd = stackedVineBlock(bd, stack, i); + data.set(x, height + 1 + i, z, bd); + } + } + + static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ, + int height, int minHeight, Hunk data, + RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) { + if (height < 0 || height >= data.getHeight()) { + return; + } + + int stack = computeStack(decorator, rng, realX, realZ, irisData, max); + + if (stack == 1) { + if (opts.caveSkipFluid && B.isFluid(data.get(x, height, z))) { + return; + } + PlatformBlockState block = decorator.pickBlockDataTop(rng, irisData, realX, realZ); + if (block == null) { + return; + } + block = stackedVineBlock(block, stack, 0); + data.set(x, height, z, fixFacesForHunk(block, data, x, z, realX, height, realZ, mantle)); + return; + } + + for (int i = 0; i < stack; i++) { + int h = height - i; + if (h < 0 || h < minHeight) { + break; + } + + double threshold = ((double) i) / (double) (stack - 1); + PlatformBlockState bd = threshold >= decorator.getTopThreshold() + ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) + : decorator.pickBlockData(rng, irisData, realX, realZ); + + if (bd == null) { + break; + } + + if (IrisProceduralBlocks.materialKey(bd).equals("minecraft:pointed_dripstone")) { + bd = dripstoneBlock(stack, i, "down"); + } + + bd = stackedVineBlock(bd, stack, i); + if (opts.caveSkipFluid && B.isFluid(data.get(x, h, z))) { + break; + } + data.set(x, h, z, fixFacesForHunk(bd, data, x, z, realX, h, realZ, mantle)); + } + } + + static void placeFloatingSimple(IrisDecorator decorator, + int xf, int zf, int realX, int realZ, + int height, int max, Hunk data, + RNG rng, IrisData irisData) { + PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + if (bd == null) { + return; + } + + String half = IrisProceduralBlocks.propertyValue(bd, "half"); + if (half != null) { + int lowerY = height + 1; + int upperY = height + 2; + if (max <= 2 || !canPlaceTwoBlockPlant(data, xf, zf, lowerY, upperY, false)) { + return; + } + + try { + PlatformBlockState upper = bd.withProperty("half", topHalfValue(half)); + PlatformBlockState lower = bd.withProperty("half", bottomHalfValue(half)); + data.set(xf, lowerY, zf, lower); + data.set(xf, upperY, zf, upper); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + return; + } + + if (max > 1 && height + 1 < data.getHeight()) { + data.set(xf, height + 1, zf, bd); + } + } + + static int placeFloatingStacked(IrisDecorator decorator, + int xf, int zf, int realX, int realZ, + int height, int max, Hunk data, + RNG rng, IrisData irisData) { + int stack = decorator.getHeight(rng, realX, realZ, irisData); + if (decorator.isScaleStack()) { + stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); + } else { + stack = Math.min(max, stack); + } + + int placed = 0; + for (int i = 0; i < stack; i++) { + int h = height + 1 + i; + if (h >= height + max || h >= data.getHeight()) { + break; + } + double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1); + PlatformBlockState bd = threshold >= decorator.getTopThreshold() + ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) + : decorator.pickBlockData(rng, irisData, realX, realZ); + if (bd == null) { + break; + } + bd = stackedVineBlock(bd, stack, i); + data.set(xf, h, zf, bd); + placed++; + } + return placed; + } + + static PlatformBlockState fixFacesForHunk(PlatformBlockState b, Hunk hunk, int rX, int rZ, + int x, int y, int z, EngineMantle mantle) { + if (!B.isVineBlock(b)) { + return b; + } + DecoratorPlatformHooks.FaceFixer fixer = DecoratorPlatformHooks.faceFixer(); + if (fixer != null) { + return fixer.fixFaces(b, hunk, rX, rZ, x, y, z, mantle); + } + BlockData rawB = (BlockData) b.nativeHandle(); + BlockData cloned = rawB.clone(); + MultipleFacing data = (MultipleFacing) cloned; + data.getFaces().forEach(f -> data.setFace(f, false)); + + boolean found = false; + for (BlockFace f : BlockFace.values()) { + if (!f.isCartesian()) { + continue; + } + int yy = y + f.getModY(); + + PlatformBlockState rs = null; + if (mantle != null) { + rs = mantle.getMantle().get(x + f.getModX(), yy, z + f.getModZ(), PlatformBlockState.class); + } + BlockData r = rs == null ? (BlockData) EngineMantle.AIR.nativeHandle() : (BlockData) rs.nativeHandle(); + if (r.isFaceSturdy(f.getOppositeFace(), BlockSupport.FULL)) { + if (data.getAllowedFaces().contains(f)) { + found = true; + data.setFace(f, true); + } + continue; + } + + int xx = rX + f.getModX(); + int zz = rZ + f.getModZ(); + if (xx < 0 || xx > 15 || zz < 0 || zz > 15 || yy < 0 || yy >= hunk.getHeight()) { + continue; + } + + r = (BlockData) hunk.get(xx, yy, zz).nativeHandle(); + if (r.isFaceSturdy(f.getOppositeFace(), BlockSupport.FULL)) { + if (data.getAllowedFaces().contains(f)) { + found = true; + data.setFace(f, true); + } + } + } + if (!found) { + BlockFace fallback = data.getAllowedFaces().contains(BlockFace.DOWN) ? BlockFace.DOWN : BlockFace.UP; + if (data.getAllowedFaces().contains(fallback)) { + data.setFace(fallback, true); + } + } + return BukkitBlockState.of(cloned); + } + + static boolean canGoOn(PlatformBlockState decorator, PlatformBlockState surface) { + if (!B.canPlaceOnto(decorator, surface)) { + return false; + } + DecoratorPlatformHooks.SurfaceSturdiness sturdiness = DecoratorPlatformHooks.surfaceSturdiness(); + if (sturdiness != null) { + return sturdiness.canGoOn(surface); + } + return ((BlockData) surface.nativeHandle()).isFaceSturdy(BlockFace.UP, BlockSupport.FULL); + } + + static boolean isValidShorelineSupport(IrisDecorator decorator, PlatformBlockState decorant, PlatformBlockState surface) { + return surface != null + && B.isSolid(surface) + && (decorator.isForcePlace() || canGoOn(decorant, surface)); + } + + static boolean canReplaceStackTarget(PlatformBlockState state, boolean allowFluid) { + return B.isAir(state) || allowFluid && B.isFluid(state); + } + + private static boolean canPlaceTwoBlockPlant(Hunk data, int x, int z, + int lowerY, int upperY, boolean caveSkipFluid) { + if (lowerY < 0 || upperY >= data.getHeight()) { + return false; + } + + PlatformBlockState lower = data.get(x, lowerY, z); + PlatformBlockState upper = data.get(x, upperY, z); + return B.isAir(lower) && B.isAir(upper) + && (!caveSkipFluid || !B.isFluid(lower) && !B.isFluid(upper)); + } + + private static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ, + IrisData irisData, int max) { + int stack = decorator.getHeight(rng, realX, realZ, irisData); + if (decorator.isScaleStack()) { + stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); + } else { + stack = Math.min(max, stack); + } + return stack; + } + + private static volatile PlatformBlockState[] dripstoneUp; + private static volatile PlatformBlockState[] dripstoneDown; + + private static PlatformBlockState[] buildDripstoneArr(String direction) { + String[] order = {"tip", "frustum", "base"}; + PlatformBlockState[] arr = new PlatformBlockState[3]; + for (int k = 0; k < 3; k++) { + arr[k] = B.getState("minecraft:pointed_dripstone[thickness=" + order[k] + ",vertical_direction=" + direction + "]"); + } + return arr; + } + + private static PlatformBlockState dripstoneBlock(int stack, int i, String direction) { + int thIdx; + if (i == stack - 1) { + thIdx = 0; + } else if (i == stack - 2) { + thIdx = 1; + } else { + thIdx = 2; + } + if (direction.equals("up")) { + if (dripstoneUp == null) { + dripstoneUp = buildDripstoneArr("up"); + } + return dripstoneUp[thIdx]; + } + if (dripstoneDown == null) { + dripstoneDown = buildDripstoneArr("down"); + } + return dripstoneDown[thIdx]; + } + + static String stackedVineKey(PlatformBlockState state, int stack, int index) { + String material = IrisProceduralBlocks.materialKey(state); + boolean tip = index == stack - 1; + return switch (material) { + case WEEPING_VINES, WEEPING_VINES_PLANT -> tip ? WEEPING_VINES : WEEPING_VINES_PLANT; + case TWISTING_VINES, TWISTING_VINES_PLANT -> tip ? TWISTING_VINES : TWISTING_VINES_PLANT; + default -> null; + }; + } + + private static PlatformBlockState stackedVineBlock(PlatformBlockState state, int stack, int index) { + String key = stackedVineKey(state, stack, index); + if (key == null) { + return state; + } + return switch (key) { + case WEEPING_VINES -> weepingVines == null ? weepingVines = B.getState(key) : weepingVines; + case WEEPING_VINES_PLANT -> weepingVinesPlant == null ? weepingVinesPlant = B.getState(key) : weepingVinesPlant; + case TWISTING_VINES -> twistingVines == null ? twistingVines = B.getState(key) : twistingVines; + case TWISTING_VINES_PLANT -> twistingVinesPlant == null ? twistingVinesPlant = B.getState(key) : twistingVinesPlant; + default -> state; + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java new file mode 100644 index 000000000..b14f63ab0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java @@ -0,0 +1,62 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; + +public final class DecoratorPlatformHooks { + private static volatile FaceFixer FACE_FIXER = null; + private static volatile SurfaceSturdiness SURFACE_STURDINESS = null; + + private DecoratorPlatformHooks() { + } + + public interface FaceFixer { + PlatformBlockState fixFaces(PlatformBlockState state, Hunk hunk, int rX, int rZ, int x, int y, int z, EngineMantle mantle); + } + + public interface SurfaceSturdiness { + boolean canGoOn(PlatformBlockState surface); + } + + public static synchronized Bindings bind(FaceFixer faceFixer, SurfaceSturdiness surfaceSturdiness) { + Bindings previous = new Bindings(FACE_FIXER, SURFACE_STURDINESS); + FACE_FIXER = faceFixer; + SURFACE_STURDINESS = surfaceSturdiness; + return previous; + } + + public static synchronized void restore(Bindings bindings) { + FACE_FIXER = bindings.faceFixer(); + SURFACE_STURDINESS = bindings.surfaceSturdiness(); + } + + static FaceFixer faceFixer() { + return FACE_FIXER; + } + + static SurfaceSturdiness surfaceSturdiness() { + return SURFACE_STURDINESS; + } + + public record Bindings(FaceFixer faceFixer, SurfaceSturdiness surfaceSturdiness) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java new file mode 100644 index 000000000..d8d31447b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java @@ -0,0 +1,55 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.spi.PlatformBlockState; + +/* + * Floating island decoration path. Bypasses all canGoOn, slope, whitelist, and blacklist + * gating from IrisSurfaceDecorator — the island top IS the biome's designated surface by + * construction, so those material-compatibility checks are never meaningful here. + */ +public class FloatingDecorator { + + public static int decorateColumn(Engine engine, IrisBiome target, IrisDecorationPart part, + int xf, int zf, int realX, int realZ, + int height, int max, Hunk data, RNG rng, + Runnable candidatesNullCallback) { + RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getDecorator(), part)); + IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ); + + if (decorator == null) { + candidatesNullCallback.run(); + return 0; + } + + if (!decorator.isStacking()) { + DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data, rng, engine.getData()); + return max > 1 ? 1 : 0; + } + + return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data, rng, engine.getData()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java new file mode 100644 index 000000000..6efb73a6a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java @@ -0,0 +1,74 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.spi.PlatformBlockState; + +public class IrisCeilingDecorator extends IrisEngineDecorator { + private final RNG partRNG; + + public IrisCeilingDecorator(Engine engine) { + super(engine, "Ceiling", IrisDecorationPart.CEILING); + this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.CEILING)); + } + + @BlockCoordinates + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, int height, int max) { + decorate(x, z, realX, realX1, realX_1, realZ, realZ1, realZ_1, data, biome, biome.getInferredType(), height, max); + } + + @BlockCoordinates + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { + boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType); + RNG rng = getRNG(realX, realZ); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + + if (decorator == null) { + return; + } + + if (!decorator.isStacking()) { + if (caveSkipFluid) { + PlatformBlockState state = data.get(x, height, z); + if (B.isFluid(state)) { + return; + } + } + DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, rng, getData(), true, getEngine().getMantle()); + return; + } + + DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); + opts.reset(); + opts.caveSkipFluid = caveSkipFluid; + DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, rng, getData(), max, opts, getEngine().getMantle()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java new file mode 100644 index 000000000..9dde144e7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java @@ -0,0 +1,45 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedComponent; +import art.arcane.iris.engine.framework.EngineDecorator; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import lombok.Getter; + +public abstract class IrisEngineDecorator extends EngineAssignedComponent implements EngineDecorator { + @Getter + private final IrisDecorationPart part; + + public IrisEngineDecorator(Engine engine, String name, IrisDecorationPart part) { + super(engine, name + " Decorator"); + this.part = part; + } + + @BlockCoordinates + protected RNG getRNG(int x, int z) { + long seed = DecoratorCore.partSeed(getSeed(), part); + long modX = 29356788L ^ (part.ordinal() + 6); + long modZ = 10439677L ^ (part.ordinal() + 1); + return new RNG(x * modX + z * modZ + seed); + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java new file mode 100644 index 000000000..6f4abf0b9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java @@ -0,0 +1,84 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.spi.PlatformBlockState; + +public class IrisSeaFloorDecorator extends IrisEngineDecorator { + private final RNG partRNG; + + public IrisSeaFloorDecorator(Engine engine) { + super(engine, "Sea Floor", IrisDecorationPart.SEA_FLOOR); + this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SEA_FLOOR)); + } + + @BlockCoordinates + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, int height, int max) { + RNG rng = getRNG(realX, realZ); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + + if (decorator == null) { + return; + } + + if (!decorator.isStacking()) { + if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault() + && !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) { + return; + } + if (height >= 0 && height < getEngine().getHeight()) { + data.set(x, height, z, decorator.getBlockData100(biome, rng, realX, height, realZ, getData())); + } + return; + } + + int stack = decorator.getHeight(rng, realX, realZ, getData()); + if (decorator.isScaleStack()) { + stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); + } else { + stack = Math.min(stack, max - height); + } + + if (stack == 1) { + data.set(x, height, z, decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData())); + return; + } + + int engineHeight = getEngine().getHeight(); + for (int i = 0; i < stack; i++) { + int h = height + i; + if (h > max || h > engineHeight) { + continue; + } + double threshold = ((double) i) / (stack - 1); + data.set(x, h, z, threshold >= decorator.getTopThreshold() + ? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData()) + : decorator.getBlockData100(biome, rng, realX, h, realZ, getData())); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java new file mode 100644 index 000000000..62d470345 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java @@ -0,0 +1,97 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.spi.PlatformBlockState; + +public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { + private final RNG partRNG; + + public IrisSeaSurfaceDecorator(Engine engine) { + super(engine, "Sea Surface", IrisDecorationPart.SEA_SURFACE); + this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SEA_SURFACE)); + } + + @BlockCoordinates + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, int height, int max) { + RNG rng = getRNG(realX, realZ); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + + if (decorator == null) { + return; + } + + if (!decorator.isStacking()) { + int targetY = height + 1; + if (height >= 0 && targetY < getEngine().getHeight() + && DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + PlatformBlockState block = decorator.getBlockData100(biome, rng, realX, height, realZ, getData()); + if (block != null) { + data.set(x, targetY, z, block); + } + } + return; + } + + int stack = decorator.getHeight(rng, realX, realZ, getData()); + if (decorator.isScaleStack()) { + stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); + } + + if (stack == 1) { + int targetY = height + 1; + if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + return; + } + + PlatformBlockState block = decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData()); + if (block != null) { + data.set(x, targetY, z, block); + } + return; + } + + int engineHeight = getEngine().getHeight(); + for (int i = 0; i < stack; i++) { + int h = height + i; + int targetY = h + 1; + if (h >= max || targetY >= engineHeight + || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + break; + } + double threshold = ((double) i) / (stack - 1); + PlatformBlockState block = threshold >= decorator.getTopThreshold() + ? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData()) + : decorator.getBlockData100(biome, rng, realX, h, realZ, getData()); + if (block == null) { + break; + } + data.set(x, targetY, z, block); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java new file mode 100644 index 000000000..d07750a71 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java @@ -0,0 +1,126 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.spi.PlatformBlockState; + +public class IrisShoreLineDecorator extends IrisEngineDecorator { + private final RNG partRNG; + + public IrisShoreLineDecorator(Engine engine) { + super(engine, "Shore Line", IrisDecorationPart.SHORE_LINE); + this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SHORE_LINE)); + } + + @BlockCoordinates + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, int height, int max) { + if (height != getDimension().getFluidHeight()) { + return; + } + + double complexFluidHeight = getComplex().getFluidHeight(); + ProceduralStream heightStream = getComplex().getHeightStream(); + if (Math.round(heightStream.get(realX1, realZ)) >= complexFluidHeight + && Math.round(heightStream.get(realX_1, realZ)) >= complexFluidHeight + && Math.round(heightStream.get(realX, realZ1)) >= complexFluidHeight + && Math.round(heightStream.get(realX, realZ_1)) >= complexFluidHeight) { + return; + } + + RNG rng = getRNG(realX, realZ); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + + if (decorator == null) { + return; + } + + if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault() + && !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) { + return; + } + + PlatformBlockState support = data.get(x, height, z); + if (support == null || !support.isSolid()) { + return; + } + + if (!decorator.isStacking()) { + int targetY = height + 1; + if (targetY >= data.getHeight() + || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + return; + } + PlatformBlockState block = decorator.getBlockData100(biome, rng, realX, height, realZ, getData()); + if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) { + data.set(x, targetY, z, block); + } + return; + } + + int stack = decorator.getHeight(rng, realX, realZ, getData()); + if (decorator.isScaleStack()) { + stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); + } else { + stack = Math.min(max - height, stack); + } + + if (stack == 1) { + int targetY = height + 1; + if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + return; + } + + PlatformBlockState block = decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData()); + if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) { + data.set(x, targetY, z, block); + } + return; + } + + for (int i = 0; i < stack; i++) { + int h = height + i; + int targetY = h + 1; + if (targetY >= data.getHeight() + || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + break; + } + double threshold = ((double) i) / (stack - 1); + PlatformBlockState block = threshold >= decorator.getTopThreshold() + ? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData()) + : decorator.getBlockData100(biome, rng, realX, h, realZ, getData()); + if (block == null) { + break; + } + if (i == 0 && !DecoratorCore.isValidShorelineSupport(decorator, block, support)) { + break; + } + data.set(x, targetY, z, block); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java new file mode 100644 index 000000000..0b18b6a84 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java @@ -0,0 +1,96 @@ +/* + * 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.decorator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.spi.PlatformBlockState; + +public class IrisSurfaceDecorator extends IrisEngineDecorator { + private final RNG partRNG; + + public IrisSurfaceDecorator(Engine engine) { + super(engine, "Surface", IrisDecorationPart.NONE); + this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.NONE)); + } + + protected IrisSurfaceDecorator(Engine engine, String name) { + super(engine, name, IrisDecorationPart.NONE); + this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.NONE)); + } + + protected boolean isSlopeValid(IrisDecorator decorator, int realX, int realZ) { + if (decorator.isForcePlace() || decorator.getSlopeCondition().isDefault()) { + return true; + } + return decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ)); + } + + @BlockCoordinates + @Override + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, int height, int max) { + decorate(x, z, realX, realX1, realX_1, realZ, realZ1, realZ_1, data, biome, biome.getInferredType(), height, max); + } + + @BlockCoordinates + public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { + int fluidHeight = getDimension().getFluidHeight(); + if (inferredType == InferredType.SHORE && height < fluidHeight) { + return; + } + + boolean underwater = isUnderwater(inferredType, height, fluidHeight); + boolean caveSkipFluid = skipsFluid(inferredType); + RNG rng = getRNG(realX, realZ); + IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + + if (decorator == null || !isSlopeValid(decorator, realX, realZ)) { + return; + } + + if (decorator.isStacking()) { + DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); + opts.reset(); + opts.underwater = underwater; + opts.fluidHeight = fluidHeight; + opts.caveSkipFluid = caveSkipFluid; + DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, rng, getData(), opts); + return; + } + + DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ, + data, rng, getData(), underwater, caveSkipFluid, getEngine().getMantle()); + } + + static boolean isUnderwater(InferredType inferredType, int height, int fluidHeight) { + return height < fluidHeight && inferredType != InferredType.CAVE; + } + + static boolean skipsFluid(InferredType inferredType) { + return inferredType == InferredType.CAVE; + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java new file mode 100644 index 000000000..b6975b753 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -0,0 +1,1321 @@ +/* + * 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.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.engine.object.structure.vanilla.IrisNativeStructure; +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.engine.object.structure.IrisStructureAnchorMode; +import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.structure.StructureDistribution; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +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. + * + * A per-engine index of placed keys is cached 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 Cache INDEX_CACHE = Caffeine.newBuilder().weakKeys().build(); + private static final Cache LOCATABLE_INDEX_CACHE = + Caffeine.newBuilder().weakKeys().build(); + 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; + } + + 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 (IrisStructurePlacement 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 void invalidate(Engine engine) { + if (engine != null) { + INDEX_CACHE.invalidate(engine); + LOCATABLE_INDEX_CACHE.invalidate(engine); + } + } + + 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 (IrisStructurePlacement placement : catalog.concentricRings()) { + int count = Math.max(1, placement.getRingCount()); + 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 (IrisStructurePlacement placement : catalog.concentricRings) { + int count = Math.max(1, placement.getRingCount()); + 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, IrisStructurePlacement 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"); + } + NativeStructurePlacementPlanner.validateBackend(placement); + if (!placement.hasIrisStructures() || placement.getDistribution() == null) { + throw new IllegalStateException("Iris structure placement is missing its distribution or 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 = engine.getData().load(IrisStructure.class, selectedKey, false); + if (structure == null) { + throw new IllegalStateException("Iris structure placement references missing structure '" + + selectedKey + "'"); + } + StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure); + 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)); + 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(IrisStructurePlacement placement, String structureKey, + int chunkX, int chunkZ, boolean outputPresent, + String failureReason) { + if (outputPresent) { + return true; + } + if (placement == null + || NativeStructureSuppression.REPLACE_SOURCE != placement.getNativeSuppression()) { + return false; + } + String key = structureKey == null || structureKey.isBlank() + ? String.valueOf(placement.getStructures()) : 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 (NativeStructureStartPlan plan : NativeStructurePlacementPlanner.plansAt(engine, cx, cz)) { + if (normalize(plan.source().getStructure()).equals(normalizedKey)) { + return new ResolvedStart(cx << 4, plan.baseY(), cz << 4); + } + } + } + KList placements = StructurePlacementScope.placementsAt(engine, cx, cz); + for (IrisStructurePlacement 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, + IrisStructurePlacement 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, IrisStructurePlacement 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.isUnderwater() + && NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ)) { + return null; + } + if (placement.resolvedAnchor() == IrisStructureAnchorMode.SURFACE) { + int surfaceY = engine.getHeight(originX, originZ, true) + engine.getMinHeight(); + return surfaceY < placement.getMinHeight() || surfaceY > placement.getMaxHeight() ? null : surfaceY; + } + int bandMin = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight())); + int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + if (bandMin > bandMax) { + return null; + } + return randomInclusive(rng, bandMin, bandMax); + } + + static Integer resolveVerticalShift(KList pieces, IrisStructurePlacement 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.getMinHeight(), placement.getMaxHeight())); + int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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, + IrisStructurePlacement 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; + } + + IrisStructureTerrain terrain = placement.resolvedTerrain(); + IrisStructureTerrainMode terrainMode = terrain.resolvedMode(); + boolean forceCarve = terrainMode == IrisStructureTerrainMode.FORCE_CARVE; + boolean bore = terrainMode == IrisStructureTerrainMode.BORE; + int sideExtension = forceCarve || bore ? Math.max(0, terrain.getHorizontalPadding()) : 0; + IrisStructureCarveShape carveShape = terrain.resolvedShape(); + int topExtension = forceCarve + ? carveShape.maximumCeilingExtension( + terrain.getCeilingPadding(), terrain.resolvedErosionStrength()) + : bore ? Math.max(0, terrain.getCeilingPadding()) : 0; + int bottomExtension = forceCarve || bore ? Math.max(0, terrain.getFloorPadding()) : 0; + int bandMin = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight())); + int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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 == IrisStructureCarveShape.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(IrisStructurePlacement placement, RNG rng) { + if (placement == null || placement.getStructures() == null || placement.getStructures().isEmpty()) { + return null; + } + return placement.getStructures().get(rng.nextInt(placement.getStructures().size())); + } + + static KList alignCavePieces( + KList pieces, + IrisStructurePlacement placement, + int anchorY + ) { + IrisStructureAnchorMode 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, + IrisStructurePlacement placement, + IrisStructure structure, int baseY) { + if (placement.isAnchoredUnderground() || pieces.size() <= 1 + || structure.getPlaceMode() == ObjectPlaceMode.STRUCTURE_PIECE + || structure.getPlaceMode() == ObjectPlaceMode.FLOATING) { + return pieces; + } + int[] bounds = computeBounds(pieces); + return bounds == null ? pieces : shiftPieces(pieces, baseY - bounds[1]); + } + + static boolean hasExactY(IrisStructurePlacement placement, IrisStructure structure, + KList pieces) { + return placement.isAnchoredUnderground() || pieces.size() > 1 + || structure.getPlaceMode() == ObjectPlaceMode.STRUCTURE_PIECE + || structure.getPlaceMode() == ObjectPlaceMode.FLOATING; + } + + 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 (IrisStructurePlacement placement : index(engine).placements) { + if (!isSearchablePlacement(engine, placement) + || !matches(placement, key, engine.getData())) { + continue; + } + if (placement.getDistribution() == StructureDistribution.RANDOM_SPREAD) { + randomSpread.add(new RandomSpreadParameters( + Math.max(1, placement.getSpacing()), placement.getSeparation(), + StructurePlacementGrid.placementSalt(placement))); + } else if (placement.getDistribution() == StructureDistribution.CONCENTRIC_RINGS) { + concentricRings.add(placement); + } else if (placement.getDistribution() == StructureDistribution.DENSITY) { + hasDensity = true; + } + } + return new PlacementCatalog(List.copyOf(randomSpread), List.copyOf(concentricRings), hasDensity); + } + + static boolean isSearchableDensityPlacement(Engine engine, IrisStructurePlacement placement) { + return placement != null + && placement.getDistribution() == StructureDistribution.DENSITY + && isSearchablePlacement(engine, placement); + } + + static boolean isSearchablePlacement(Engine engine, IrisStructurePlacement placement) { + if (engine == null || placement == null || placement.getDistribution() == null + || engine.getHeight() <= 0) { + return false; + } + if (placement.getDistribution() == StructureDistribution.DENSITY + && !(placement.getDensity() > 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.getMinHeight(), placement.getMaxHeight()) + : placement.getMinHeight(); + long configuredMax = placement.isAnchoredUnderground() + ? Math.max(placement.getMinHeight(), placement.getMaxHeight()) + : placement.getMaxHeight(); + 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(IrisStructurePlacement placement, String key, IrisData data) { + if (placement == null || key == null || data == null) { + return false; + } + String normalizedKey = normalize(key); + if (placement.getNativeStructures() != null) { + for (IrisNativeStructure source : placement.getNativeStructures()) { + if (source != null && normalize(source.getStructure()).equals(normalizedKey)) { + return true; + } + } + } + if (placement.getStructures() == null) { + return false; + } + for (String structureKey : placement.getStructures()) { + if (structureKey == null || structureKey.isBlank()) { + continue; + } + IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + 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 INDEX_CACHE.get(engine, ignored -> build(engine)); + } + + private static LocatableIndex locatableIndex(Engine engine) { + if (engine == null) { + return EMPTY_LOCATABLE_INDEX; + } + return LOCATABLE_INDEX_CACHE.get(engine, ignored -> buildLocatableIndex(engine)); + } + + 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 (IrisStructurePlacement placement : index(engine).placements) { + if (!isSearchablePlacement(engine, placement)) { + continue; + } + if (placement.hasNativeStructures()) { + for (IrisNativeStructure source : placement.getNativeStructures()) { + addLocatableKey(source.getStructure(), keys, normalizedKeys); + addLocatableKey(source.getStructure(), nativeKeys, normalizedNativeKeys); + } + continue; + } + for (String structureKey : placement.getStructures()) { + IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + 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(); + Set loadKeys = new LinkedHashSet<>(); + Set normalizedLoadKeys = new LinkedHashSet<>(); + Set vanillaAliases = new LinkedHashSet<>(); + Set suppressedVanillaSources = new LinkedHashSet<>(); + List placements = new ArrayList<>(); + collect(engine.getDimension().getStructures(), data, loadKeys, normalizedLoadKeys, vanillaAliases, + suppressedVanillaSources, placements, true); + KList regions = engine.getDimension().getAllRegions(engine); + if (regions != null) { + for (IrisRegion region : regions) { + collect(region == null ? null : region.getStructures(), data, + loadKeys, normalizedLoadKeys, vanillaAliases, + suppressedVanillaSources, placements, false); + } + } + KList biomes = engine.getDimension().getReachableBiomes(engine); + if (biomes != null) { + for (IrisBiome biome : biomes) { + collect(biome == null ? null : biome.getStructures(), data, + 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 (IrisStructurePlacement placement : placements) { + if (!placement.hasNativeStructures()) { + continue; + } + for (IrisNativeStructure source : placement.getNativeStructures()) { + if (source != null) { + nativeKeys.add(normalize(source.getStructure())); + } + } + } + return Collections.unmodifiableSet(nativeKeys); + } + + private static void collect(KList source, IrisData data, Set loadKeys, + Set normalizedLoadKeys, Set vanillaAliases, + Set suppressedVanillaSources, + List placements, boolean allowNativeSuppression) { + if (source == null) { + return; + } + for (IrisStructurePlacement placement : source) { + if (placement == null) { + throw new IllegalStateException("Iris structure placement list contains a null placement"); + } + if (placement.getDistribution() == null) { + throw new IllegalStateException("Iris structure placement is missing its distribution"); + } + NativeStructurePlacementPlanner.validateBackend(placement); + boolean replacesNative = NativeStructureSuppression.REPLACE_SOURCE == placement.getNativeSuppression(); + if (replacesNative && !allowNativeSuppression) { + throw new IllegalStateException("REPLACE_SOURCE is only valid on dimension-level structure placements"); + } + if (placement.hasNativeStructures()) { + for (IrisNativeStructure nativeStructure : placement.getNativeStructures()) { + if (nativeStructure == null + || nativeStructure.getStructure() == null + || !NAMESPACED_RESOURCE_KEY.matcher(nativeStructure.getStructure()).matches()) { + throw new IllegalStateException("Native structure placement contains an invalid structure key"); + } + String sourceKey = nativeStructure.getStructure(); + 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.getStructures()) { + 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 = data.load(IrisStructure.class, structureKey, false); + 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)) { + 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(IrisStructurePlacement 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 new file mode 100644 index 000000000..ca294d0a2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/PlacedObject.java @@ -0,0 +1,37 @@ +/* + * 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 new file mode 100644 index 000000000..49d62339d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java @@ -0,0 +1,54 @@ +/* + * 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 new file mode 100644 index 000000000..08df2d833 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java @@ -0,0 +1,1357 @@ +/* + * 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 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) { + 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), 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 new file mode 100644 index 000000000..599b4bd88 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java @@ -0,0 +1,359 @@ +package art.arcane.iris.engine.framework; + +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +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, IrisStructurePlacement 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"); + IrisStructureAnchorMode 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.getMinHeight(), placement.getMaxHeight())); + int maximumY = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + if (minimumY > maximumY) { + return null; + } + + int attempts = Math.min(MAX_ATTEMPTS, Math.max(1, placement.getCaveAnchorAttempts())); + int scanStep = Math.min(MAX_SCAN_STEP, Math.max(1, placement.getCaveAnchorScanStep())); + int clearance = Math.min(MAX_CLEARANCE, Math.max(1, placement.getCaveMinimumClearance())); + 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, + IrisStructurePlacement placement, + IrisStructureAnchorMode mode, + int blockX, + int blockZ, + int minimumY, + int maximumY, + int scanStep, + int clearance + ) { + if (mode == IrisStructureAnchorMode.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, + IrisStructurePlacement 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, + IrisStructurePlacement 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, + IrisStructureAnchorMode mode, + int blockX, + int mantleY, + int blockZ, + int clearance + ) { + IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); + if (mode == IrisStructureAnchorMode.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, + IrisStructureAnchorMode 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, + IrisStructurePlacement placement, + int blockX, + int mantleY, + int blockZ + ) { + MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); + return acceptsAnchorFluid( + placement.isUnderwater(), + cavern, + mantleY, + engine.getDimension().getCaveLavaHeight()); + } + + 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, + IrisStructurePlacement placement, + int blockX, + int mantleY, + int blockZ + ) { + if (placement.getCaveBiomes() == null || placement.getCaveBiomes().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.getCaveBiomes()) { + 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/StructurePlacementGrid.java b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java new file mode 100644 index 000000000..e02ad2288 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java @@ -0,0 +1,287 @@ +/* + * 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.vanilla.IrisNativeStructure; +import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.volmlib.util.math.RNG; + +import java.util.Locale; +import java.util.Set; +import java.util.TreeSet; + +public final class StructurePlacementGrid { + private static final long DENSITY_SIGNATURE = 0x6A09E667F3BCC909L; + + private StructurePlacementGrid() { + } + + public static boolean startsInChunk(IrisStructurePlacement placement, int cx, int cz, long seed) { + return switch (placement.getDistribution()) { + case RANDOM_SPREAD -> randomSpreadStart(cx, cz, placement.getSpacing(), placement.getSeparation(), + placementSalt(placement), seed); + case DENSITY -> densityStart(placement, cx, cz, seed); + case CONCENTRIC_RINGS -> concentricRingsStart(cx, cz, placement, seed); + }; + } + + public static RNG placementRng(IrisStructurePlacement placement, int cx, int cz, long seed) { + return new RNG(placementSeed(placement, cx, cz, seed)); + } + + public static boolean randomSpreadStart(int cx, int cz, int spacing, int separation, int salt, long seed) { + int sp = Math.max(1, spacing); + int cellX = Math.floorDiv(cx, sp); + int cellZ = Math.floorDiv(cz, sp); + int[] start = randomSpreadCellChunk(cellX, cellZ, spacing, separation, salt, seed); + return start[0] == cx && start[1] == cz; + } + + /** + * Returns the single {chunkX, chunkZ} that a RANDOM_SPREAD placement occupies within the given + * grid cell. This is the inverse of {@link #randomSpreadStart} and uses the identical formula, so + * a locator can jump straight to the one candidate per cell instead of testing every chunk. + */ + public static int[] randomSpreadCellChunk(int cellX, int cellZ, int spacing, int separation, int salt, long seed) { + int sp = Math.max(1, spacing); + int sep = Math.max(0, Math.min(separation, sp - 1)); + RNG r = new RNG(mix(seed, cellX, cellZ, salt)); + int range = Math.max(1, sp - sep); + int startCx = cellX * sp + r.nextInt(range); + int startCz = cellZ * sp + r.nextInt(range); + return new int[]{startCx, startCz}; + } + + public static int[] concentricRingChunk(IrisStructurePlacement placement, int placementIndex, long seed) { + int count = Math.max(1, placement.getRingCount()); + if (placementIndex < 0 || placementIndex >= count) { + return null; + } + int distance = Math.max(1, placement.getRingDistance()); + int spread = Math.max(1, placement.getRingSpread()); + int ring = Math.floorDiv(placementIndex, spread) + 1; + int firstIndex = (ring - 1) * spread; + int slots = Math.min(spread, count - firstIndex); + int slot = placementIndex - firstIndex; + double slotAngle = (2.0 * Math.PI) / slots; + double offset = unitDouble(mix(seed, ring, count, placementSalt(placement))) * slotAngle; + double angle = offset + (slot * slotAngle); + long configuredRadius = (long) ring * distance; + if (configuredRadius > Integer.MAX_VALUE) { + return null; + } + int radius = (int) configuredRadius; + return new int[]{ + (int) Math.round(Math.cos(angle) * radius), + (int) Math.round(Math.sin(angle) * radius) + }; + } + + private static boolean concentricRingsStart(int cx, int cz, IrisStructurePlacement placement, long seed) { + if (cx == 0 && cz == 0) { + return false; + } + int distance = Math.max(1, placement.getRingDistance()); + int count = Math.max(1, placement.getRingCount()); + int spread = Math.max(1, placement.getRingSpread()); + double dist = Math.sqrt((double) cx * cx + (double) cz * cz); + int estimatedRing = (int) Math.round(dist / distance); + int ringCount = Math.ceilDiv(count, spread); + int firstRing = Math.max(1, estimatedRing - 1); + int lastRing = Math.min(ringCount, estimatedRing + 1); + for (int ring = firstRing; ring <= lastRing; ring++) { + int firstIndex = (ring - 1) * spread; + int slots = Math.min(spread, count - firstIndex); + if (slots <= 0) { + continue; + } + double slotAngle = (2.0 * Math.PI) / slots; + double offset = unitDouble(mix(seed, ring, count, placementSalt(placement))) * slotAngle; + double slotPosition = (Math.atan2(cz, cx) - offset) / slotAngle; + int nearestSlot = Math.floorMod((int) Math.round(slotPosition), slots); + for (int delta = -1; delta <= 1; delta++) { + int slot = Math.floorMod(nearestSlot + delta, slots); + int[] candidate = concentricRingChunk(placement, firstIndex + slot, seed); + if (candidate != null && candidate[0] == cx && candidate[1] == cz) { + return true; + } + } + } + return false; + } + + private static boolean densityStart(IrisStructurePlacement placement, int cx, int cz, long seed) { + double density = placement.getDensity(); + if (density <= 0.0) { + return false; + } + if (density >= 1.0) { + return true; + } + RNG rng = new RNG(placementSeed(placement, cx, cz, seed) ^ DENSITY_SIGNATURE); + return rng.chance(density); + } + + public static long placementIdentity(IrisStructurePlacement placement) { + long signature = 1469598103934665603L; + signature = appendLong(signature, placement.getDistribution().ordinal()); + signature = appendLong(signature, placement.getSalt()); + String placementId = placement.getPlacementId(); + if (placementId != null && !placementId.isBlank()) { + signature = appendLong(signature, 1L); + signature = appendSignature(signature, placementId.trim()); + } else { + signature = appendLong(signature, 0L); + signature = appendLong(signature, placement.getSpacing()); + signature = appendLong(signature, placement.getSeparation()); + signature = appendLong(signature, Double.doubleToLongBits(placement.getDensity())); + signature = appendLong(signature, placement.getRingCount()); + signature = appendLong(signature, placement.getRingDistance()); + signature = appendLong(signature, placement.getRingSpread()); + signature = appendLong(signature, placement.getMinHeight()); + signature = appendLong(signature, placement.getMaxHeight()); + signature = appendLong(signature, placement.isUnderground() ? 1L : 0L); + signature = appendLong(signature, placement.isUnderwater() ? 1L : 0L); + signature = appendSources(signature, placement); + signature = appendAnchor(signature, placement); + } + return signature; + } + + private static long placementSeed(IrisStructurePlacement placement, int cx, int cz, long seed) { + long signature = placementIdentity(placement); + int identitySalt = (int) (signature ^ (signature >>> 32)); + return mix(seed ^ signature, cx, cz, placementSalt(placement) ^ identitySalt); + } + + private static long appendSignature(long signature, String value) { + long result = appendLong(signature, value.length()); + for (int index = 0; index < value.length(); index++) { + result = (result ^ value.charAt(index)) * 1099511628211L; + } + return result; + } + + private static long appendLong(long signature, long value) { + long result = signature; + long remaining = value; + for (int index = 0; index < Long.BYTES; index++) { + result = (result ^ (remaining & 0xffL)) * 1099511628211L; + remaining >>>= Byte.SIZE; + } + return result; + } + + private static long appendSources(long signature, IrisStructurePlacement placement) { + long result = signature; + if (placement.hasIrisStructures()) { + result = appendLong(result, 1L); + result = appendLong(result, placement.getStructures().size()); + for (String key : placement.getStructures()) { + result = appendSignature(result, key == null ? "" : key); + } + return result; + } + result = appendLong(result, 2L); + if (placement.getNativeStructures() == null) { + return appendLong(result, 0L); + } + result = appendLong(result, placement.getNativeStructures().size()); + for (IrisNativeStructure source : placement.getNativeStructures()) { + if (source == null) { + result = appendSignature(result, ""); + result = appendLong(result, 0L); + continue; + } + result = appendSignature(result, + source.getStructure() == null ? "" : source.getStructure()); + result = appendLong(result, source.getWeight()); + } + return result; + } + + private static long appendAnchor(long signature, IrisStructurePlacement placement) { + IrisStructureAnchorMode anchor = placement.getAnchor(); + if (anchor == null || anchor == IrisStructureAnchorMode.LEGACY) { + return signature; + } + long result = appendLong(signature, 0x4A49475341574C41L); + result = appendLong(result, anchor.ordinal()); + if (!anchor.isCave()) { + return result; + } + result = appendLong(result, placement.getCaveAnchorAttempts()); + result = appendLong(result, placement.getCaveAnchorScanStep()); + result = appendLong(result, placement.getCaveMinimumClearance()); + if (placement.getCaveBiomes() == null) { + return appendLong(result, 0L); + } + Set biomes = new TreeSet<>(); + for (String biome : placement.getCaveBiomes()) { + if (biome != null && !biome.isBlank()) { + biomes.add(biome.trim().toLowerCase(Locale.ROOT)); + } + } + result = appendLong(result, biomes.size()); + for (String biome : biomes) { + result = appendSignature(result, biome); + } + return result; + } + + static int placementSalt(IrisStructurePlacement placement) { + String placementId = placement.getPlacementId(); + long identity; + if (placementId != null && !placementId.isBlank()) { + identity = appendSignature(1469598103934665603L, placementId.trim()); + } else { + identity = 1469598103934665603L; + identity = appendLong(identity, placement.getDistribution().ordinal()); + identity = appendLong(identity, placement.getSpacing()); + identity = appendLong(identity, placement.getSeparation()); + identity = appendLong(identity, Double.doubleToLongBits(placement.getDensity())); + identity = appendLong(identity, placement.getRingCount()); + identity = appendLong(identity, placement.getRingDistance()); + identity = appendLong(identity, placement.getRingSpread()); + identity = appendLong(identity, placement.getMinHeight()); + identity = appendLong(identity, placement.getMaxHeight()); + identity = appendLong(identity, placement.isUnderground() ? 1L : 0L); + identity = appendLong(identity, placement.isUnderwater() ? 1L : 0L); + identity = appendSources(identity, placement); + identity = appendAnchor(identity, placement); + } + return placement.getSalt() ^ (int) (identity ^ (identity >>> 32)); + } + + private static double unitDouble(long value) { + return (value >>> 11) * 0x1.0p-53; + } + + public static long mix(long seed, int a, int b, int salt) { + long h = seed; + h = h * 6364136223846793005L + (a * 341873128712L); + h = h * 6364136223846793005L + (b * 132897987541L); + h = h * 6364136223846793005L + salt; + h ^= (h >>> 33); + h *= 0xff51afd7ed558ccdL; + h ^= (h >>> 33); + return h; + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java new file mode 100644 index 000000000..13bd4bed2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java @@ -0,0 +1,95 @@ +package art.arcane.iris.engine.framework; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Objects; + +public final class StructurePlacementMarker { + private static final String FAMILY_PREFIX = "@iris-structure:"; + private static final String VERSION_PREFIX = FAMILY_PREFIX + "v1:"; + + private StructurePlacementMarker() { + } + + public static String encodeStructure(String objectKey, int placementId, String structureKey) { + String normalizedObjectKey = requireKey(objectKey, "objectKey"); + String normalizedStructureKey = requireKey(structureKey, "structureKey"); + return VERSION_PREFIX + + encodeKey(normalizedObjectKey) + + ":" + placementId + + ":" + encodeKey(normalizedStructureKey); + } + + public static Decoded decode(String marker) { + if (marker == null || marker.isBlank()) { + return null; + } + if (marker.startsWith(FAMILY_PREFIX)) { + return decodeStructure(marker); + } + return decodeLegacy(marker); + } + + private static Decoded decodeStructure(String marker) { + if (!marker.startsWith(VERSION_PREFIX)) { + return null; + } + String[] fields = marker.split(":", -1); + if (fields.length != 5 || !fields[0].equals("@iris-structure") || !fields[1].equals("v1")) { + return null; + } + try { + String objectKey = decodeCanonicalKey(fields[2]); + int placementId = Integer.parseInt(fields[3]); + String structureKey = decodeCanonicalKey(fields[4]); + if (objectKey.isBlank() || structureKey.isBlank()) { + return null; + } + return new Decoded(objectKey, placementId, structureKey); + } catch (IllegalArgumentException exception) { + return null; + } + } + + private static Decoded decodeLegacy(String marker) { + int separator = marker.indexOf('@'); + if (separator <= 0 || separator != marker.lastIndexOf('@') || separator == marker.length() - 1) { + return null; + } + String objectKey = marker.substring(0, separator); + if (objectKey.isEmpty() || objectKey.equals("null")) { + return null; + } + try { + return new Decoded(objectKey, Integer.parseInt(marker.substring(separator + 1)), null); + } catch (NumberFormatException exception) { + return null; + } + } + + private static String requireKey(String key, String name) { + String required = Objects.requireNonNull(key, name); + if (required.isBlank()) { + throw new IllegalArgumentException(name + " must not be blank"); + } + return required; + } + + private static String encodeKey(String key) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(key.getBytes(StandardCharsets.UTF_8)); + } + + private static String decodeCanonicalKey(String key) { + String decoded = new String(Base64.getUrlDecoder().decode(key), StandardCharsets.UTF_8); + if (!encodeKey(decoded).equals(key)) { + throw new IllegalArgumentException("Non-canonical marker key"); + } + return decoded; + } + + public record Decoded(String objectKey, int placementId, String structureKey) { + public boolean structureAware() { + return structureKey != null; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java new file mode 100644 index 000000000..9e35719af --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java @@ -0,0 +1,148 @@ +package art.arcane.iris.engine.framework; + +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.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.volmlib.util.collection.KList; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +public final class StructurePlacementScope { + private static final List SCOPE_INDEXES = new ArrayList<>(); + + private StructurePlacementScope() { + } + + 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, biome == null ? null : biome.getStructures()); + } + if (index.caveBiome()) { + IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ); + addCaveUnique(placements, seen, caveBiome == null ? null : caveBiome.getStructures()); + } + if (index.region()) { + IrisRegion region = complex.getRegionStream().get(blockX, blockZ); + addUnique(placements, seen, region == null ? null : region.getStructures()); + } + } + if (index.dimension()) { + addUnique(placements, seen, activeEngine.getDimension().getStructures()); + } + return placements; + } + + private static ScopeIndex scopeIndex(Engine engine) { + int revision = engine.getCacheID(); + synchronized (SCOPE_INDEXES) { + for (int i = SCOPE_INDEXES.size() - 1; i >= 0; i--) { + CachedScopeIndex cached = SCOPE_INDEXES.get(i); + Engine indexedEngine = cached.engine().get(); + if (indexedEngine == null) { + SCOPE_INDEXES.remove(i); + continue; + } + if (indexedEngine == engine) { + if (cached.revision() == revision) { + return cached.index(); + } + SCOPE_INDEXES.remove(i); + break; + } + } + ScopeIndex index = buildScopeIndex(engine); + SCOPE_INDEXES.add(new CachedScopeIndex(new WeakReference<>(engine), revision, index)); + return index; + } + } + + 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) { + KList structures = candidate.getStructures(); + if (structures == null || structures.isEmpty()) { + continue; + } + biome = true; + for (IrisStructurePlacement placement : structures) { + if (placement != null && placement.resolvedAnchor().isCave()) { + caveBiome = true; + break; + } + } + } + } + boolean region = false; + if (engine.getDimension() != null) { + KList allRegions = engine.getDimension().getAllRegions(engine); + if (allRegions == null) { + region = true; + } else { + for (IrisRegion candidate : allRegions) { + if (candidate.getStructures() != null && !candidate.getStructures().isEmpty()) { + region = true; + break; + } + } + } + } + boolean dimension = engine.getDimension() != null + && engine.getDimension().getStructures() != null + && !engine.getDimension().getStructures().isEmpty(); + return new ScopeIndex(biome, caveBiome, region, dimension); + } + + private static void addUnique(KList destination, + Set seen, + KList source) { + if (source == null) { + return; + } + for (IrisStructurePlacement placement : source) { + if (placement != null && seen.add(placement)) { + destination.add(placement); + } + } + } + + private static void addCaveUnique(KList destination, + Set seen, + KList source) { + if (source == null) { + return; + } + for (IrisStructurePlacement placement : source) { + if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) { + destination.add(placement); + } + } + } + + private record CachedScopeIndex(WeakReference engine, int revision, ScopeIndex index) { + } + + private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureReachability.java b/src/main/java/art/arcane/iris/engine/framework/StructureReachability.java new file mode 100644 index 000000000..15910aa36 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructureReachability.java @@ -0,0 +1,127 @@ +/* + * 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.world.IrisWorld; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.volmlib.util.collection.KList; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Objects; +import java.util.Set; + +/** + * Determines which vanilla/datapack structures can ever generate in a world, using the same biome + * gate vanilla applies: a structure is reachable when its biome filter intersects the set of vanilla + * biomes the pack actually produces (its {@code possibleBiomes}). Structures whose required biomes are + * never produced cannot generate and must not be scanned for by {@code /locate} or {@code /iris find} + * (an unbounded scan for an absent biome is what stalls the server). + * + *

The reachable set is fixed per live engine/world and is rebuilt after hotload. + */ +public final class StructureReachability { + private static final Cache> REACHABLE_CACHE = Caffeine.newBuilder().weakKeys().build(); + + private StructureReachability() { + } + + public static Set reachableKeys(Engine engine) { + Engine activeEngine = Objects.requireNonNull(engine, "Structure reachability requires an engine"); + if (activeEngine.getData() == null) { + throw new IllegalStateException("Structure reachability requires a bound pack data loader"); + } + return REACHABLE_CACHE.get(activeEngine, ignored -> build(activeEngine)); + } + + public static boolean isReachable(Engine engine, String structureKey) { + String normalizedStructureKey = normalizeStructureKey(structureKey); + return reachableKeys(engine).contains(normalizedStructureKey); + } + + public static void invalidate(Engine engine) { + if (engine == null) { + return; + } + REACHABLE_CACHE.invalidate(engine); + } + + private static Set build(Engine engine) { + IrisWorld world = engine.getWorld(); + if (world == null) { + throw new IllegalStateException("Structure reachability requires a bound Iris world"); + } + if (world.platformWorld() == null) { + throw new IllegalStateException("Structure reachability requires a bound platform world"); + } + Set reachable = new LinkedHashSet<>(); + for (String key : IrisPlatforms.get().structureHooks().reachableStructureKeys(world.platformWorld())) { + if (key == null || key.isBlank()) { + throw new IllegalStateException("Platform structure reachability returned a blank registry key"); + } + reachable.add(key.toLowerCase(Locale.ROOT)); + } + return Collections.unmodifiableSet(reachable); + } + + /** + * The vanilla biome keys (e.g. {@code minecraft:taiga}) from a structure's filter that the pack + * does not produce. An empty list means the structure is reachable. Used by the structure verify + * diagnostic to explain why a structure cannot generate. + */ + public static KList missingBiomeKeys(Engine engine, String structureKey) { + KList missing = new KList<>(); + Engine activeEngine = Objects.requireNonNull(engine, "Structure biome diagnostics require an engine"); + String normalizedStructureKey = normalizeStructureKey(structureKey); + IrisWorld world = activeEngine.getWorld(); + if (world == null) { + throw new IllegalStateException("Structure biome diagnostics require a bound Iris world"); + } + if (world.platformWorld() == null) { + throw new IllegalStateException("Structure biome diagnostics require a bound platform world"); + } + Set possible = new LinkedHashSet<>(); + for (String key : IrisPlatforms.get().structureHooks().possibleBiomeKeys(world.platformWorld())) { + if (key == null || key.isBlank()) { + throw new IllegalStateException("Platform structure biome query returned a blank possible-biome key"); + } + possible.add(key.toLowerCase(Locale.ROOT)); + } + for (String biomeKey : IrisPlatforms.get().structureHooks().structureBiomeKeys(normalizedStructureKey)) { + if (biomeKey == null || biomeKey.isBlank()) { + throw new IllegalStateException("Platform structure biome query returned a blank required-biome key for " + + normalizedStructureKey); + } + if (!possible.contains(biomeKey.toLowerCase(Locale.ROOT))) { + missing.add(biomeKey); + } + } + return missing; + } + + private static String normalizeStructureKey(String structureKey) { + if (structureKey == null || structureKey.isBlank()) { + throw new IllegalArgumentException("Registered structure key must not be blank"); + } + return structureKey.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java b/src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java new file mode 100644 index 000000000..05e67668c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/StructureVerticalBounds.java @@ -0,0 +1,51 @@ +/* + * 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; + +public final class StructureVerticalBounds { + private StructureVerticalBounds() { + } + + public static int clampOffset( + int structureMinY, + int structureMaxY, + int requestedOffset, + int worldMinY, + int worldMaxYExclusive + ) { + if (structureMaxY < structureMinY) { + throw new IllegalArgumentException("Structure maximum Y cannot be below its minimum Y"); + } + if (worldMaxYExclusive <= worldMinY) { + throw new IllegalArgumentException("World maximum Y must be above its minimum Y"); + } + + long structureHeight = (long) structureMaxY - structureMinY + 1L; + long worldHeight = (long) worldMaxYExclusive - worldMinY; + if (structureHeight > worldHeight) { + throw new IllegalArgumentException("Structure height " + structureHeight + + " exceeds writable world height " + worldHeight); + } + + long minimumOffset = (long) worldMinY - structureMinY; + long maximumOffset = (long) worldMaxYExclusive - 1L - structureMaxY; + long clamped = Math.max(minimumOffset, Math.min(maximumOffset, (long) requestedOffset)); + return Math.toIntExact(clamped); + } +} 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 new file mode 100644 index 000000000..ec18f15a6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java @@ -0,0 +1,101 @@ +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 new file mode 100644 index 000000000..38292bd5b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java @@ -0,0 +1,386 @@ +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 new file mode 100644 index 000000000..8e18400e4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java @@ -0,0 +1,104 @@ +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/PlanarJigsawWorkcellResolver.java b/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java new file mode 100644 index 000000000..53c3f8606 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java @@ -0,0 +1,139 @@ +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 new file mode 100644 index 000000000..02d7d1e87 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java @@ -0,0 +1,71 @@ +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/StructureAssemblyStatus.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyStatus.java new file mode 100644 index 000000000..c8642ab59 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyStatus.java @@ -0,0 +1,17 @@ +package art.arcane.iris.engine.framework.structure; + +public enum StructureAssemblyStatus { + COMPLETE, + INTENTIONAL_EMPTY, + FAILED_UNCAPPED, + FAILED_RULES, + HARD_CAP; + + public boolean isComplete() { + return this == COMPLETE || this == INTENTIONAL_EMPTY; + } + + public boolean isFailure() { + return !isComplete(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java new file mode 100644 index 000000000..b045843f6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphAssemblySample.java @@ -0,0 +1,30 @@ +package art.arcane.iris.engine.framework.structure; + +import java.util.List; +import java.util.Objects; + +public record StructureGraphAssemblySample(long seed, Outcome outcome) { + public record Outcome( + List pieceKeys, + StructureAssemblyStatus status, + String detail + ) { + public Outcome { + pieceKeys = List.copyOf(Objects.requireNonNull(pieceKeys)); + status = Objects.requireNonNull(status); + detail = Objects.requireNonNull(detail); + } + + public boolean pieceCapReached() { + return status == StructureAssemblyStatus.HARD_CAP; + } + + public boolean intentionalEmpty() { + return status == StructureAssemblyStatus.INTENTIONAL_EMPTY; + } + + public boolean isComplete() { + return status.isComplete(); + } + } +} 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 new file mode 100644 index 000000000..42e00e57d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java @@ -0,0 +1,99 @@ +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.core.loader.IrisData; +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.iris.spi.IrisLogging; +import art.arcane.volmlib.util.math.RNG; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +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) { + IrisData activeData = Objects.requireNonNull(data); + IrisStructure activeStructure = Objects.requireNonNull(structure); + String structureKey = activeStructure.getLoadKey(); + if (structureKey == null || structureKey.isBlank()) { + return compileAndReport(activeData, activeStructure); + } + ConcurrentMap catalog = CACHE.get( + activeData, ignored -> new ConcurrentHashMap<>()); + return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure)); + } + + public static void invalidate(IrisData data) { + if (data != null) { + CACHE.invalidate(data); + RUNTIME_OUTPUT.invalidate(data); + } + } + + public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure) { + IrisData activeData = Objects.requireNonNull(data); + IrisStructure activeStructure = Objects.requireNonNull(structure); + if (!compile(activeData, activeStructure).guaranteesAssemblyOutput()) { + return false; + } + String structureKey = activeStructure.getLoadKey(); + if (structureKey == null || structureKey.isBlank()) { + return sampleRuntimeAssembly(activeData, activeStructure); + } + ConcurrentMap catalog = RUNTIME_OUTPUT.get( + activeData, ignored -> new ConcurrentHashMap<>()); + return catalog.computeIfAbsent( + structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure)); + } + + private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure) { + 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) { + IrisLogging.error(message); + } else { + IrisLogging.warn(message); + } + } + if (!compilation.isAssemblyViable()) { + IrisLogging.error("[StructureGraph:" + structureKey + + "] Graph rejected because deterministic assembly did not complete."); + } + return compilation; + } + + private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure) { + for (long seed : RUNTIME_SAMPLE_SEEDS) { + try { + StructureAssembler assembler = StructureAssembler.forData( + data, structure, new IrisPosition(0, 64, 0)); + StructureAssemblyResult result = assembler.assemble(new RNG(seed)); + if (!result.hasOutput()) { + return false; + } + } catch (Throwable e) { + IrisLogging.reportError(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 new file mode 100644 index 000000000..c58e4a977 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java @@ -0,0 +1,242 @@ +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 new file mode 100644 index 000000000..94585498e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java @@ -0,0 +1,1264 @@ +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/StructureGraphDiagnostic.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphDiagnostic.java new file mode 100644 index 000000000..e6fc5a636 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphDiagnostic.java @@ -0,0 +1,67 @@ +package art.arcane.iris.engine.framework.structure; + +import java.util.Objects; + +public record StructureGraphDiagnostic(Code code, String message) { + public StructureGraphDiagnostic { + Objects.requireNonNull(code); + Objects.requireNonNull(message); + } + + public Severity severity() { + return code.severity(); + } + + public enum Severity { + ERROR, + WARNING + } + + public enum Code { + MISSING_START_POOL(Severity.ERROR), + EMPTY_START_POOL(Severity.ERROR), + MISSING_POOL(Severity.ERROR), + INVALID_MAX_DEPTH(Severity.ERROR), + INVALID_MAX_SIZE(Severity.ERROR), + INVALID_POOL_ENTRY(Severity.ERROR), + INVALID_WEIGHT(Severity.ERROR), + INVALID_CHANCE(Severity.ERROR), + INVALID_THEME(Severity.ERROR), + INVALID_PIECE_RULE(Severity.ERROR), + UNSATISFIABLE_PIECE_RULE(Severity.ERROR), + MISSING_REQUIRED_FALLBACK(Severity.ERROR), + NO_REQUIRED_TERMINAL(Severity.ERROR), + NON_PORTABLE_METADATA(Severity.ERROR), + MISSING_PIECE(Severity.ERROR), + MISSING_OBJECT(Severity.ERROR), + INVALID_OBJECT_BOUNDS(Severity.ERROR), + INVALID_CONNECTOR(Severity.ERROR), + INVALID_CONNECTOR_METADATA(Severity.ERROR), + INVALID_CONNECTOR_POSITION(Severity.ERROR), + INVALID_CONNECTOR_DIRECTION(Severity.ERROR), + INVALID_PLANAR_CELL_SIZE(Severity.ERROR), + INVALID_PLANAR_WORKCELL(Severity.ERROR), + INVALID_PLANAR_OBJECT_SIZE(Severity.ERROR), + INVALID_PLANAR_CONNECTOR(Severity.ERROR), + NON_PORTABLE_CONNECTOR(Severity.ERROR), + MISSING_CONNECTOR_POOL(Severity.ERROR), + FALLBACK_CYCLE(Severity.ERROR), + NO_ENABLED_START_PIECE(Severity.ERROR), + NO_VIABLE_START_PIECE(Severity.WARNING), + NO_COMPATIBLE_CONNECTOR(Severity.WARNING), + UNREACHABLE_POOL(Severity.WARNING), + UNREACHABLE_PIECE(Severity.WARNING), + ASSEMBLY_RUNTIME_FAILURE(Severity.ERROR), + ASSEMBLY_PIECE_CAP_REACHED(Severity.WARNING); + + private final Severity severity; + + Code(Severity severity) { + this.severity = severity; + } + + public Severity severity() { + return severity; + } + } +} 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 new file mode 100644 index 000000000..e9688dcea --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java @@ -0,0 +1,74 @@ +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 data.load(IrisJigsawPool.class, key, false); + } + + @Override + public IrisJigsawPiece loadPiece(String key) { + return data.load(IrisJigsawPiece.class, key, false); + } + + @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/StructureGraphValidationException.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationException.java new file mode 100644 index 000000000..fc2b25643 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationException.java @@ -0,0 +1,11 @@ +package art.arcane.iris.engine.framework.structure; + +public final class StructureGraphValidationException extends IllegalArgumentException { + public StructureGraphValidationException(String message) { + super(message); + } + + public StructureGraphValidationException(String message, Throwable cause) { + super(message, cause); + } +} 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 new file mode 100644 index 000000000..f78a69716 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java @@ -0,0 +1,201 @@ +/* + * 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/image/CompiledIrisImageMap.java b/src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java new file mode 100644 index 000000000..3fdf34378 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java @@ -0,0 +1,424 @@ +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 new file mode 100644 index 000000000..9d942878a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/image/IrisImageMapCompiler.java @@ -0,0 +1,825 @@ +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 new file mode 100644 index 000000000..5171993c1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/image/IrisImageMapMaskSampler.java @@ -0,0 +1,113 @@ +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 new file mode 100644 index 000000000..8cf796869 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java @@ -0,0 +1,386 @@ +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/image/IrisImageMapSourceMetadata.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java new file mode 100644 index 000000000..71a9bfce4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java @@ -0,0 +1,18 @@ +package art.arcane.iris.engine.image; + +import art.arcane.iris.engine.object.image.IrisImageColorMode; + +public record IrisImageMapSourceMetadata( + String format, + IrisImageColorMode colorMode, + int width, + int height, + int colorComponents, + int channels, + int bitDepth, + boolean alpha, + double minimumAlpha, + double maximumAlpha, + String decodedContentHash +) { +} diff --git a/src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java new file mode 100644 index 000000000..9c267b4a9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java @@ -0,0 +1,35 @@ +package art.arcane.iris.engine.image; + +import java.util.List; + +public final class IrisImageMapValidationException extends IllegalArgumentException { + private final List diagnostics; + + public IrisImageMapValidationException(String diagnostic) { + this(List.of(diagnostic)); + } + + public IrisImageMapValidationException(List diagnostics) { + super(message(diagnostics)); + if (diagnostics == null || diagnostics.isEmpty()) { + throw new IllegalArgumentException("Image-map validation requires at least one diagnostic"); + } + this.diagnostics = List.copyOf(diagnostics); + } + + public IrisImageMapValidationException(String diagnostic, Throwable cause) { + super(diagnostic, cause); + this.diagnostics = List.of(diagnostic); + } + + public List getDiagnostics() { + return diagnostics; + } + + private static String message(List diagnostics) { + if (diagnostics == null || diagnostics.isEmpty()) { + return "Image-map validation failed"; + } + return String.join("; ", diagnostics); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java b/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java new file mode 100644 index 000000000..a9e964f2e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java @@ -0,0 +1,313 @@ +/* + * 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.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterSlice; + +import java.util.Arrays; + +public final class CarveOrphanSweep { + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + private static final int BAND_FLOOR_MARGIN = 4; + private static final int MAX_ORPHAN_CELLS = 16; + private static final MatterCavern ORPHAN_CAVERN = new MatterCavern(true, "", (byte) 0); + private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(SweepScratch::new); + + public interface CarveAccess { + boolean isCarved(int localX, int y, int localZ); + + void markCarved(int localX, int y, int localZ); + + default boolean isProtected(int localX, int y, int localZ) { + return false; + } + + /** + * Cheap pre-check: may any block in [minY, maxY] be carved at all? Default true keeps + * every implementor correct; the mantle-backed access answers from section slice + * presence so an uncarved chunk skips the full band fill + scan. + */ + default boolean mayContainCarvedCells(int minY, int maxY) { + return true; + } + } + + private CarveOrphanSweep() { + } + + static int sweepChunk( + MantleChunk chunk, + int[] surfaceHeights, + int maxSurfaceBreakDepth, + int worldCeilingY, + int[] surfaceFluidBoundaryStartY, + int fluidHeight + ) { + if (chunk == null) { + return 0; + } + + return sweep(surfaceHeights, maxSurfaceBreakDepth, 0, worldCeilingY, + new MantleCarveAccess(chunk, surfaceFluidBoundaryStartY, fluidHeight)); + } + + public static int sweep(int[] surfaceHeights, int maxSurfaceBreakDepth, int worldFloorY, int worldCeilingY, CarveAccess access) { + if (surfaceHeights == null || surfaceHeights.length < CHUNK_AREA || access == null) { + return 0; + } + + int minSurfaceY = Integer.MAX_VALUE; + int maxSurfaceY = Integer.MIN_VALUE; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + int surfaceY = surfaceHeights[columnIndex]; + if (surfaceY < minSurfaceY) { + minSurfaceY = surfaceY; + } + if (surfaceY > maxSurfaceY) { + maxSurfaceY = surfaceY; + } + } + + int bandTop = Math.min(worldCeilingY, maxSurfaceY); + int bandFloor = Math.max(worldFloorY + 1, minSurfaceY - Math.max(0, maxSurfaceBreakDepth) - BAND_FLOOR_MARGIN); + if (bandTop < bandFloor) { + return 0; + } + + if (!access.mayContainCarvedCells(bandFloor, bandTop)) { + // Same early return the carvedPresent check reaches, without zero-filling and + // scanning the whole band first. + return 0; + } + + int bandHeight = bandTop - bandFloor + 1; + int cellCount = bandHeight * CHUNK_AREA; + SweepScratch scratch = SCRATCH.get(); + scratch.prepare(cellCount); + long[] solid = scratch.solid; + long[] visited = scratch.visited; + int[] stack = scratch.stack; + int[] component = scratch.component; + + boolean carvedPresent = false; + for (int y = bandFloor; y <= bandTop; y++) { + int layer = (y - bandFloor) * CHUNK_AREA; + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + if (y > surfaceHeights[columnIndex]) { + continue; + } + if (access.isCarved(localX, y, localZ)) { + carvedPresent = true; + continue; + } + + setBit(solid, layer + columnIndex); + } + } + } + + if (!carvedPresent) { + return 0; + } + + int marked = 0; + for (int rootIndex = 0; rootIndex < cellCount; rootIndex++) { + if (!getBit(solid, rootIndex) || getBit(visited, rootIndex)) { + continue; + } + + setBit(visited, rootIndex); + stack[0] = rootIndex; + int stackSize = 1; + int componentSize = 0; + boolean anchored = false; + + while (stackSize > 0) { + int current = stack[--stackSize]; + int columnIndex = current & (CHUNK_AREA - 1); + int localX = columnIndex >>> 4; + int localZ = columnIndex & (CHUNK_SIZE - 1); + int y = bandFloor + (current / CHUNK_AREA); + + if (!anchored) { + if (access.isProtected(localX, y, localZ)) { + anchored = true; + } else if (localX == 0 || localX == CHUNK_SIZE - 1 || localZ == 0 || localZ == CHUNK_SIZE - 1) { + anchored = true; + } else if (y == bandFloor && isSolidBelowBand(access, surfaceHeights, columnIndex, localX, localZ, bandFloor - 1, worldFloorY)) { + anchored = true; + } else if (componentSize >= MAX_ORPHAN_CELLS) { + anchored = true; + } else { + component[componentSize++] = current; + } + } + + if (y > bandFloor) { + stackSize = push(solid, visited, stack, stackSize, current - CHUNK_AREA); + } + if (y < bandTop) { + stackSize = push(solid, visited, stack, stackSize, current + CHUNK_AREA); + } + if (localX > 0) { + stackSize = push(solid, visited, stack, stackSize, current - CHUNK_SIZE); + } + if (localX < CHUNK_SIZE - 1) { + stackSize = push(solid, visited, stack, stackSize, current + CHUNK_SIZE); + } + if (localZ > 0) { + stackSize = push(solid, visited, stack, stackSize, current - 1); + } + if (localZ < CHUNK_SIZE - 1) { + stackSize = push(solid, visited, stack, stackSize, current + 1); + } + } + + if (anchored) { + continue; + } + + for (int index = 0; index < componentSize; index++) { + int cell = component[index]; + int columnIndex = cell & (CHUNK_AREA - 1); + access.markCarved(columnIndex >>> 4, bandFloor + (cell / CHUNK_AREA), columnIndex & (CHUNK_SIZE - 1)); + marked++; + } + } + + return marked; + } + + private static int push(long[] solid, long[] visited, int[] stack, int stackSize, int neighbor) { + if (!getBit(solid, neighbor) || getBit(visited, neighbor)) { + return stackSize; + } + + setBit(visited, neighbor); + stack[stackSize] = neighbor; + return stackSize + 1; + } + + private static boolean isSolidBelowBand(CarveAccess access, int[] surfaceHeights, int columnIndex, int localX, int localZ, int belowY, int worldFloorY) { + if (belowY < worldFloorY || belowY > surfaceHeights[columnIndex]) { + return false; + } + + return !access.isCarved(localX, belowY, localZ); + } + + private static boolean getBit(long[] bits, int index) { + return (bits[index >>> 6] & (1L << (index & 63))) != 0L; + } + + private static void setBit(long[] bits, int index) { + bits[index >>> 6] |= 1L << (index & 63); + } + + private static final class MantleCarveAccess implements CarveAccess { + private final MantleChunk chunk; + private final int[] surfaceFluidBoundaryStartY; + private final int fluidHeight; + private MatterSlice cachedSlice; + private int cachedSectionIndex = -1; + + private MantleCarveAccess(MantleChunk chunk, int[] surfaceFluidBoundaryStartY, int fluidHeight) { + this.chunk = chunk; + this.surfaceFluidBoundaryStartY = surfaceFluidBoundaryStartY; + this.fluidHeight = fluidHeight; + } + + @Override + public boolean isCarved(int localX, int y, int localZ) { + MatterSlice cavernSlice = resolveSlice(y >> 4); + if (cavernSlice == null) { + return false; + } + + MatterCavern cavern = cavernSlice.get(localX, y & 15, localZ); + return cavern != null && cavern.isCavern(); + } + + @Override + public void markCarved(int localX, int y, int localZ) { + chunk.getOrCreate(y >> 4).slice(MatterCavern.class).set(localX, y & 15, localZ, ORPHAN_CAVERN); + cachedSectionIndex = -1; + cachedSlice = null; + } + + @Override + public boolean isProtected(int localX, int y, int localZ) { + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + return SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight); + } + + @Override + public boolean mayContainCarvedCells(int minY, int maxY) { + int minSection = Math.max(0, minY >> 4); + int maxSection = Math.min(chunk.sectionCount() - 1, maxY >> 4); + for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { + Matter section = chunk.get(sectionIndex); + if (section != null && section.getSlice(MatterCavern.class) != null) { + return true; + } + } + return false; + } + + private MatterSlice resolveSlice(int sectionIndex) { + if (sectionIndex == cachedSectionIndex) { + return cachedSlice; + } + + Matter section = sectionIndex >= 0 && sectionIndex < chunk.sectionCount() ? chunk.get(sectionIndex) : null; + cachedSlice = section == null ? null : section.getSlice(MatterCavern.class); + cachedSectionIndex = sectionIndex; + return cachedSlice; + } + } + + private static final class SweepScratch { + private final int[] component = new int[MAX_ORPHAN_CELLS]; + private long[] solid = new long[0]; + private long[] visited = new long[0]; + private int[] stack = new int[0]; + + private void prepare(int cellCount) { + int words = (cellCount + 63) >>> 6; + if (solid.length < words) { + solid = new long[words]; + visited = new long[words]; + } else { + Arrays.fill(solid, 0, words, 0L); + Arrays.fill(visited, 0, words, 0L); + } + + if (stack.length < cellCount) { + stack = new int[cellCount]; + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java new file mode 100644 index 000000000..912663a19 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java @@ -0,0 +1,73 @@ +/* + * 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.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterSlice; + +final class CaveCarveScratch { + final int[] columnMaxY = new int[256]; + final int[] fluidMaxY = new int[256]; + final int[] surfaceBreakFloorY = new int[256]; + final boolean[] surfaceBreakColumn = new boolean[256]; + final boolean[] surfaceCeilingColumn = new boolean[256]; + final double[] columnThreshold = new double[256]; + final double[] passThreshold = new double[256]; + final double[] fullWeights = new double[256]; + final double[] clampedColumnWeights = new double[256]; + final int[] activeColumnIndices = new int[256]; + final int[] activeColumnTopY = new int[256]; + final int[] planeColumnIndices = new int[256]; + final double[] planeThresholdLimit = new double[256]; + final boolean[] planeCarve = new boolean[256]; + final double[] adaptivePlaneDensity = new double[81]; + final double[] adaptivePlanePrediction = new double[256]; + final double[] adaptivePlaneAmbiguity = new double[256]; + final int[] adaptivePlaneSampleBounds = new int[4]; + final int[] adaptiveCellX = new int[256]; + final int[] adaptiveCellZ = new int[256]; + final int[] adaptiveRow0 = new int[256]; + final int[] adaptiveRow1 = new int[256]; + final double[] adaptiveTx = new double[256]; + final double[] adaptiveTz = new double[256]; + final boolean[] warpCacheSet = new boolean[256]; + final int[] warpCacheX = new int[256]; + final int[] warpCacheY = new int[256]; + final int[] warpCacheZ = new int[256]; + final double[] warpCacheA = new double[256]; + final double[] warpCacheB = new double[256]; + final int[] tileIndices = new int[4]; + final int[] tileLocalX = new int[4]; + final int[] tileLocalZ = new int[4]; + final int[] tileTopY = new int[4]; + CaveFieldModuleState[] activeModules = new CaveFieldModuleState[0]; + double[] activeModuleRemainingMin = new double[0]; + double[] activeModuleRemainingMax = new double[0]; + int activeModulesY = Integer.MIN_VALUE; + int activeModuleCount; + double[] verticalEdgeFade = new double[0]; + double[] surfaceClosureThreshold = new double[0]; + MatterCavern[] matterByY = new MatterCavern[0]; + Matter[] sectionMatter = new Matter[0]; + MatterSlice[] sectionSlices = new MatterSlice[0]; + int adaptiveGeometryStep = -1; + int adaptiveGeometryAxisCells = -1; + boolean fullWeightsInitialized; +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java new file mode 100644 index 000000000..269876586 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java @@ -0,0 +1,58 @@ +/* + * 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.engine.object.terrain.carving.IrisCaveFieldModule; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.util.project.noise.CNG; + +final class CaveFieldModuleState { + final CNG density; + final int minY; + final int maxY; + final double weight; + final double threshold; + final boolean invert; + final double minContribution; + final double maxContribution; + + CaveFieldModuleState(IrisCaveFieldModule module, CNG density) { + IrisRange range = module.getVerticalRange(); + this.density = density; + this.minY = (int) Math.floor(range.getMin()); + this.maxY = (int) Math.ceil(range.getMax()); + this.weight = module.getWeight(); + this.threshold = module.getThreshold(); + this.invert = module.isInvert(); + double rawMin = invert ? threshold - 1D : -1D - threshold; + double rawMax = invert ? threshold + 1D : 1D - threshold; + this.minContribution = rawMin * weight; + this.maxContribution = rawMax * weight; + } + + double sample(double x, int y, double z) { + double sampled = density.noiseFastSigned3D(x, y, z); + return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; + } + + double sample(double x, double y, double z) { + double sampled = density.noiseFastSigned3D(x, y, z); + return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java new file mode 100644 index 000000000..ca98541ed --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java @@ -0,0 +1,120 @@ +/* + * 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.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterSlice; + +import java.util.BitSet; +import java.util.IdentityHashMap; +import java.util.Map; + +final class CaveFluidSupportPlan { + private final IdentityHashMap groups = new IdentityHashMap<>(); + + void add(int localX, int y, int localZ, MatterCavern fluid, MatterCavern air) { + FluidCandidateGroup group = groups.computeIfAbsent(fluid, key -> new FluidCandidateGroup(fluid, air)); + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + group.positions.set((y << 8) | columnIndex); + } + + void resolve(MantleChunk chunk) { + if (chunk == null) { + groups.clear(); + return; + } + + for (Map.Entry entry : groups.entrySet()) { + FluidCandidateGroup group = entry.getValue(); + for (int position = group.positions.nextSetBit(0); position >= 0; position = group.positions.nextSetBit(position + 1)) { + int y = position >>> 8; + int columnIndex = position & 255; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + MatterCavern current = getCavern(chunk, localX, y, localZ); + if (current != group.fluid || hasCupSupport(chunk, localX, y, localZ)) { + continue; + } + + Matter section = chunk.get(y >> 4); + MatterSlice cavernSlice = section.getSlice(MatterCavern.class); + cavernSlice.set(localX, y & 15, localZ, group.air); + } + } + groups.clear(); + } + + private static boolean hasCupSupport(MantleChunk chunk, int localX, int y, int localZ) { + if (localX <= 0 || localX >= 15 || localZ <= 0 || localZ >= 15 + || y <= 1 || !isSolid(chunk, localX, y - 1, localZ) + || !isSolid(chunk, localX, y - 2, localZ)) { + return false; + } + + int support = 0; + if (isSolid(chunk, localX + 1, y, localZ)) { + support++; + } + if (isSolid(chunk, localX - 1, y, localZ)) { + support++; + } + if (isSolid(chunk, localX, y, localZ + 1)) { + support++; + } + if (isSolid(chunk, localX, y, localZ - 1)) { + support++; + } + if (isSolid(chunk, localX, y + 1, localZ)) { + support++; + } + return support >= 4; + } + + private static boolean isSolid(MantleChunk chunk, int localX, int y, int localZ) { + if (localX < 0 || localX >= 16 || localZ < 0 || localZ >= 16) { + return false; + } + MatterCavern cavern = getCavern(chunk, localX, y, localZ); + return cavern == null || !cavern.isCavern(); + } + + private static MatterCavern getCavern(MantleChunk chunk, int localX, int y, int localZ) { + Matter section = chunk.get(y >> 4); + if (section == null) { + return null; + } + + MatterSlice cavernSlice = section.getSlice(MatterCavern.class); + return cavernSlice == null ? null : cavernSlice.get(localX, y & 15, localZ); + } + + private static final class FluidCandidateGroup { + private final MatterCavern fluid; + private final MatterCavern air; + private final BitSet positions = new BitSet(); + + private FluidCandidateGroup(MatterCavern fluid, MatterCavern air) { + this.fluid = fluid; + this.air = air; + } + } +} 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 new file mode 100644 index 000000000..8f14ee5a9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java @@ -0,0 +1,286 @@ +/* + * 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.data.cache.Cache; +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; + +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; + + 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); + } + + 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; + } + + void discard() { + mutations.clear(); + bufferedBlocks.clear(); + blockWrites = 0; + } + + int getCaveCeiling(int x, int z) { + long key = Cache.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 = Cache.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); + } + + 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/FloatingIslandSampleResolver.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java new file mode 100644 index 000000000..21b8ef106 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -0,0 +1,74 @@ +/* + * 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.data.cache.Cache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import org.jetbrains.annotations.Nullable; + +final class FloatingIslandSampleResolver implements IslandObjectPlacer.SampleProvider { + private final IrisData data; + private final Engine engine; + private final int chunkHeight; + private final long baseSeed; + private final FloatingIslandBoundarySampler boundarySampler; + private final Long2ObjectOpenHashMap sampleCache; + private final LongOpenHashSet resolvedSamples; + + FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler) { + this.data = engineMantle.getData(); + this.engine = engineMantle.getEngine(); + this.chunkHeight = engine.getHeight(); + this.baseSeed = engine.getSeedManager().getTerrain() ^ IrisFloatingChildBiomeModifier.FLOATING_BASE_SEED_SALT; + this.boundarySampler = boundarySampler; + this.sampleCache = new Long2ObjectOpenHashMap<>(); + this.resolvedSamples = new LongOpenHashSet(); + } + + @Override + public @Nullable FloatingIslandSample sample(int x, int z) { + long key = Cache.key(x, z); + if (resolvedSamples.contains(key)) { + return sampleCache.get(key); + } + IrisBiome parent = parent(x, z); + if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) { + resolvedSamples.add(key); + return null; + } + FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler); + resolvedSamples.add(key); + if (sample != null) { + sampleCache.put(key, sample); + } + return sample; + } + + @Nullable IrisBiome parent(int x, int z) { + return boundarySampler.parent(x, 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 new file mode 100644 index 000000000..b956544bd --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java @@ -0,0 +1,211 @@ +/* + * 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; + +final class FloatingObjectPlacementTransaction implements IObjectPlacer { + private final IslandObjectPlacer delegate; + private final KList mutations; + private final Map bufferedBlocks; + private int blockWrites; + + FloatingObjectPlacementTransaction(IslandObjectPlacer delegate) { + this.delegate = delegate; + this.mutations = new KList<>(); + this.bufferedBlocks = new HashMap<>(); + } + + 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; + } + + 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(); + } + + 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 new file mode 100644 index 000000000..696305827 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java @@ -0,0 +1,159 @@ +/* + * 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.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; + +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; + + GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag) { + this.delegate = delegate; + this.tag = tag; + } + + 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; + } + } + + 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); + IrisLogging.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); + IrisLogging.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); + IrisLogging.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); + IrisLogging.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/IrisCaveCarver3D.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java new file mode 100644 index 000000000..962aee6c9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -0,0 +1,2381 @@ +/* + * 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.mantle.MantleWriter; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveFieldModule; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.engine.object.noise.IrisStyledRange; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.math.M; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterSlice; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class IrisCaveCarver3D { + private static final byte LIQUID_AIR = 0; + private static final byte LIQUID_FLUID = 1; + private static final byte LIQUID_LAVA = 2; + private static final byte LIQUID_FORCED_AIR = 3; + private static final int ADAPTIVE_MIN_PLANE_COLUMNS = 16; + private static final int ADAPTIVE_DEEP_SAMPLE_STEP = 8; + private static final double ADAPTIVE_LOCAL_RANGE_SCALE = 0.125D; + private static final double ADAPTIVE_DEEP_MARGIN_BOOST = 0.015D; + private static final int SURFACE_CEILING_FADE_DEPTH = 12; + private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; + + private final Engine engine; + private final IrisData data; + private final IrisCaveProfile profile; + private final CNG baseDensity; + private final CNG detailDensity; + private final CNG warpDensity; + private final CNG surfaceBreakDensity; + private final RNG thresholdRng; + private final CaveFieldModuleState[] modules; + private final double inverseNormalization; + private final MatterCavern carveAir; + private final MatterCavern carveFluid; + private final MatterCavern carveLava; + private final MatterCavern carveForcedAir; + private final double normalizationFactor; + private final double baseWeight; + private final double detailWeight; + private final double detailMinContribution; + private final double detailMaxContribution; + private final double warpStrength; + private final boolean hasWarp; + private final boolean hasModules; + private final int warpResolution; + private final boolean allowFluid; + private final boolean fluidRequiresFloor; + private final int fluidMinDepthBelowSurface; + private final int fluidHeight; + private final int aquiferCeilingY; + private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); + + public IrisCaveCarver3D(Engine engine, IrisCaveProfile profile) { + this.engine = engine; + this.data = engine.getData(); + this.profile = profile; + this.carveAir = new MatterCavern(true, "", LIQUID_AIR); + this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); + this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); + this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR); + List moduleStates = new ArrayList<>(); + + RNG baseRng = new RNG(engine.getSeedManager().getCarve()); + this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); + this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); + this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); + this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); + this.thresholdRng = baseRng.nextParallelRNG(489_112); + this.baseWeight = profile.getBaseWeight(); + this.detailWeight = profile.getDetailWeight(); + this.warpStrength = profile.getWarpStrength(); + this.hasWarp = this.warpStrength > 0D; + this.warpResolution = 2; + this.allowFluid = profile.isAllowFluid(); + this.fluidRequiresFloor = profile.isFluidRequiresFloor(); + this.fluidMinDepthBelowSurface = Math.max(0, profile.getFluidMinDepthBelowSurface()); + this.fluidHeight = engine.getDimension().getFluidHeight(); + this.aquiferCeilingY = engine.getHeight() - 1; + + double weight = Math.abs(baseWeight) + Math.abs(detailWeight); + int index = 0; + for (IrisCaveFieldModule module : profile.getModules()) { + CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); + moduleStates.add(state); + weight += Math.abs(state.weight); + index++; + } + + this.modules = moduleStates.toArray(new CaveFieldModuleState[0]); + double normalization = weight <= 0 ? 1 : weight; + normalizationFactor = normalization; + inverseNormalization = 1D / normalization; + hasModules = modules.length > 0; + detailMinContribution = -detailWeight; + detailMaxContribution = detailWeight; + } + + public int carve(MantleWriter writer, int chunkX, int chunkZ) { + CaveCarveScratch scratch = scratchCache.get(); + if (!scratch.fullWeightsInitialized) { + Arrays.fill(scratch.fullWeights, 1D); + scratch.fullWeightsInitialized = true; + } + return carve(writer, chunkX, chunkZ, scratch.fullWeights, 0D, 0D, null, null); + } + + public int carve( + MantleWriter writer, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty + ) { + return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, null, null); + } + + public int carve( + MantleWriter writer, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + IrisRange worldYRange + ) { + return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, null); + } + + public int carve( + MantleWriter writer, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + IrisRange worldYRange, + int[] precomputedSurfaceHeights + ) { + return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, precomputedSurfaceHeights, null); + } + + public int carve( + MantleWriter writer, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + IrisRange worldYRange, + int[] precomputedSurfaceHeights, + IrisRange overrideVerticalRange + ) { + CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); + int carved = carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, + worldYRange, precomputedSurfaceHeights, null, overrideVerticalRange, fluidSupportPlan); + fluidSupportPlan.resolve(writer.acquireChunk(chunkX, chunkZ)); + return carved; + } + + int carve( + MantleWriter writer, + int chunkX, + int chunkZ, + double[] columnWeights, + double minWeight, + double thresholdPenalty, + IrisRange worldYRange, + int[] precomputedSurfaceHeights, + int[] surfaceFluidBoundaryStartY, + IrisRange overrideVerticalRange, + CaveFluidSupportPlan fluidSupportPlan + ) { + PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); + try { + CaveCarveScratch scratch = scratchCache.get(); + if (columnWeights == null || columnWeights.length < 256) { + if (!scratch.fullWeightsInitialized) { + Arrays.fill(scratch.fullWeights, 1D); + scratch.fullWeightsInitialized = true; + } + columnWeights = scratch.fullWeights; + } + + double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); + double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); + int worldHeight = writer.getMantle().getWorldHeight(); + IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.getVerticalRange(); + int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.getMin())); + int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.getMax())); + if (worldYRange != null) { + int worldMinHeight = engine.getWorld().minHeight(); + int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); + int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); + minY = Math.max(minY, rangeMinY); + maxY = Math.min(maxY, rangeMaxY); + } + int sampleStep = Math.max(1, profile.getSampleStep()); + boolean exactSampling = sampleStep <= 2; + boolean adaptiveSampling = exactSampling && profile.isAdaptiveSampling(); + int adaptiveSampleStep = Math.max(2, profile.getAdaptiveSampleStep()); + double adaptiveThresholdMargin = Math.max(0D, profile.getAdaptiveThresholdMargin()); + int surfaceClearance = Math.max(0, profile.getSurfaceClearance()); + int surfaceBreakDepth = Math.max(0, profile.getSurfaceBreakDepth()); + double surfaceBreakNoiseThreshold = profile.getSurfaceBreakNoiseThreshold(); + double surfaceBreakThresholdBoost = Math.max(0, profile.getSurfaceBreakThresholdBoost()); + boolean allowSurfaceBreak = profile.isAllowSurfaceBreak(); + if (maxY < minY) { + return 0; + } + + MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); + if (chunk == null) { + return 0; + } + + int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int[] columnMaxY = scratch.columnMaxY; + int[] fluidMaxY = scratch.fluidMaxY; + int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; + boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; + boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; + double[] columnThreshold = scratch.columnThreshold; + double[] clampedWeights = scratch.clampedColumnWeights; + double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); + prepareSurfaceClosureThresholdTable(scratch, minY, maxY); + MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); + prepareSectionCaches(scratch, minY, maxY); + + // IrisStyledRange.get() resolves its CNG per call, which costs a cache-key allocation, + // a capturing lambda and a shared LRU touch. The CNG is constant for (thresholdRng, data), + // so resolve it once here and replicate the min==max / isFlat short circuits verbatim. + IrisStyledRange densityThreshold = profile.getDensityThreshold(); + double thresholdMin = densityThreshold.getMin(); + double thresholdMax = densityThreshold.getMax(); + double thresholdBias = profile.getThresholdBias(); + CNG thresholdDensity = null; + double constantThreshold = 0D; + if (thresholdMin == thresholdMax) { + constantThreshold = thresholdMin; + } else if (densityThreshold.getStyle().isFlat()) { + constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); + } else { + thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); + } + + for (int lx = 0; lx < 16; lx++) { + int x = x0 + lx; + for (int lz = 0; lz < 16; lz++) { + int z = z0 + lz; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + int columnSurfaceY; + if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > index) { + columnSurfaceY = precomputedSurfaceHeights[index]; + } else { + columnSurfaceY = engine.getHeight(x, z); + } + int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; + int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); + boolean breakColumn = allowSurfaceBreak + && surfaceBreakDensity.noiseFastSigned2D(x, z) >= surfaceBreakNoiseThreshold; + int columnTopY = breakColumn + ? Math.min(maxY, Math.max(minY, columnSurfaceY)) + : clearanceTopY; + + columnMaxY[index] = columnTopY; + fluidMaxY[index] = allowFluid + ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) + : Integer.MIN_VALUE; + surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); + surfaceBreakColumn[index] = breakColumn; + surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; + columnThreshold[index] = (thresholdDensity == null + ? constantThreshold + : thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z)) - thresholdBias; + clampedWeights[index] = clampColumnWeight(columnWeights[index]); + } + } + + int carved; + if (exactSampling) { + if (adaptiveSampling) { + carved = carvePassAdaptive( + chunk, + x0, + z0, + minY, + maxY, + adaptiveSampleStep, + adaptiveThresholdMargin, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } else { + carved = carvePassExact( + chunk, + x0, + z0, + minY, + maxY, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } + } else { + int latticeStep = sampleStep; + carved = carvePassLattice( + chunk, + x0, + z0, + minY, + maxY, + latticeStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { + carved += carvePassFallback( + chunk, + x0, + z0, + minY, + maxY, + sampleStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } + } + + return carved; + } finally { + engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); + } + } + + private int carvePassExact( + MantleChunk chunk, + int x0, + int z0, + int minY, + int maxY, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + MatterCavern[] matterByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + double[] passThreshold = scratch.passThreshold; + int[] activeColumnIndices = scratch.activeColumnIndices; + int[] activeColumnTopY = scratch.activeColumnTopY; + int activeColumnCount = 0; + + for (int index = 0; index < 256; index++) { + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight || columnMaxY[index] < minY) { + passThreshold[index] = Double.NaN; + continue; + } + + passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + activeColumnIndices[activeColumnCount] = index; + activeColumnTopY[activeColumnCount] = columnMaxY[index]; + activeColumnCount++; + } + + if (activeColumnCount == 0) { + return 0; + } + + int[] planeColumnIndices = scratch.planeColumnIndices; + double[] planeThresholdLimit = scratch.planeThresholdLimit; + boolean[] planeCarve = scratch.planeCarve; + int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); + int maxSection = PowerOfTwoCoordinates.floorDivPow2(maxY, 4); + + for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { + int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); + int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); + MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); + + for (int y = sectionMinY; y <= sectionMaxY; y++) { + int planeCount = 0; + for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { + if (activeColumnTopY[activeIndex] < y) { + continue; + } + + int columnIndex = activeColumnIndices[activeIndex]; + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight)) { + continue; + } + planeColumnIndices[planeCount] = columnIndex; + double localThreshold = passThreshold[columnIndex]; + if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[y - minY]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); + planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; + planeCount++; + } + + if (planeCount == 0) { + continue; + } + + classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + int fadeIndex = y - minY; + int localY = y & 15; + MatterCavern verticalMatter = matterByY[fadeIndex]; + + if (skipExistingCarved) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + if (cavernSlice.get(localX, localY, localZ) != null) { + continue; + } + + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + carved++; + } + continue; + } + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + carved++; + } + } + } + + return carved; + } + + private int carvePassAdaptive( + MantleChunk chunk, + int x0, + int z0, + int minY, + int maxY, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + MatterCavern[] matterByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + double[] passThreshold = scratch.passThreshold; + int[] activeColumnIndices = scratch.activeColumnIndices; + int[] activeColumnTopY = scratch.activeColumnTopY; + int activeColumnCount = 0; + + for (int index = 0; index < 256; index++) { + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight || columnMaxY[index] < minY) { + passThreshold[index] = Double.NaN; + continue; + } + + passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + activeColumnIndices[activeColumnCount] = index; + activeColumnTopY[activeColumnCount] = columnMaxY[index]; + activeColumnCount++; + } + + if (activeColumnCount == 0) { + return 0; + } + + int[] planeColumnIndices = scratch.planeColumnIndices; + double[] planeThresholdLimit = scratch.planeThresholdLimit; + boolean[] planeCarve = scratch.planeCarve; + int minSection = PowerOfTwoCoordinates.floorDivPow2(minY, 4); + int maxSection = PowerOfTwoCoordinates.floorDivPow2(maxY, 4); + int effectiveAdaptiveSampleStep = Math.max(adaptiveSampleStep, ADAPTIVE_DEEP_SAMPLE_STEP); + double effectiveAdaptiveThresholdMargin = resolveAdaptivePlaneThresholdMargin( + adaptiveThresholdMargin, + adaptiveSampleStep, + effectiveAdaptiveSampleStep + ); + + for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { + int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); + int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); + MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); + + for (int y = sectionMinY; y <= sectionMaxY; y++) { + int planeCount = 0; + for (int activeIndex = 0; activeIndex < activeColumnCount; activeIndex++) { + if (activeColumnTopY[activeIndex] < y) { + continue; + } + + int columnIndex = activeColumnIndices[activeIndex]; + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight)) { + continue; + } + planeColumnIndices[planeCount] = columnIndex; + double localThreshold = passThreshold[columnIndex]; + if (surfaceBreakColumn[columnIndex] && y >= surfaceBreakFloorY[columnIndex]) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[y - minY]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, columnIndex, y, minY); + planeThresholdLimit[planeCount] = localThreshold * normalizationFactor; + planeCount++; + } + + if (planeCount == 0) { + continue; + } + + classifyDensityPlaneAdaptive( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + effectiveAdaptiveSampleStep, + effectiveAdaptiveThresholdMargin + ); + int fadeIndex = y - minY; + int localY = y & 15; + MatterCavern verticalMatter = matterByY[fadeIndex]; + + if (skipExistingCarved) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + if (cavernSlice.get(localX, localY, localZ) != null) { + continue; + } + + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + carved++; + } + continue; + } + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + if (!planeCarve[planeIndex]) { + continue; + } + + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; + MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + columnIndex, fluidMaxY, localThreshold); + writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + carved++; + } + } + } + + return carved; + } + + private double resolveAdaptivePlaneThresholdMargin( + double adaptiveThresholdMargin, + int adaptiveSampleStep, + int effectiveAdaptiveSampleStep + ) { + if (effectiveAdaptiveSampleStep <= adaptiveSampleStep) { + return adaptiveThresholdMargin; + } + + return adaptiveThresholdMargin + ((effectiveAdaptiveSampleStep - adaptiveSampleStep) * ADAPTIVE_DEEP_MARGIN_BOOST); + } + + private int carvePassLattice( + MantleChunk chunk, + int x0, + int z0, + int minY, + int maxY, + int latticeStep, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + MatterCavern[] matterByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + double[] passThreshold = scratch.passThreshold; + int[] tileIndices = scratch.tileIndices; + int[] tileLocalX = scratch.tileLocalX; + int[] tileLocalZ = scratch.tileLocalZ; + int[] tileTopY = scratch.tileTopY; + + for (int index = 0; index < 256; index++) { + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight || columnMaxY[index] < minY) { + passThreshold[index] = Double.NaN; + continue; + } + passThreshold[index] = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + } + + for (int lx = 0; lx < 16; lx += 2) { + int x = x0 + lx; + int lx1 = lx + 1; + for (int lz = 0; lz < 16; lz += 2) { + int z = z0 + lz; + int lz1 = lz + 1; + int activeColumns = 0; + + int index00 = PowerOfTwoCoordinates.packLocal16(lx, lz); + if (!Double.isNaN(passThreshold[index00])) { + tileIndices[activeColumns] = index00; + tileLocalX[activeColumns] = lx; + tileLocalZ[activeColumns] = lz; + tileTopY[activeColumns] = columnMaxY[index00]; + activeColumns++; + } + + int index01 = PowerOfTwoCoordinates.packLocal16(lx, lz1); + if (!Double.isNaN(passThreshold[index01])) { + tileIndices[activeColumns] = index01; + tileLocalX[activeColumns] = lx; + tileLocalZ[activeColumns] = lz1; + tileTopY[activeColumns] = columnMaxY[index01]; + activeColumns++; + } + + int index10 = PowerOfTwoCoordinates.packLocal16(lx1, lz); + if (!Double.isNaN(passThreshold[index10])) { + tileIndices[activeColumns] = index10; + tileLocalX[activeColumns] = lx1; + tileLocalZ[activeColumns] = lz; + tileTopY[activeColumns] = columnMaxY[index10]; + activeColumns++; + } + + int index11 = PowerOfTwoCoordinates.packLocal16(lx1, lz1); + if (!Double.isNaN(passThreshold[index11])) { + tileIndices[activeColumns] = index11; + tileLocalX[activeColumns] = lx1; + tileLocalZ[activeColumns] = lz1; + tileTopY[activeColumns] = columnMaxY[index11]; + activeColumns++; + } + + if (activeColumns == 0) { + continue; + } + + int tileMaxY = minY; + for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { + if (tileTopY[columnIndex] > tileMaxY) { + tileMaxY = tileTopY[columnIndex]; + } + } + if (tileMaxY < minY) { + continue; + } + + for (int y = minY; y <= tileMaxY; y += latticeStep) { + double density = sampleDensityOptimized(scratch, x, y, z); + int stampMaxY = Math.min(maxY, y + 1); + for (int yy = y; yy <= stampMaxY; yy++) { + MatterCavern verticalMatter = matterByY[yy - minY]; + MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, PowerOfTwoCoordinates.floorDivPow2(yy, 4)); + int localY = yy & 15; + int fadeIndex = yy - minY; + for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { + if (yy > tileTopY[columnIndex]) { + continue; + } + + int index = tileIndices[columnIndex]; + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, index, yy, fluidHeight)) { + continue; + } + double localThreshold = passThreshold[index]; + if (surfaceBreakColumn[index] && yy >= surfaceBreakFloorY[index]) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[fadeIndex]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); + if (density > localThreshold) { + continue; + } + + int localX = tileLocalX[columnIndex]; + int localZ = tileLocalZ[columnIndex]; + int worldX = x0 + localX; + int worldZ = z0 + localZ; + MatterCavern matter = resolveMatter(scratch, verticalMatter, worldX, yy, worldZ, + index, fluidMaxY, localThreshold); + if (skipExistingCarved) { + if (cavernSlice.get(localX, localY, localZ) == null) { + writeCavern(cavernSlice, localX, yy, localZ, matter, fluidSupportPlan); + carved++; + } + continue; + } + + writeCavern(cavernSlice, localX, yy, localZ, matter, fluidSupportPlan); + carved++; + } + } + } + } + } + + return carved; + } + + private int carvePassFallback( + MantleChunk chunk, + int x0, + int z0, + int minY, + int maxY, + int sampleStep, + double surfaceBreakThresholdBoost, + int[] columnMaxY, + int[] fluidMaxY, + int[] surfaceFluidBoundaryStartY, + int[] surfaceBreakFloorY, + boolean[] surfaceBreakColumn, + double[] columnThreshold, + double[] clampedWeights, + double[] verticalEdgeFade, + MatterCavern[] matterByY, + CaveFluidSupportPlan fluidSupportPlan, + double minWeight, + double thresholdPenalty, + double thresholdBoost, + boolean skipExistingCarved + ) { + int carved = 0; + CaveCarveScratch scratch = scratchCache.get(); + + for (int lx = 0; lx < 16; lx++) { + int x = x0 + lx; + for (int lz = 0; lz < 16; lz++) { + int z = z0 + lz; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + double columnWeight = clampedWeights[index]; + if (columnWeight <= minWeight) { + continue; + } + + int columnTopY = columnMaxY[index]; + if (columnTopY < minY) { + continue; + } + + boolean breakColumn = surfaceBreakColumn[index]; + int breakFloorY = surfaceBreakFloorY[index]; + double threshold = columnThreshold[index] + thresholdBoost - ((1D - columnWeight) * thresholdPenalty); + + for (int y = minY; y <= columnTopY; y += sampleStep) { + double density = sampleDensityOptimized(scratch, x, y, z); + int carveMaxY = Math.min(columnTopY, y + sampleStep - 1); + for (int yy = y; yy <= carveMaxY; yy++) { + if (SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, index, yy, fluidHeight)) { + continue; + } + double localThreshold = threshold; + if (breakColumn && yy >= breakFloorY) { + localThreshold += surfaceBreakThresholdBoost; + } + localThreshold -= verticalEdgeFade[yy - minY]; + localThreshold = applySurfaceCeilingFade(scratch, localThreshold, index, yy, minY); + if (density > localThreshold) { + continue; + } + MatterCavern verticalMatter = matterByY[yy - minY]; + MatterCavern matter = resolveMatter(scratch, verticalMatter, x, yy, z, + index, fluidMaxY, localThreshold); + MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, PowerOfTwoCoordinates.floorDivPow2(yy, 4)); + int localY = yy & 15; + if (skipExistingCarved) { + if (cavernSlice.get(lx, localY, lz) == null) { + writeCavern(cavernSlice, lx, yy, lz, matter, fluidSupportPlan); + carved++; + } + continue; + } + + writeCavern(cavernSlice, lx, yy, lz, matter, fluidSupportPlan); + carved++; + } + } + } + } + + return carved; + } + + private boolean hasFallbackCandidates(int[] columnMaxY, double[] clampedWeights, int minY, double minWeight) { + for (int index = 0; index < 256; index++) { + if (clampedWeights[index] <= minWeight) { + continue; + } + + if (columnMaxY[index] >= minY) { + return true; + } + } + + return false; + } + + private double sampleDensityOptimized(int x, int y, int z) { + if (!hasWarp && !hasModules) { + return sampleDensityNoWarpNoModules(x, y, z); + } + + return sampleDensityOptimized(scratchCache.get(), x, y, z); + } + + private double sampleDensityOptimized(CaveCarveScratch scratch, int x, int y, int z) { + if (!hasWarp) { + if (!hasModules) { + return sampleDensityNoWarpNoModules(x, y, z); + } + + return sampleDensityNoWarpModules(scratch, x, y, z); + } + + if (!hasModules) { + return sampleDensityWarpOnly(scratch, x, y, z); + } + + return sampleDensityWarpModules(scratch, x, y, z); + } + + private void classifyDensityPlane(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + if (!hasWarp) { + if (!hasModules) { + classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + classifyDensityPlaneNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + if (!hasModules) { + classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + classifyDensityPlaneWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + } + + private void classifyDensityPlaneAdaptive( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + if (adaptiveSampleStep <= 1 || planeCount < ADAPTIVE_MIN_PLANE_COLUMNS) { + classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + if (!hasWarp) { + if (!hasModules) { + classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + classifyDensityPlaneAdaptiveNoWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + if (!hasModules) { + classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + classifyDensityPlaneAdaptiveWarpModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + } + + private void classifyDensityPlaneNoWarpNoModules(int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x, y, z, planeThresholdLimit[planeIndex]); + } + } + + private void classifyDensityPlaneNoWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneNoWarpNoModules(x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointNoWarpModules( + x, + y, + z, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyDensityPlaneWarpOnly(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x, y, z, planeThresholdLimit[planeIndex]); + } + } + + private void classifyDensityPlaneWarpModules(CaveCarveScratch scratch, int x0, int z0, int y, int[] planeColumnIndices, double[] planeThresholdLimit, int planeCount, boolean[] planeCarve) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int x = x0 + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int z = z0 + (columnIndex & 15); + planeCarve[planeIndex] = classifyDensityPointWarpModules( + scratch, + x, + y, + z, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyDensityPlaneAdaptiveNoWarpNoModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityNoWarpNoModules(x, y, z0 + sampleLocalZ); + } + } + + classifyAdaptivePlaneColumnsNoWarpNoModules( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples + ); + } + + private void classifyDensityPlaneAdaptiveNoWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneAdaptiveNoWarpNoModules(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityNoWarpNoModules(x, y, z0 + sampleLocalZ); + } + } + + classifyAdaptivePlaneColumnsNoWarpModules( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + + private void classifyDensityPlaneAdaptiveWarpOnly( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityWarpOnly(scratch, x, y, z0 + sampleLocalZ); + } + } + + classifyAdaptivePlaneColumnsWarpOnly( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples + ); + } + + private void classifyDensityPlaneAdaptiveWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin + ) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + classifyDensityPlaneAdaptiveWarpOnly(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve, adaptiveSampleStep, adaptiveThresholdMargin); + return; + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double[] remainingMin = scratch.activeModuleRemainingMin; + double[] remainingMax = scratch.activeModuleRemainingMax; + double[] adaptivePlaneDensity = scratch.adaptivePlaneDensity; + int axisCells = (16 + adaptiveSampleStep - 1) / adaptiveSampleStep; + int axisSamples = axisCells + 1; + int[] adaptivePlaneSampleBounds = scratch.adaptivePlaneSampleBounds; + prepareAdaptivePlaneSampleBounds(scratch, planeColumnIndices, planeCount, adaptiveSampleStep, adaptivePlaneSampleBounds, axisCells); + for (int sampleXIndex = adaptivePlaneSampleBounds[0]; sampleXIndex <= adaptivePlaneSampleBounds[1]; sampleXIndex++) { + int sampleLocalX = Math.min(sampleXIndex * adaptiveSampleStep, 16); + int x = x0 + sampleLocalX; + int rowOffset = sampleXIndex * axisSamples; + for (int sampleZIndex = adaptivePlaneSampleBounds[2]; sampleZIndex <= adaptivePlaneSampleBounds[3]; sampleZIndex++) { + int sampleLocalZ = Math.min(sampleZIndex * adaptiveSampleStep, 16); + adaptivePlaneDensity[rowOffset + sampleZIndex] = sampleDensityWarpModules( + scratch, + x, + y, + z0 + sampleLocalZ, + localModules, + activeModuleCount + ); + } + } + + classifyAdaptivePlaneColumnsWarpModulesSampled( + scratch, + x0, + z0, + y, + planeColumnIndices, + planeThresholdLimit, + planeCount, + planeCarve, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + + private void classifyAdaptivePlaneColumnsNoWarpNoModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + if (predictedDensity <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if (predictedDensity > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointNoWarpNoModules(x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); + } + } + + private void classifyAdaptivePlaneColumnsNoWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = classifyDensityPointNoWarpModulesFromExactDensity( + x0 + localX, + y, + z0 + localZ, + threshold, + predictedDensity, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + continue; + } + if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointNoWarpModules( + x0 + localX, + y, + z0 + localZ, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyAdaptivePlaneColumnsWarpOnly( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + if (predictedDensity <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if (predictedDensity > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointWarpOnly(scratch, x0 + localX, y, z0 + localZ, planeThresholdLimit[planeIndex]); + } + } + + private void classifyAdaptivePlaneColumnsWarpModules( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = classifyDensityPointWarpModulesFromExactDensity( + scratch, + x0 + localX, + y, + z0 + localZ, + threshold, + predictedDensity, + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + continue; + } + if ((predictedDensity + maxRemaining) <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if ((predictedDensity + minRemaining) > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointWarpModules( + scratch, + x0 + localX, + y, + z0 + localZ, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private void classifyAdaptivePlaneColumnsWarpModulesSampled( + CaveCarveScratch scratch, + int x0, + int z0, + int y, + int[] planeColumnIndices, + double[] planeThresholdLimit, + int planeCount, + boolean[] planeCarve, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + double[] adaptivePlanePrediction = scratch.adaptivePlanePrediction; + double[] adaptivePlaneAmbiguity = scratch.adaptivePlaneAmbiguity; + prepareAdaptivePlaneColumns( + scratch, + planeColumnIndices, + planeCount, + adaptiveSampleStep, + adaptiveThresholdMargin, + adaptivePlaneDensity, + axisCells, + axisSamples, + adaptivePlanePrediction, + adaptivePlaneAmbiguity + ); + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + double threshold = planeThresholdLimit[planeIndex] * inverseNormalization; + double predictedDensity = adaptivePlanePrediction[planeIndex]; + double ambiguityMargin = adaptivePlaneAmbiguity[planeIndex]; + if (isAdaptivePlaneSampleAligned(localX, localZ, adaptiveSampleStep)) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + if (predictedDensity <= threshold - ambiguityMargin) { + planeCarve[planeIndex] = true; + continue; + } + if (predictedDensity > threshold + ambiguityMargin) { + planeCarve[planeIndex] = false; + continue; + } + if (adaptiveSampleStep >= ADAPTIVE_DEEP_SAMPLE_STEP) { + planeCarve[planeIndex] = predictedDensity <= threshold; + continue; + } + + planeCarve[planeIndex] = classifyDensityPointWarpModules( + scratch, + x0 + localX, + y, + z0 + localZ, + planeThresholdLimit[planeIndex], + localModules, + activeModuleCount, + remainingMin, + remainingMax + ); + } + } + + private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { + double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + if ((density + detailMinContribution) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution) <= thresholdLimit) { + return true; + } + + density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + return density <= thresholdLimit; + } + + private boolean classifyDensityPointNoWarpModules( + int x, + int y, + int z, + double thresholdLimit, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); + } + + double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { + return true; + } + + density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + if ((density + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[0]) <= thresholdLimit) { + return true; + } + + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(x, y, z); + if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { + return true; + } + } + + return density <= thresholdLimit; + } + + private int snapWarp(int c) { + int g = warpResolution; + if (g <= 1) { + return c; + } + if ((g & (g - 1)) == 0) { + return c & -g; + } + return Math.floorDiv(c, g) * g; + } + + private boolean classifyDensityPointWarpOnly(CaveCarveScratch scratch, int x, int y, int z, double thresholdLimit) { + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + if ((density + detailMinContribution) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution) <= thresholdLimit) { + return true; + } + + density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + return density <= thresholdLimit; + } + + private boolean classifyDensityPointWarpModules( + CaveCarveScratch scratch, + int x, + int y, + int z, + double thresholdLimit, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return classifyDensityPointWarpOnly(scratch, x, y, z, thresholdLimit); + } + + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + detailMaxContribution + remainingMax[0]) <= thresholdLimit) { + return true; + } + + density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + if ((density + remainingMin[0]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[0]) <= thresholdLimit) { + return true; + } + + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ); + if ((density + remainingMin[moduleIndex + 1]) > thresholdLimit) { + return false; + } + if ((density + remainingMax[moduleIndex + 1]) <= thresholdLimit) { + return true; + } + } + + return density <= thresholdLimit; + } + + private boolean classifyDensityPointNoWarpModulesFromExactDensity( + int x, + int y, + int z, + double threshold, + double density, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return density <= threshold; + } + + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + if ((density + minRemaining) > threshold) { + return false; + } + if ((density + maxRemaining) <= threshold) { + return true; + } + + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(x, y, z) * inverseNormalization; + if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { + return false; + } + if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { + return true; + } + } + + return density <= threshold; + } + + private boolean classifyDensityPointWarpModulesFromExactDensity( + CaveCarveScratch scratch, + int x, + int y, + int z, + double threshold, + double density, + CaveFieldModuleState[] localModules, + int activeModuleCount, + double[] remainingMin, + double[] remainingMax + ) { + if (activeModuleCount == 0) { + return density <= threshold; + } + + double minRemaining = remainingMin[0] * inverseNormalization; + double maxRemaining = remainingMax[0] * inverseNormalization; + if ((density + minRemaining) > threshold) { + return false; + } + if ((density + maxRemaining) <= threshold) { + return true; + } + + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + density += localModules[moduleIndex].sample(warpedX, warpedY, warpedZ) * inverseNormalization; + if ((density + (remainingMin[moduleIndex + 1] * inverseNormalization)) > threshold) { + return false; + } + if ((density + (remainingMax[moduleIndex + 1] * inverseNormalization)) <= threshold) { + return true; + } + } + + return density <= threshold; + } + + private boolean isAdaptivePlaneSampleAligned(int localX, int localZ, int adaptiveSampleStep) { + if ((adaptiveSampleStep & (adaptiveSampleStep - 1)) == 0) { + int mask = adaptiveSampleStep - 1; + return (localX & mask) == 0 && (localZ & mask) == 0; + } + return localX % adaptiveSampleStep == 0 && localZ % adaptiveSampleStep == 0; + } + + private void prepareAdaptivePlaneSampleBounds( + CaveCarveScratch scratch, + int[] planeColumnIndices, + int planeCount, + int adaptiveSampleStep, + int[] adaptivePlaneSampleBounds, + int axisCells + ) { + prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisCells + 1); + int[] adaptiveCellX = scratch.adaptiveCellX; + int[] adaptiveCellZ = scratch.adaptiveCellZ; + int minSampleX = axisCells; + int maxSampleX = 0; + int minSampleZ = axisCells; + int maxSampleZ = 0; + + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int sampleX = adaptiveCellX[columnIndex]; + int sampleZ = adaptiveCellZ[columnIndex]; + if (sampleX < minSampleX) { + minSampleX = sampleX; + } + if (sampleX + 1 > maxSampleX) { + maxSampleX = sampleX + 1; + } + if (sampleZ < minSampleZ) { + minSampleZ = sampleZ; + } + if (sampleZ + 1 > maxSampleZ) { + maxSampleZ = sampleZ + 1; + } + } + + adaptivePlaneSampleBounds[0] = minSampleX; + adaptivePlaneSampleBounds[1] = maxSampleX; + adaptivePlaneSampleBounds[2] = minSampleZ; + adaptivePlaneSampleBounds[3] = maxSampleZ; + } + + private void prepareAdaptivePlaneColumns( + CaveCarveScratch scratch, + int[] planeColumnIndices, + int planeCount, + int adaptiveSampleStep, + double adaptiveThresholdMargin, + double[] adaptivePlaneDensity, + int axisCells, + int axisSamples, + double[] adaptivePlanePrediction, + double[] adaptivePlaneAmbiguity + ) { + prepareAdaptiveGeometry(scratch, adaptiveSampleStep, axisCells, axisSamples); + int[] adaptiveCellZ = scratch.adaptiveCellZ; + int[] adaptiveRow0 = scratch.adaptiveRow0; + int[] adaptiveRow1 = scratch.adaptiveRow1; + double[] adaptiveTx = scratch.adaptiveTx; + double[] adaptiveTz = scratch.adaptiveTz; + for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { + int columnIndex = planeColumnIndices[planeIndex]; + int cellZ = adaptiveCellZ[columnIndex]; + int row0 = adaptiveRow0[columnIndex]; + int row1 = adaptiveRow1[columnIndex]; + double tx = adaptiveTx[columnIndex]; + double tz = adaptiveTz[columnIndex]; + double d00 = adaptivePlaneDensity[row0 + cellZ]; + double d01 = adaptivePlaneDensity[row0 + cellZ + 1]; + double d10 = adaptivePlaneDensity[row1 + cellZ]; + double d11 = adaptivePlaneDensity[row1 + cellZ + 1]; + double dx0 = d00 + ((d10 - d00) * tx); + double dx1 = d01 + ((d11 - d01) * tx); + adaptivePlanePrediction[planeIndex] = dx0 + ((dx1 - dx0) * tz); + double minDensity = Math.min(Math.min(d00, d01), Math.min(d10, d11)); + double maxDensity = Math.max(Math.max(d00, d01), Math.max(d10, d11)); + adaptivePlaneAmbiguity[planeIndex] = adaptiveThresholdMargin + ((maxDensity - minDensity) * ADAPTIVE_LOCAL_RANGE_SCALE); + } + } + + private void prepareAdaptiveGeometry(CaveCarveScratch scratch, int adaptiveSampleStep, int axisCells, int axisSamples) { + if (scratch.adaptiveGeometryStep == adaptiveSampleStep && scratch.adaptiveGeometryAxisCells == axisCells) { + return; + } + + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + int localX = columnIndex >> 4; + int localZ = columnIndex & 15; + int cellX = Math.min(localX / adaptiveSampleStep, axisCells - 1); + int cellZ = Math.min(localZ / adaptiveSampleStep, axisCells - 1); + int x0 = cellX * adaptiveSampleStep; + int z0 = cellZ * adaptiveSampleStep; + int x1 = Math.min(x0 + adaptiveSampleStep, 16); + int z1 = Math.min(z0 + adaptiveSampleStep, 16); + scratch.adaptiveCellX[columnIndex] = cellX; + scratch.adaptiveCellZ[columnIndex] = cellZ; + scratch.adaptiveRow0[columnIndex] = cellX * axisSamples; + scratch.adaptiveRow1[columnIndex] = (cellX + 1) * axisSamples; + scratch.adaptiveTx[columnIndex] = x1 == x0 ? 0D : (localX - x0) / (double) (x1 - x0); + scratch.adaptiveTz[columnIndex] = z1 == z0 ? 0D : (localZ - z0) / (double) (z1 - z0); + } + + scratch.adaptiveGeometryStep = adaptiveSampleStep; + scratch.adaptiveGeometryAxisCells = axisCells; + } + + private double sampleDensityNoWarpNoModules(int x, int y, int z) { + double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + return density * inverseNormalization; + } + + private double sampleDensityNoWarpModules(CaveCarveScratch scratch, int x, int y, int z) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + return sampleDensityNoWarpNoModules(x, y, z); + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + CaveFieldModuleState module = localModules[moduleIndex]; + double moduleDensity = module.density.noiseFastSigned3D(x, y, z) - module.threshold; + if (module.invert) { + moduleDensity = -moduleDensity; + } + + density += moduleDensity * module.weight; + } + + return density * inverseNormalization; + } + + private double sampleDensityWarpOnly(CaveCarveScratch scratch, int x, int y, int z) { + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + return density * inverseNormalization; + } + + private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z) { + int activeModuleCount = prepareActiveModules(scratch, y); + if (activeModuleCount == 0) { + return sampleDensityWarpOnly(scratch, x, y, z); + } + + CaveFieldModuleState[] localModules = scratch.activeModules; + return sampleDensityWarpModules(scratch, x, y, z, localModules, activeModuleCount); + } + + private double sampleDensityWarpModules(CaveCarveScratch scratch, int x, int y, int z, CaveFieldModuleState[] localModules, int activeModuleCount) { + int sx = snapWarp(x); + int sy = snapWarp(y); + int sz = snapWarp(z); + int warpSlot = prepareWarpSample(scratch, sx, sy, sz); + double warpA = scratch.warpCacheA[warpSlot]; + double warpB = scratch.warpCacheB[warpSlot]; + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { + CaveFieldModuleState module = localModules[moduleIndex]; + double moduleDensity = module.density.noiseFastSigned3D(warpedX, warpedY, warpedZ) - module.threshold; + if (module.invert) { + moduleDensity = -moduleDensity; + } + + density += moduleDensity * module.weight; + } + + return density * inverseNormalization; + } + + private int prepareWarpSample(CaveCarveScratch scratch, int sx, int sy, int sz) { + int slot = mixWarpKey(sx, sy, sz) & (scratch.warpCacheX.length - 1); + if (scratch.warpCacheSet[slot] + && scratch.warpCacheX[slot] == sx + && scratch.warpCacheY[slot] == sy + && scratch.warpCacheZ[slot] == sz) { + return slot; + } + + scratch.warpCacheSet[slot] = true; + scratch.warpCacheX[slot] = sx; + scratch.warpCacheY[slot] = sy; + scratch.warpCacheZ[slot] = sz; + scratch.warpCacheA[slot] = warpDensity.noiseFastSigned3D(sx, sy, sz); + scratch.warpCacheB[slot] = warpDensity.noiseFastSigned3D(sx + 31.37D, sy - 17.21D, sz + 23.91D); + return slot; + } + + private static int mixWarpKey(int sx, int sy, int sz) { + int hash = sx * 73428767; + hash ^= sy * 91227153; + hash ^= sz * 43828939; + hash ^= hash >>> 16; + return hash; + } + + private int prepareActiveModules(CaveCarveScratch scratch, int y) { + CaveFieldModuleState[] configuredModules = modules; + int configuredCount = configuredModules.length; + if (configuredCount == 0) { + return 0; + } + + // Pure function of (y, modules). modules is final and the scratch is per carver per thread, + // so the band selection and the remaining-contribution prefix sums only change when y does. + if (scratch.activeModulesY == y) { + return scratch.activeModuleCount; + } + + if (scratch.activeModules.length < configuredCount) { + scratch.activeModules = new CaveFieldModuleState[configuredCount]; + } + + int activeCount = 0; + for (int moduleIndex = 0; moduleIndex < configuredCount; moduleIndex++) { + CaveFieldModuleState module = configuredModules[moduleIndex]; + if (y < module.minY || y > module.maxY) { + continue; + } + + scratch.activeModules[activeCount] = module; + activeCount++; + } + + if (scratch.activeModuleRemainingMin.length < activeCount + 1) { + scratch.activeModuleRemainingMin = new double[activeCount + 1]; + scratch.activeModuleRemainingMax = new double[activeCount + 1]; + } + + scratch.activeModuleRemainingMin[activeCount] = 0D; + scratch.activeModuleRemainingMax[activeCount] = 0D; + for (int moduleIndex = activeCount - 1; moduleIndex >= 0; moduleIndex--) { + CaveFieldModuleState module = scratch.activeModules[moduleIndex]; + scratch.activeModuleRemainingMin[moduleIndex] = scratch.activeModuleRemainingMin[moduleIndex + 1] + module.minContribution; + scratch.activeModuleRemainingMax[moduleIndex] = scratch.activeModuleRemainingMax[moduleIndex + 1] + module.maxContribution; + } + + scratch.activeModulesY = y; + scratch.activeModuleCount = activeCount; + return activeCount; + } + + private MatterSlice resolveCavernSlice(CaveCarveScratch scratch, MantleChunk chunk, int sectionIndex) { + @SuppressWarnings("unchecked") + MatterSlice cachedSlice = (MatterSlice) scratch.sectionSlices[sectionIndex]; + if (cachedSlice != null) { + return cachedSlice; + } + + Matter sectionMatter = scratch.sectionMatter[sectionIndex]; + if (sectionMatter == null) { + sectionMatter = chunk.getOrCreate(sectionIndex); + scratch.sectionMatter[sectionIndex] = sectionMatter; + } + + MatterSlice resolvedSlice = sectionMatter.slice(MatterCavern.class); + scratch.sectionSlices[sectionIndex] = resolvedSlice; + return resolvedSlice; + } + + private MatterCavern[] prepareMatterByYTable(CaveCarveScratch scratch, int minY, int maxY) { + int size = Math.max(0, maxY - minY + 1); + if (scratch.matterByY.length < size) { + scratch.matterByY = new MatterCavern[size]; + } + + MatterCavern[] matterByY = scratch.matterByY; + boolean allowLava = profile.isAllowLava(); + int lavaHeight = engine.getDimension().getCaveLavaHeight(); + + for (int y = minY; y <= maxY; y++) { + int offset = y - minY; + if (allowLava && y <= lavaHeight) { + matterByY[offset] = carveLava; + continue; + } + if (!allowLava && y <= lavaHeight) { + matterByY[offset] = carveForcedAir; + continue; + } + + matterByY[offset] = carveAir; + } + + return matterByY; + } + + private MatterCavern resolveMatter(CaveCarveScratch scratch, MatterCavern verticalMatter, int x, int y, int z, + int columnIndex, int[] fluidMaxY, double localThreshold) { + if (verticalMatter != carveLava + && y <= fluidMaxY[columnIndex] + && isAquiferCandidate(scratch, x, y, z, localThreshold)) { + return carveFluid; + } + return verticalMatter; + } + + private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { + double depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D)); + double cutoff = 0.35D + (depthFactor * 0.2D); + if (detailDensity.noiseFastSigned3D(x, y * 0.5D, z) <= cutoff) { + return false; + } + return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); + } + + private boolean isAquiferCandidate(int x, int y, int z, double localThreshold) { + return isAquiferCandidate(scratchCache.get(), x, y, z, localThreshold); + } + + private boolean hasAquiferCupSupport(CaveCarveScratch scratch, int x, int y, int z, double threshold) { + int floorY = Math.max(0, y - 1); + int deepFloorY = Math.max(0, y - 2); + int aboveY = Math.min(aquiferCeilingY, y + 1); + if (!isDensitySolid(scratch, x, floorY, z, threshold)) { + return false; + } + if (!isDensitySolid(scratch, x, deepFloorY, z, threshold - 0.05D)) { + return false; + } + + int support = 0; + if (isDensitySolid(scratch, x + 1, y, z, threshold)) { + support++; + } + if (isDensitySolid(scratch, x - 1, y, z, threshold)) { + support++; + } + if (isDensitySolid(scratch, x, y, z + 1, threshold)) { + support++; + } + if (isDensitySolid(scratch, x, y, z - 1, threshold)) { + support++; + } + if (isDensitySolid(scratch, x, aboveY, z, threshold)) { + support++; + } + return support >= 4; + } + + private boolean isDensitySolid(CaveCarveScratch scratch, int x, int y, int z, double threshold) { + return sampleDensityOptimized(scratch, x, y, z) > threshold; + } + + private void writeCavern(MatterSlice cavernSlice, int localX, int y, int localZ, + MatterCavern matter, CaveFluidSupportPlan fluidSupportPlan) { + cavernSlice.set(localX, y & 15, localZ, matter); + if (fluidSupportPlan != null && matter == carveFluid) { + fluidSupportPlan.add(localX, y, localZ, carveFluid, carveAir); + } + } + + private void prepareSectionCaches(CaveCarveScratch scratch, int minY, int maxY) { + int minSection = Math.max(0, PowerOfTwoCoordinates.floorDivPow2(minY, 4)); + int maxSection = Math.max(minSection, PowerOfTwoCoordinates.floorDivPow2(maxY, 4)); + int requiredSections = maxSection + 1; + if (scratch.sectionMatter.length < requiredSections) { + scratch.sectionMatter = new Matter[requiredSections]; + scratch.sectionSlices = new MatterSlice[requiredSections]; + return; + } + + for (int section = minSection; section <= maxSection; section++) { + scratch.sectionMatter[section] = null; + scratch.sectionSlices[section] = null; + } + } + + private double clampColumnWeight(double weight) { + if (Double.isNaN(weight) || Double.isInfinite(weight)) { + return 0D; + } + + if (weight <= 0D) { + return 0D; + } + + if (weight >= 1D) { + return 1D; + } + + return weight; + } + + private double signed(double value) { + return (value * 2D) - 1D; + } + + private double applySurfaceCeilingFade( + CaveCarveScratch scratch, + double threshold, + int columnIndex, + int y, + int minY + ) { + if (!scratch.surfaceCeilingColumn[columnIndex]) { + return threshold; + } + + int ceilingDistance = scratch.columnMaxY[columnIndex] - y; + if (ceilingDistance < 0 || ceilingDistance >= SURFACE_CEILING_FADE_DEPTH) { + return threshold; + } + + double closureThreshold = scratch.surfaceClosureThreshold[y - minY]; + if (threshold <= closureThreshold) { + return threshold; + } + + double progress = ceilingDistance / (double) SURFACE_CEILING_FADE_DEPTH; + double smooth = progress * progress * (3D - (2D * progress)); + return closureThreshold + ((threshold - closureThreshold) * smooth); + } + + private void prepareSurfaceClosureThresholdTable(CaveCarveScratch scratch, int minY, int maxY) { + int size = Math.max(0, maxY - minY + 1); + if (scratch.surfaceClosureThreshold.length < size) { + scratch.surfaceClosureThreshold = new double[size]; + } + + double baseMinimum = -Math.abs(baseWeight) - Math.abs(detailWeight); + for (int y = minY; y <= maxY; y++) { + double minimumDensity = baseMinimum; + for (CaveFieldModuleState module : modules) { + if (y < module.minY || y > module.maxY) { + continue; + } + minimumDensity += Math.min(module.minContribution, module.maxContribution); + } + scratch.surfaceClosureThreshold[y - minY] = + (minimumDensity * inverseNormalization) - SURFACE_CEILING_SOLID_EPSILON; + } + } + + private double[] prepareVerticalEdgeFadeTable(CaveCarveScratch scratch, int minY, int maxY) { + int size = Math.max(0, maxY - minY + 1); + if (scratch.verticalEdgeFade.length < size) { + scratch.verticalEdgeFade = new double[size]; + } + + double[] verticalEdgeFade = scratch.verticalEdgeFade; + int fadeRange = Math.max(0, profile.getVerticalEdgeFade()); + double fadeStrength = Math.max(0D, profile.getVerticalEdgeFadeStrength()); + if (size <= 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { + Arrays.fill(verticalEdgeFade, 0, size, 0D); + return verticalEdgeFade; + } + + for (int y = minY; y <= maxY; y++) { + int floorDistance = y - minY; + int ceilingDistance = maxY - y; + int edgeDistance = Math.min(floorDistance, ceilingDistance); + int offsetIndex = y - minY; + if (edgeDistance >= fadeRange) { + verticalEdgeFade[offsetIndex] = 0D; + continue; + } + + double t = Math.max(0D, Math.min(1D, edgeDistance / (double) fadeRange)); + double smooth = t * t * (3D - (2D * t)); + verticalEdgeFade[offsetIndex] = (1D - smooth) * fadeStrength; + } + + return verticalEdgeFade; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java new file mode 100644 index 000000000..40edd8af8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java @@ -0,0 +1,678 @@ +/* + * 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.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.Cache; +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.engine.framework.StructurePlacementMarker; +import art.arcane.iris.engine.framework.TreeBlockMaterial; +import art.arcane.iris.engine.mantle.ComponentFlag; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.mantle.IrisMantleComponent; +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.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; +import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.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.mantle.flag.ReservedFlag; +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.Map; +import java.util.Objects; + +@ComponentFlag(ReservedFlag.JIGSAW) +public class IrisStructureComponent extends IrisMantleComponent { + private static final MatterCavern CARVE_CAVERN = new MatterCavern(true, "", (byte) 3); + + public IrisStructureComponent(EngineMantle engineMantle) { + super(engineMantle, ReservedFlag.JIGSAW, 3); + } + + @Override + @ChunkCoordinates + public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + for (IrisStructurePlacement placement : StructurePlacementScope.placementsAt( + getEngineMantle().getEngine(), x, z)) { + if (!placement.hasIrisStructures()) { + continue; + } + placeFromPlacement(writer, placement, x, z); + } + } + + @ChunkCoordinates + private void placeFromPlacement(MantleWriter writer, IrisStructurePlacement placement, int cx, int cz) { + IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement( + getEngineMantle().getEngine(), placement, cx, cz); + if (resolved == null) { + return; + } + + boolean trace = IrisSettings.get().getGeneral().isDebug(); + if (trace) { + IrisLogging.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.getStructures() + + " anchor=" + placement.resolvedAnchor() + " band=" + placement.getMinHeight() + ".." + placement.getMaxHeight()); + } + + 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) { + IrisLogging.debug("[StructTrace] ASSEMBLED chunk=" + cx + "," + cz + " key=" + key + " baseY=" + baseY + " pieces=" + pieces.size()); + } + + if (!placement.isAnchoredUnderground()) { + clearIntersectingObjectTrees(writer, resolved); + } + + IrisStructureTerrain terrain = placement.resolvedTerrain(); + IrisStructureTerrainMode terrainMode = terrain.resolvedMode(); + if (terrainMode == IrisStructureTerrainMode.FORCE_CARVE) { + forceCarveStructure(writer, pieces, terrain); + } else if (terrainMode == IrisStructureTerrainMode.BORE) { + boreStructure(writer, pieces, terrain); + } else if (terrainMode != IrisStructureTerrainMode.PRESERVE + && terrainMode != IrisStructureTerrainMode.SOURCE) { + throw new IllegalStateException("Iris assembly terrain mode " + terrainMode + + " is not implemented for structure '" + key + "'"); + } + + ObjectPlaceMode mode = structure.getPlaceMode(); + int failedPieces = 0; + IrisStructureStiltSettings stilt = placement.getStilt(); + Long2IntOpenHashMap foundationColumns = stilt == null + ? null : new Long2IntOpenHashMap(); + boolean supportNonOccluding = stilt != null && stilt.isSupportNonOccluding(); + if (placement.isAnchoredUnderground()) { + ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG) + ? mode : ObjectPlaceMode.STRUCTURE_PIECE; + for (PlacedStructurePiece p : pieces) { + if (placeObject(writer, structure, p, undergroundMode, p.getY(), rng, + foundationColumns, supportNonOccluding) == -1) { + failedPieces++; + } + } + } else if (mode == ObjectPlaceMode.STRUCTURE_PIECE || mode == ObjectPlaceMode.FLOATING) { + 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, + IrisStructureStiltSettings settings, RNG rng, + boolean surfaceStructure) { + IrisMaterialPalette palette = Objects.requireNonNull( + settings.getPalette(), "Structure stilt palette must not be null"); + int mantleOffset = getEngineMantle().getEngine().getMinHeight(); + int maxDepth = Math.max(1, settings.getMaxDepth()); + 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 = getEngineMantle().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, palette, rng, getData(), worldX, y, worldZ, mantleOffset); + }); + } + } + + static void writeFoundationSupport(MantleWriter writer, IrisMaterialPalette palette, RNG rng, + IrisData data, int worldX, int mantleY, int worldZ, + int mantleOffset) { + int worldY = mantleY + mantleOffset; + PlatformBlockState support = palette.get(rng, worldX, worldY, worldZ, data); + 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, + IrisStructureTerrain terrain) { + int[] bounds = computePieceBounds(pieces); + if (bounds == null) { + return; + } + int pad = Math.max(0, terrain.getHorizontalPadding()); + int minX = bounds[0] - pad; + int minY = bounds[1] - Math.max(0, terrain.getFloorPadding()); + int minZ = bounds[2] - pad; + int maxX = bounds[3] + pad; + int maxY = bounds[4] + Math.max(0, terrain.getCeilingPadding()); + int maxZ = bounds[5] + pad; + int worldMin = getEngineMantle().getEngine().getMinHeight() + 1; + int worldMax = getEngineMantle().getEngine().getMinHeight() + getEngineMantle().getEngine().getHeight() - 1; + minY = Math.max(minY, worldMin); + maxY = Math.min(maxY, worldMax); + if (maxX < minX || maxY < minY || maxZ < minZ) { + return; + } + int mantleOffset = getEngineMantle().getEngine().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, + IrisStructureTerrain terrain) { + int[] bounds = computePieceBounds(pieces); + if (bounds == null) { + return; + } + IrisStructureCarveShape shape = terrain.resolvedShape(); + int margin = Math.max(0, terrain.getHorizontalPadding()); + int head = Math.max(0, terrain.getCeilingPadding()); + int floorCut = Math.max(0, terrain.getFloorPadding()); + double strength = terrain.resolvedErosionStrength(); + int mantleOffset = getEngineMantle().getEngine().getMinHeight(); + int worldMin = getEngineMantle().getEngine().getMinHeight() + 1; + int worldMax = getEngineMantle().getEngine().getMinHeight() + getEngineMantle().getEngine().getHeight() - 1; + int upExtension = shape.maximumCeilingExtension(head, strength); + + if (shape == IrisStructureCarveShape.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 == IrisStructureCarveShape.ERODED && strength > 0D; + CNG blob = null; + CNG roll = null; + if (eroded) { + RNG noiseRng = new RNG(seed() + Cache.key(bounds[0], bounds[2])); + blob = CNG.signature(noiseRng); + roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17)); + } + + if (IrisSettings.get().getGeneral().isDebug()) { + IrisLogging.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 = getEngineMantle().getEngine().getMinHeight(); + int worldHeight = getEngineMantle().getEngine().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 = 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 != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) { + config.setForcePlace(true); + } + int placeY = (y == -1) ? -1 : y - getEngineMantle().getEngine().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, 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); + } + + @Override + protected int computeRadius() { + IrisDimension dimension = getDimension(); + int maxBlocks = 0; + + for (IrisRegion region : dimension.getAllRegions(this::getData)) { + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(region.getStructures())); + } + for (IrisBiome biome : dimension.getReachableBiomes(this::getData)) { + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(biome.getStructures())); + } + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(dimension.getStructures())); + + return maxBlocks; + } + + private int maxBlocksFrom(KList placements) { + int max = 0; + for (IrisStructurePlacement placement : placements) { + if (!placement.hasIrisStructures()) { + continue; + } + IrisStructureTerrain terrain = placement.resolvedTerrain(); + int carvePadding = terrain.resolvedMode() == IrisStructureTerrainMode.FORCE_CARVE + || terrain.resolvedMode() == IrisStructureTerrainMode.BORE + ? Math.max(0, terrain.getHorizontalPadding()) : 0; + for (String key : placement.getStructures()) { + IrisStructure structure = getData().load(IrisStructure.class, key, false); + 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/mantle/components/IslandObjectPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java new file mode 100644 index 000000000..11cd38d58 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java @@ -0,0 +1,220 @@ +/* + * 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.mantle.MantleWriter; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.spi.PlatformBlockState; +import org.jetbrains.annotations.Nullable; + +public final class IslandObjectPlacer implements IObjectPlacer { + private static final int OVERHANG_RADIUS = 2; + private static final int OVERHANG_HEIGHT_TOLERANCE = 4; + + private final MantleWriter wrapped; + private final SampleProvider samples; + private final IrisFloatingChildBiomes entry; + private final int anchorY; + private final AnchorFace face; + + private IslandObjectPlacer(MantleWriter wrapped, AnchorSettings settings) { + this.wrapped = wrapped; + this.samples = settings.samples(); + this.entry = settings.entry(); + this.anchorY = settings.anchorY(); + this.face = settings.face(); + } + + public static IslandObjectPlacer top(MantleWriter wrapped, SampleProvider samples, + IrisFloatingChildBiomes entry, int anchorY) { + return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.TOP)); + } + + public static IslandObjectPlacer bottom(MantleWriter wrapped, SampleProvider samples, + IrisFloatingChildBiomes entry, int anchorY) { + return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.BOTTOM)); + } + + public boolean canWriteObjectBlock(int x, int y, int z) { + return !shouldSkipAirColumn(x, y, z); + } + + @Override + public int getHighest(int x, int z, IrisData data) { + FloatingIslandSample sample = samples.sample(x, z); + if (face == AnchorFace.TOP) { + return sample == null ? anchorY : sample.topY(); + } + if (sample == null) { + return anchorY; + } + int bottomY = sample.bottomY(); + return bottomY < 0 ? anchorY : bottomY; + } + + @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) { + FloatingIslandSample sample = samples.sample(x, z); + if (sample != null) { + int index = y - sample.islandBaseY; + if (index >= 0 && index < sample.solidMask.length) { + return sample.solidMask[index]; + } + return false; + } + return 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 (!shouldSkipAirColumn(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 (!shouldSkipAirColumn(x, y, z)) { + wrapped.setTile(x, y, z, tile); + } + } + + @Override + public void setData(int x, int y, int z, T data) { + if (!shouldSkipAirColumn(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(); + } + + static boolean matchesAnchor(FloatingIslandSample sample, IrisFloatingChildBiomes entry, AnchorFace face) { + if (sample == null) { + return false; + } + return face == AnchorFace.TOP ? sample.entry == entry : sample.bottomEntry() == entry; + } + + private boolean shouldSkipAirColumn(int x, int y, int z) { + Engine engine = getEngine(); + if (engine != null && (y < 0 || y >= engine.getHeight())) { + return true; + } + + FloatingIslandSample sample = samples.sample(x, z); + if (matchesAnchor(sample, entry, face) && isNearAnchorHeight(sample)) { + return face == AnchorFace.BOTTOM && y >= anchorY; + } + if (face == AnchorFace.TOP && y <= anchorY) { + return true; + } + if (face == AnchorFace.BOTTOM && y >= anchorY) { + return true; + } + return !hasNearbySupport(x, z); + } + + private boolean hasNearbySupport(int x, int z) { + for (int dz = -OVERHANG_RADIUS; dz <= OVERHANG_RADIUS; dz++) { + for (int dx = -OVERHANG_RADIUS; dx <= OVERHANG_RADIUS; dx++) { + FloatingIslandSample sample = samples.sample(x + dx, z + dz); + if (matchesAnchor(sample, entry, face) && isNearAnchorHeight(sample)) { + return true; + } + } + } + return false; + } + + private boolean isNearAnchorHeight(FloatingIslandSample sample) { + int faceY = face == AnchorFace.TOP ? sample.topY() : sample.bottomY(); + return faceY >= 0 && Math.abs(faceY - anchorY) <= OVERHANG_HEIGHT_TOLERANCE; + } + + public enum AnchorFace { + TOP, + BOTTOM + } + + @FunctionalInterface + public interface SampleProvider { + @Nullable FloatingIslandSample sample(int x, int z); + } + + private record AnchorSettings( + SampleProvider samples, + IrisFloatingChildBiomes entry, + int anchorY, + AnchorFace face + ) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java new file mode 100644 index 000000000..fa61ed86f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java @@ -0,0 +1,708 @@ +/* + * 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.engine.IrisComplex; +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.mantle.ComponentFlag; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.mantle.IrisMantleComponent; +import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.iris.util.project.stream.utility.ChunkFillableDoubleStream2D; +import art.arcane.iris.util.simd.SimdKernels; +import art.arcane.iris.util.simd.SimdSupport; +import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.volmlib.util.mantle.flag.ReservedFlag; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +@ComponentFlag(ReservedFlag.CARVED) +public class MantleCarvingComponent extends IrisMantleComponent { + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + private static final int BLEND_RADIUS = 3; + private static final int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2); + private static final double MIN_WEIGHT = 0.08D; + private static final double THRESHOLD_PENALTY = 0.24D; + private static final int MAX_BLENDED_PROFILE_PASSES = 2; + private static final int KERNEL_WIDTH = (BLEND_RADIUS * 2) + 1; + private static final int KERNEL_SIZE = KERNEL_WIDTH * KERNEL_WIDTH; + private static final int[] KERNEL_DX = new int[KERNEL_SIZE]; + private static final int[] KERNEL_DZ = new int[KERNEL_SIZE]; + private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; + private static final ThreadLocal BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); + + private final Object profileCarverLock = new Object(); + private volatile Map profileCarvers = new IdentityHashMap<>(); + + static { + int kernelIndex = 0; + for (int offsetX = -BLEND_RADIUS; offsetX <= BLEND_RADIUS; offsetX++) { + for (int offsetZ = -BLEND_RADIUS; offsetZ <= BLEND_RADIUS; offsetZ++) { + KERNEL_DX[kernelIndex] = offsetX; + KERNEL_DZ[kernelIndex] = offsetZ; + int edgeDistance = Math.max(Math.abs(offsetX), Math.abs(offsetZ)); + KERNEL_WEIGHT[kernelIndex] = (BLEND_RADIUS + 1D) - edgeDistance; + kernelIndex++; + } + } + } + + public MantleCarvingComponent(EngineMantle engineMantle) { + super(engineMantle, ReservedFlag.CARVED, 0); + } + + @Override + public void hotload() { + super.hotload(); + // Hotload swaps in fresh IrisCaveProfile instances (identity keys), so retained + // entries would strand a full carver set pinning the closed IrisData per reload. + // Carvers rebuild deterministically from the carve seed, so output is unchanged. + synchronized (profileCarverLock) { + profileCarvers = new IdentityHashMap<>(); + } + } + + @Override + public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + IrisComplex complex = context.getComplex(); + IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); + BlendScratch blendScratch = BLEND_SCRATCH.get(); + int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); + PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); + List weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); + getEngineMantle().getEngine().getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); + int fluidHeight = getDimension().getFluidHeight(); + int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY; + SurfaceFluidBoundaryPlan.fill( + chunkSurfaceHeights, + blendScratch.fieldSurfaceHeights, + blendScratch.fieldHasFluid, + FIELD_SIZE, + BLEND_RADIUS, + fluidHeight, + surfaceFluidBoundaryStartY + ); + CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); + for (WeightedProfile weightedProfile : weightedProfiles) { + carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); + } + + UpperDimensionContext upperCtx = getEngineMantle().getEngine().getUpperContext(); + if (upperCtx != null && getDimension().isUpperDimensionCarving()) { + carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, chunkSurfaceHeights, fluidSupportPlan); + } + fluidSupportPlan.resolve(writer.acquireChunk(x, z)); + + if (!weightedProfiles.isEmpty()) { + CarveOrphanSweep.sweepChunk( + writer.acquireChunk(x, z), + chunkSurfaceHeights, + maxSurfaceBreakDepth(weightedProfiles), + writer.getMantle().getWorldHeight() - 1, + surfaceFluidBoundaryStartY, + fluidHeight + ); + } + } + + private static int maxSurfaceBreakDepth(List weightedProfiles) { + int maxDepth = 0; + for (WeightedProfile weightedProfile : weightedProfiles) { + maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.getSurfaceBreakDepth())); + } + return maxDepth; + } + + @ChunkCoordinates + private void carveProfile(WeightedProfile weightedProfile, MantleWriter writer, int cx, int cz, + int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY, + CaveFluidSupportPlan fluidSupportPlan) { + IrisCaveCarver3D carver = getCarver(weightedProfile.profile); + carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan); + } + + private void carveUpperTerrain(UpperDimensionContext upperCtx, List normalProfiles, + MantleWriter writer, int cx, int cz, int[] lowerSurfaceHeights, + CaveFluidSupportPlan fluidSupportPlan) { + int chunkHeight = getEngineMantle().getEngine().getHeight(); + int worldMinHeight = getEngineMantle().getEngine().getWorld().minHeight(); + int gap = getDimension().getUpperDimensionGap(); + int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); + + int minUpperSurfaceY = chunkHeight; + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int worldX = baseX + localX; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int worldZ = baseZ + localZ; + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); + int upperY = Math.max(rawUpper, lowerSurfaceHeights[columnIndex] + gap); + if (upperY < minUpperSurfaceY) { + minUpperSurfaceY = upperY; + } + } + } + + if (minUpperSurfaceY >= chunkHeight - 2) { + return; + } + + IrisRange upperYRange = new IrisRange( + minUpperSurfaceY + worldMinHeight, + chunkHeight - 1 + worldMinHeight + ); + IrisRange fullVerticalRange = new IrisRange(0, chunkHeight); + + int[] ceilingSurfaceHeights = new int[CHUNK_AREA]; + Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1); + + for (WeightedProfile weightedProfile : normalProfiles) { + IrisRange constrainedRange; + if (weightedProfile.worldYRange != null) { + double min = Math.max(weightedProfile.worldYRange.getMin(), upperYRange.getMin()); + double max = Math.min(weightedProfile.worldYRange.getMax(), upperYRange.getMax()); + if (min >= max) { + continue; + } + constrainedRange = new IrisRange(min, max); + } else { + constrainedRange = upperYRange; + } + IrisCaveCarver3D carver = getCarver(weightedProfile.profile); + carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan); + } + } + + private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState) { + BlendScratch blendScratch = BLEND_SCRATCH.get(); + IrisCaveProfile[] profileField = blendScratch.profileField; + Map columnProfileWeights = blendScratch.columnProfileWeights; + IdentityHashMap activeProfiles = blendScratch.activeProfiles; + List profileOrder = blendScratch.profileOrder; + IrisCaveProfile[] kernelProfiles = blendScratch.kernelProfiles; + double[] kernelProfileWeights = blendScratch.kernelProfileWeights; + activeProfiles.clear(); + profileOrder.clear(); + fillProfileField(profileField, chunkX, chunkZ, complex, resolverState, blendScratch); + + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int profileCount = 0; + int centerX = localX + BLEND_RADIUS; + int centerZ = localZ + BLEND_RADIUS; + double totalKernelWeight = 0D; + + for (int kernelIndex = 0; kernelIndex < KERNEL_SIZE; kernelIndex++) { + int sampleX = centerX + KERNEL_DX[kernelIndex]; + int sampleZ = centerZ + KERNEL_DZ[kernelIndex]; + IrisCaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ]; + if (!isProfileEnabled(profile)) { + continue; + } + + double kernelWeight = KERNEL_WEIGHT[kernelIndex]; + int existingIndex = findProfileIndex(kernelProfiles, profileCount, profile); + if (existingIndex >= 0) { + kernelProfileWeights[existingIndex] += kernelWeight; + } else { + kernelProfiles[profileCount] = profile; + kernelProfileWeights[profileCount] = kernelWeight; + profileCount++; + } + totalKernelWeight += kernelWeight; + } + + if (totalKernelWeight <= 0D || profileCount == 0) { + continue; + } + + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + for (int profileIndex = 0; profileIndex < profileCount; profileIndex++) { + IrisCaveProfile profile = kernelProfiles[profileIndex]; + double kernelWeight = kernelProfileWeights[profileIndex]; + kernelProfiles[profileIndex] = null; + kernelProfileWeights[profileIndex] = 0D; + + double columnWeight = clampWeight(kernelWeight / totalKernelWeight); + if (columnWeight < MIN_WEIGHT) { + continue; + } + + double[] weights = columnProfileWeights.get(profile); + if (weights == null) { + weights = new double[CHUNK_AREA]; + columnProfileWeights.put(profile, weights); + } else if (!activeProfiles.containsKey(profile)) { + Arrays.fill(weights, 0D); + } + if (activeProfiles.put(profile, Boolean.TRUE) == null) { + profileOrder.add(profile); + } + weights[columnIndex] = columnWeight; + } + } + } + + List columnWeightedProfiles = new ArrayList<>(); + for (IrisCaveProfile profile : profileOrder) { + double[] weights = columnProfileWeights.get(profile); + if (weights == null) { + continue; + } + + // averageWeight ranks and orders carve passes, so it must be bit-identical across + // installations: kernels.sum reassociates FP addition under the vector kernel, + // making profile order depend on a JVM flag. max() is order-independent and safe. + double maxWeight = SimdSupport.kernels().max(weights, weights.length); + + if (maxWeight < MIN_WEIGHT) { + continue; + } + + double averageWeight = computeAverageWeight(weights); + columnWeightedProfiles.add(new WeightedProfile(profile, weights, averageWeight, null, columnWeightedProfiles.size())); + } + + List blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA); + List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, resolverState, blendScratch); + resolvedProfiles.addAll(blendedProfiles); + return resolvedProfiles; + } + + private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { + List weightedProfiles = new ArrayList<>(); + List entries = getDimension().getCarving(); + if (entries == null || entries.isEmpty()) { + return weightedProfiles; + } + + Map dimensionColumnPlans = blendScratch.dimensionColumnPlans; + dimensionColumnPlans.clear(); + + for (IrisDimensionCarvingEntry entry : entries) { + if (entry == null || !entry.isEnabled()) { + continue; + } + + IrisBiome rootBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), entry, resolverState); + if (rootBiome == null) { + continue; + } + + IrisDimensionCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new IrisDimensionCarvingEntry[CHUNK_AREA]); + buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState); + + Map rootProfileColumnWeights = new IdentityHashMap<>(); + List rootProfileOrder = new ArrayList<>(); + IrisRange worldYRange = entry.getWorldYRange(); + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + IrisDimensionCarvingEntry resolvedEntry = columnPlan[columnIndex]; + IrisBiome resolvedBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), resolvedEntry, resolverState); + if (resolvedBiome == null) { + continue; + } + + IrisCaveProfile profile = resolvedBiome.getCaveProfile(); + if (!isProfileEnabled(profile)) { + continue; + } + + double[] columnWeights = rootProfileColumnWeights.get(profile); + if (columnWeights == null) { + columnWeights = new double[CHUNK_AREA]; + rootProfileColumnWeights.put(profile, columnWeights); + rootProfileOrder.add(profile); + } + columnWeights[columnIndex] = 1D; + } + + for (IrisCaveProfile profile : rootProfileOrder) { + weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size())); + } + } + + return weightedProfiles; + } + + private void buildDimensionColumnPlan(IrisDimensionCarvingEntry[] columnPlan, int chunkX, int chunkZ, IrisDimensionCarvingEntry entry, IrisDimensionCarvingResolver.State resolverState) { + int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int worldX = baseX + localX; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int worldZ = baseZ + localZ; + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + columnPlan[columnIndex] = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), entry, worldX, worldZ, resolverState); + } + } + } + + private void fillProfileField(IrisCaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { + int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; + int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; + prefillProfileFieldSamples(startX, startZ, complex, blendScratch); + + for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { + int worldX = startX + fieldX; + for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { + int worldZ = startZ + fieldZ; + int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; + profileField[fieldIndex] = resolveColumnProfile( + worldX, + worldZ, + blendScratch.fieldSurfaceHeights[fieldIndex], + blendScratch.fieldRegions[fieldIndex], + blendScratch.fieldSurfaceBiomes[fieldIndex], + blendScratch.fieldCaveBiomes[fieldIndex], + resolverState + ); + } + } + } + + private int findProfileIndex(IrisCaveProfile[] profiles, int size, IrisCaveProfile profile) { + for (int index = 0; index < size; index++) { + if (profiles[index] == profile) { + return index; + } + } + + return -1; + } + + private IrisCaveProfile resolveColumnProfile( + int worldX, + int worldZ, + double surfaceHeight, + IrisRegion region, + IrisBiome surfaceBiome, + IrisBiome caveBiome, + IrisDimensionCarvingResolver.State resolverState + ) { + IrisCaveProfile resolved = null; + IrisCaveProfile dimensionProfile = getDimension().getCaveProfile(); + if (isProfileEnabled(dimensionProfile)) { + resolved = dimensionProfile; + } + + if (region != null) { + IrisCaveProfile regionProfile = region.getCaveProfile(); + if (isProfileEnabled(regionProfile)) { + resolved = regionProfile; + } + } + + if (surfaceBiome != null) { + IrisCaveProfile surfaceProfile = surfaceBiome.getCaveProfile(); + if (isProfileEnabled(surfaceProfile)) { + resolved = surfaceProfile; + } + } + + int roundedSurfaceY = (int) Math.round(surfaceHeight); + int sampleY = Math.max(1, roundedSurfaceY - 56); + int worldY = sampleY + getEngineMantle().getEngine().getWorld().minHeight(); + IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(getEngineMantle().getEngine(), worldY, resolverState); + IrisBiome resolvedCarvingBiome = null; + if (rootCarvingEntry != null) { + IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), rootCarvingEntry, worldX, worldZ, resolverState); + resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), resolvedCarvingEntry, resolverState); + if (resolvedCarvingBiome != null) { + caveBiome = resolvedCarvingBiome; + } + } + if (caveBiome != null) { + IrisBiome effectiveCaveBiome = caveBiome; + if (resolvedCarvingBiome == null && surfaceBiome != null) { + if (surfaceBiome != null) { + int truncatedSurfaceY = (int) surfaceHeight; + int depthBelowSurface = truncatedSurfaceY - sampleY; + if (depthBelowSurface <= 0) { + effectiveCaveBiome = surfaceBiome; + } else { + int minDepth = Math.max(0, caveBiome.getCaveMinDepthBelowSurface()); + if (depthBelowSurface < minDepth) { + effectiveCaveBiome = surfaceBiome; + } + } + } + } + + IrisCaveProfile caveProfile = effectiveCaveBiome.getCaveProfile(); + if (isProfileEnabled(caveProfile)) { + resolved = caveProfile; + } + } + + return resolved; + } + + private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { + fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights); + fillFieldFluidPresence(complex.getFluidStream(), startX, startZ, blendScratch.fieldHasFluid); + fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions); + fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes); + fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes); + } + + private void fillFieldObjects(ProceduralStream stream, int startX, int startZ, T[] target) { + for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { + int worldX = startX + fieldX; + for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { + target[(fieldX * FIELD_SIZE) + fieldZ] = stream.get(worldX, startZ + fieldZ); + } + } + } + + private void fillFieldHeights(ProceduralStream stream, int startX, int startZ, double[] target) { + for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { + int worldX = startX + fieldX; + for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { + target[(fieldX * FIELD_SIZE) + fieldZ] = stream.getDouble(worldX, startZ + fieldZ); + } + } + } + + private void fillFieldFluidPresence(ProceduralStream stream, int startX, int startZ, boolean[] target) { + for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { + int worldX = startX + fieldX; + for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { + target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(stream.get(worldX, startZ + fieldZ)); + } + } + } + + private IrisCaveCarver3D getCarver(IrisCaveProfile profile) { + IrisCaveCarver3D carver = profileCarvers.get(profile); + if (carver != null) { + return carver; + } + + IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(getEngineMantle().getEngine(), profile); + synchronized (profileCarverLock) { + IrisCaveCarver3D published = profileCarvers.get(profile); + if (published != null) { + return published; + } + + Map updated = new IdentityHashMap<>(profileCarvers); + updated.put(profile, createdCarver); + profileCarvers = updated; + return createdCarver; + } + } + + private boolean isProfileEnabled(IrisCaveProfile profile) { + return profile != null && profile.isEnabled(); + } + + protected int computeRadius() { + return 1; + } + + private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) { + int[] surfaceHeights = scratch; + int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + boolean useContextHeight = context != null + && context.getHeight() != null + && context.getX() == baseX + && context.getZ() == baseZ; + double[] cachedChunkHeights = null; + if (!useContextHeight && context != null) { + ProceduralStream heightStream = context.getComplex().getHeightStream(); + if (heightStream instanceof ChunkFillableDoubleStream2D cachedHeightStream) { + cachedChunkHeights = BLEND_SCRATCH.get().chunkSurfaceHeightSamples; + cachedHeightStream.fillChunkDoubles(baseX, baseZ, cachedChunkHeights); + } + } + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int worldX = baseX + localX; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int worldZ = baseZ + localZ; + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + if (useContextHeight) { + surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ); + continue; + } + if (cachedChunkHeights != null) { + surfaceHeights[columnIndex] = (int) Math.round(cachedChunkHeights[(localZ << 4) + localX]); + continue; + } + surfaceHeights[columnIndex] = getEngineMantle().getEngine().getHeight(worldX, worldZ); + } + } + return surfaceHeights; + } + + private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles) { + return limitAndMergeBlendedProfiles(blendedProfiles, maxProfiles, CHUNK_AREA); + } + + private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles, int areaSize) { + if (blendedProfiles == null || blendedProfiles.isEmpty()) { + return new ArrayList<>(); + } + + int clampedLimit = Math.max(1, maxProfiles); + List rankedProfiles = new ArrayList<>(blendedProfiles); + rankedProfiles.sort(MantleCarvingComponent::compareBySelectionRank); + List keptProfiles = new ArrayList<>(); + int keptCount = Math.min(clampedLimit, rankedProfiles.size()); + for (int index = 0; index < keptCount; index++) { + keptProfiles.add(rankedProfiles.get(index)); + } + + if (rankedProfiles.size() > keptCount) { + for (int columnIndex = 0; columnIndex < areaSize; columnIndex++) { + int dominantIndex = 0; + double dominantWeight = Double.NEGATIVE_INFINITY; + for (int keptIndex = 0; keptIndex < keptProfiles.size(); keptIndex++) { + double keptWeight = keptProfiles.get(keptIndex).columnWeights[columnIndex]; + if (keptWeight > dominantWeight) { + dominantWeight = keptWeight; + dominantIndex = keptIndex; + } + } + + double droppedWeight = 0D; + for (int droppedIndex = keptCount; droppedIndex < rankedProfiles.size(); droppedIndex++) { + droppedWeight += rankedProfiles.get(droppedIndex).columnWeights[columnIndex]; + } + if (droppedWeight <= 0D) { + continue; + } + + WeightedProfile dominantProfile = keptProfiles.get(dominantIndex); + double mergedWeight = dominantProfile.columnWeights[columnIndex] + droppedWeight; + dominantProfile.columnWeights[columnIndex] = clampWeight(mergedWeight); + } + } + + List mergedProfiles = new ArrayList<>(); + for (WeightedProfile keptProfile : keptProfiles) { + double averageWeight = computeAverageWeight(keptProfile.columnWeights, areaSize); + mergedProfiles.add(new WeightedProfile(keptProfile.profile, keptProfile.columnWeights, averageWeight, keptProfile.worldYRange, keptProfile.sequence)); + } + mergedProfiles.sort(MantleCarvingComponent::compareByCarveOrder); + return mergedProfiles; + } + + private static int compareBySelectionRank(WeightedProfile a, WeightedProfile b) { + int weightOrder = Double.compare(b.averageWeight, a.averageWeight); + if (weightOrder != 0) { + return weightOrder; + } + return Integer.compare(a.sequence, b.sequence); + } + + private static int compareByCarveOrder(WeightedProfile a, WeightedProfile b) { + int weightOrder = Double.compare(a.averageWeight, b.averageWeight); + if (weightOrder != 0) { + return weightOrder; + } + return Integer.compare(a.sequence, b.sequence); + } + + private static double computeAverageWeight(double[] weights) { + return computeAverageWeight(weights, CHUNK_AREA); + } + + private static double computeAverageWeight(double[] weights, int areaSize) { + if (weights == null || weights.length == 0) { + return 0D; + } + double sum = 0D; + for (double weight : weights) { + sum += weight; + } + return sum / Math.max(1, areaSize); + } + + private static double clampWeight(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + return 0D; + } + if (value <= 0D) { + return 0D; + } + if (value >= 1D) { + return 1D; + } + return value; + } + + private static final class WeightedProfile { + private final IrisCaveProfile profile; + private final double[] columnWeights; + private final double averageWeight; + private final IrisRange worldYRange; + private final int sequence; + + private WeightedProfile(IrisCaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { + this.profile = profile; + this.columnWeights = columnWeights; + this.averageWeight = averageWeight; + this.worldYRange = worldYRange; + this.sequence = sequence; + } + + private double averageWeight() { + return averageWeight; + } + } + + private static final class BlendScratch { + private final IrisCaveProfile[] profileField = new IrisCaveProfile[FIELD_SIZE * FIELD_SIZE]; + private final IrisCaveProfile[] kernelProfiles = new IrisCaveProfile[KERNEL_SIZE]; + private final double[] kernelProfileWeights = new double[KERNEL_SIZE]; + private final IdentityHashMap columnProfileWeights = new IdentityHashMap<>(); + private final IdentityHashMap dimensionColumnPlans = new IdentityHashMap<>(); + private final IdentityHashMap activeProfiles = new IdentityHashMap<>(); + private final List profileOrder = new ArrayList<>(); + private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; + private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; + private final IrisRegion[] fieldRegions = new IrisRegion[FIELD_SIZE * FIELD_SIZE]; + private final IrisBiome[] fieldSurfaceBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE]; + private final IrisBiome[] fieldCaveBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE]; + private final int[] chunkSurfaceHeights = new int[CHUNK_AREA]; + private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA]; + private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA]; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java new file mode 100644 index 000000000..8a1bfc446 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java @@ -0,0 +1,614 @@ +/* + * 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.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.iris.engine.mantle.ComponentFlag; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.mantle.IrisMantleComponent; +import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.volmlib.util.mantle.flag.ReservedFlag; +import art.arcane.volmlib.util.math.RNG; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.Set; + +@ComponentFlag(ReservedFlag.FLOATING_OBJECT) +public class MantleFloatingObjectComponent extends IrisMantleComponent { + private static final int INVERTED_PICK_ATTEMPTS = 8; + private static final IrisObjectRotation ROTATION_NONE = IrisObjectRotation.of(0, 0, 0); + + public MantleFloatingObjectComponent(EngineMantle engineMantle) { + super(engineMantle, ReservedFlag.FLOATING_OBJECT, 2); + } + + @Override + public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + IrisComplex complex = context.getComplex(); + IrisData data = getData(); + int minX = x << 4; + int minZ = z << 4; + RNG chunkRng = new RNG(Cache.key(x, z) + seed() + 0x0FA710BEL); + FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(getEngineMantle(), context.getFloatingIslandBoundarySampler()); + + FloatingIslandSample.clearChunkMemo(); + + FloatingIslandSample[] samples = new FloatingIslandSample[256]; + for (int xf = 0; xf < 16; xf++) { + for (int zf = 0; zf < 16; zf++) { + int wx = minX + xf; + int wz = minZ + zf; + FloatingIslandSample sample = sampleResolver.sample(wx, wz); + if (sample != null) { + samples[(zf << 4) | xf] = sample; + } + } + } + + // The IdentityHashMaps are lookup indices only. Iteration MUST follow the encounter + // order of the deterministic 0..255 column scan: identity-hash order changes per JVM + // run, and the shared chunkRng makes placement output depend on iteration order. + IdentityHashMap> entryColumns = new IdentityHashMap<>(); + IdentityHashMap> bottomEntryColumns = new IdentityHashMap<>(); + KList entryOrder = new KList<>(); + KList bottomEntryOrder = new KList<>(); + for (int i = 0; i < 256; i++) { + FloatingIslandSample s = samples[i]; + if (s == null || s.entry == null) { + continue; + } + entryColumns.computeIfAbsent(s.entry, e -> { + entryOrder.add(e); + return new KList<>(); + }).add(i); + IrisFloatingChildBiomes bottomEntry = s.bottomEntry(); + if (bottomEntry != null) { + bottomEntryColumns.computeIfAbsent(bottomEntry, e -> { + bottomEntryOrder.add(e); + return new KList<>(); + }).add(i); + } + } + + for (IrisFloatingChildBiomes entry : entryOrder) { + KList columns = entryColumns.get(entry); + if (columns.isEmpty()) { + continue; + } + + int firstKey = columns.get(0); + IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4)); + IrisBiome target = entry.getRealBiome(parent, data); + + KList floating = entry.getFloatingObjects(); + if (floating != null && !floating.isEmpty()) { + for (IrisObjectPlacement placement : floating) { + tryPlaceFloatingChunk(writer, complex, chunkRng, data, placement, columns, minX, minZ, entry); + } + } + + KList surface = target != null ? entry.resolveTopObjects(target) : null; + KList extras = entry.getExtraObjects(); + boolean hasSurface = surface != null && !surface.isEmpty(); + boolean hasExtras = extras != null && !extras.isEmpty(); + KList interior = null; + if (hasSurface || hasExtras) { + interior = interiorColumns(sampleResolver, columns, minX, minZ, entry, IslandObjectPlacer.AnchorFace.TOP); + if (hasSurface) { + for (IrisObjectPlacement placement : surface) { + tryPlaceAnchoredChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry); + } + } + if (hasExtras) { + for (IrisObjectPlacement placement : extras) { + tryPlaceAnchoredChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry); + } + } + } + } + + for (IrisFloatingChildBiomes entry : bottomEntryOrder) { + KList columns = bottomEntryColumns.get(entry); + if (columns.isEmpty()) { + continue; + } + + int firstKey = columns.get(0); + IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4)); + IrisBiome target = entry.getRealBiome(parent, data); + KList bottom = target != null ? entry.resolveBottomObjects(target) : null; + if (bottom != null && !bottom.isEmpty()) { + KList interior = interiorColumns(sampleResolver, columns, minX, minZ, entry, IslandObjectPlacer.AnchorFace.BOTTOM); + for (IrisObjectPlacement placement : bottom) { + tryPlaceInvertedChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry); + } + } + } + } + + @ChunkCoordinates + private void tryPlaceFloatingChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, KList columns, int minX, int minZ, IrisFloatingChildBiomes entry) { + if (placement == null || columns == null || columns.isEmpty()) { + return; + } + int density = placement.getDensity(rng, minX, minZ, data); + double perAttempt = placement.getChance(); + for (int i = 0; i < density; i++) { + if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { + continue; + } + IrisObject raw = placement.getObject(complex, rng); + if (raw == null) { + continue; + } + IrisObject obj0 = placement.getScale().get(rng, raw); + if (obj0 == null) { + continue; + } + if (entry != null && entry.hasObjectShrink()) { + obj0 = entry.getShrinkScale().get(rng, obj0); + if (obj0 == null) { + continue; + } + } + final IrisObject obj = obj0; + + int key = columns.get(rng.i(columns.size())); + int xx = minX + (key & 15); + int zz = minZ + (key >> 4); + IrisObjectPlacement floatingPlacement = placement.toPlacement(obj.getLoadKey()); + int id = rng.i(0, Integer.MAX_VALUE); + + try { + obj.place(xx, -1, zz, writer, floatingPlacement, rng, (b, bd) -> { + String marker = placementMarker(obj, id); + if (marker != null && shouldWritePlacementMarker(writer, bd, b.getX(), b.getY(), b.getZ())) { + writer.setData(b.getX(), b.getY(), b.getZ(), marker); + } + }, null, data); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + + @ChunkCoordinates + private void tryPlaceAnchoredChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, IrisFloatingChildBiomes entry) { + if (placement == null || columns.isEmpty()) { + return; + } + int density = placement.getDensity(rng, minX, minZ, data); + double perAttempt = placement.getChance(); + + for (int i = 0; i < density; i++) { + if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { + continue; + } + + IrisObject raw = placement.getObject(complex, rng); + if (raw == null) { + continue; + } + IrisObject obj0 = placement.getScale().get(rng, raw); + if (obj0 == null) { + continue; + } + if (entry != null && entry.hasObjectShrink()) { + obj0 = entry.getShrinkScale().get(rng, obj0); + if (obj0 == null) { + continue; + } + } + final IrisObject obj = obj0; + + FloatingObjectFootprint fp = FloatingObjectFootprint.compute(obj); + + KList pool = interior.isEmpty() ? columns : interior; + + int pickedKey = pool.get(rng.i(pool.size())); + int pickedXf = pickedKey & 15; + int pickedZf = pickedKey >> 4; + FloatingIslandSample pickedSample = samples[(pickedZf << 4) | pickedXf]; + if (pickedSample == null) { + continue; + } + int pickTopY = pickedSample.topY(); + + int pickedX = minX + pickedXf; + int pickedZ = minZ + pickedZf; + if (!isFootprintFlat(fp, pickedX, pickedZ, pickTopY, sampleProvider, entry, 2)) { + if (!isFootprintFlat(fp, pickedX, pickedZ, pickTopY, sampleProvider, entry, 4)) { + continue; + } + } + + int wx = minX + pickedXf - fp.getTallestKx(); + int wz = minZ + pickedZf - fp.getTallestKz(); + + IrisObjectPlacement anchored = placement.toPlacement(obj.getLoadKey()); + anchored.setMode(translateStiltModeForFloating(anchored.getMode())); + anchored.setTranslate(new IrisObjectTranslate()); + anchored.setRotation(ROTATION_NONE); + anchored.setForcePlace(true); + anchored.setBottom(false); + + int yv = pickTopY + 1 - fp.getLowestSolidKeyY(); + + IslandObjectPlacer islandPlacer = IslandObjectPlacer.top(writer, sampleProvider, entry, pickTopY); + FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(islandPlacer); + int id = rng.i(0, Integer.MAX_VALUE); + + try { + int resultY = obj.place(wx, yv, wz, transaction, anchored, rng, (b, bd) -> { + String marker = placementMarker(obj, id); + if (marker != null && shouldWritePlacementMarker(transaction, bd, b.getX(), b.getY(), b.getZ())) { + transaction.setData(b.getX(), b.getY(), b.getZ(), marker); + } + }, null, data); + if (resultY < 0) { + transaction.discard(); + } else { + transaction.commit(); + } + } catch (Throwable e) { + transaction.discard(); + IrisLogging.reportError(e); + } + } + } + + @ChunkCoordinates + private void tryPlaceInvertedChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, IrisFloatingChildBiomes entry) { + if (placement == null || columns.isEmpty()) { + return; + } + int density = placement.getDensity(rng, minX, minZ, data); + double perAttempt = placement.getChance(); + + for (int i = 0; i < density; i++) { + if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { + continue; + } + + IrisObject raw = placement.getObject(complex, rng); + if (raw == null) { + continue; + } + IrisObject obj0 = placement.getScale().get(rng, raw); + if (obj0 == null) { + continue; + } + if (entry != null && entry.hasObjectShrink()) { + obj0 = entry.getShrinkScale().get(rng, obj0); + if (obj0 == null) { + continue; + } + } + final IrisObject obj = obj0; + + FloatingObjectFootprint fp = FloatingObjectFootprint.compute(obj); + int invertedYRotation = rng.i(4) * 90; + IrisObjectRotation invertedRotation = IrisObjectRotation.xFlip180WithY(invertedYRotation); + + KList pool = interior.isEmpty() ? columns : interior; + + int pickedXf = -1; + int pickedZf = -1; + int pickBottomY = -1; + boolean foundBottomAnchor = false; + for (int attempt = 0; attempt < INVERTED_PICK_ATTEMPTS; attempt++) { + int pickedKey = pool.get(rng.i(pool.size())); + int candidateXf = pickedKey & 15; + int candidateZf = pickedKey >> 4; + FloatingIslandSample candidateSample = samples[(candidateZf << 4) | candidateXf]; + if (candidateSample == null) { + continue; + } + int candidateBottomY = candidateSample.bottomY(); + if (candidateBottomY < 0) { + continue; + } + int candidateX = minX + candidateXf; + int candidateZ = minZ + candidateZf; + if (!isFootprintFlatBottom(fp, invertedRotation, candidateX, candidateZ, candidateBottomY, sampleProvider, entry, 2) + && !isFootprintFlatBottom(fp, invertedRotation, candidateX, candidateZ, candidateBottomY, sampleProvider, entry, 4)) { + continue; + } + pickedXf = candidateXf; + pickedZf = candidateZf; + pickBottomY = candidateBottomY; + foundBottomAnchor = true; + break; + } + if (!foundBottomAnchor) { + continue; + } + + int wx = invertedBaseX(minX, pickedXf, fp, invertedRotation); + int wz = invertedBaseZ(minZ, pickedZf, fp, invertedRotation); + + IrisObjectPlacement inverted = placement.toPlacement(obj.getLoadKey()); + inverted.setMode(translateStiltModeForFloating(inverted.getMode())); + inverted.setTranslate(new IrisObjectTranslate()); + inverted.setRotation(invertedRotation); + inverted.setForcePlace(true); + inverted.setBottom(false); + + int yv = invertedBaseY(pickBottomY, fp, invertedRotation); + + IslandObjectPlacer islandPlacer = IslandObjectPlacer.bottom(writer, sampleProvider, entry, pickBottomY); + FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(islandPlacer); + int id = rng.i(0, Integer.MAX_VALUE); + + try { + int resultY = obj.place(wx, yv, wz, transaction, inverted, rng, (b, bd) -> { + String marker = placementMarker(obj, id); + if (marker != null && shouldWritePlacementMarker(transaction, bd, b.getX(), b.getY(), b.getZ())) { + transaction.setData(b.getX(), b.getY(), b.getZ(), marker); + } + }, null, data); + if (resultY < 0) { + transaction.discard(); + } else { + transaction.commit(); + } + } catch (Throwable e) { + transaction.discard(); + IrisLogging.reportError(e); + } + } + } + + static boolean isFootprintFlatBottom(FloatingObjectFootprint fp, IrisObjectRotation rotation, + int pickedX, int pickedZ, int pickBottomY, + IslandObjectPlacer.SampleProvider samples, + IrisFloatingChildBiomes entry, int tolerance) { + IrisBlockVector anchor = invertedFootprintAnchor(fp, rotation); + long[] cells = fp.footprintXZ(); + if (cells.length == 0) { + return false; + } + for (int i = 0, n = cells.length; i < n; i++) { + long encoded = cells[i]; + int kx = (int) (encoded >> 32); + int kz = (int) (encoded & 0xFFFFFFFFL); + IrisBlockVector cell = rotation.rotate(new IrisBlockVector(kx, 0, kz), 0, 0, 0); + int columnX = pickedX + cell.getBlockX() - anchor.getBlockX(); + int columnZ = pickedZ + cell.getBlockZ() - anchor.getBlockZ(); + FloatingIslandSample sample = samples.sample(columnX, columnZ); + if (!IslandObjectPlacer.matchesAnchor(sample, entry, IslandObjectPlacer.AnchorFace.BOTTOM)) { + return false; + } + int bottomY = sample.bottomY(); + if (bottomY < 0 || Math.abs(bottomY - pickBottomY) > tolerance) { + return false; + } + } + return true; + } + + static int invertedBaseX(int minX, int pickedXf, FloatingObjectFootprint fp) { + return invertedBaseX(minX, pickedXf, fp, IrisObjectRotation.xFlip180()); + } + + static int invertedBaseY(int pickBottomY, FloatingObjectFootprint fp) { + return invertedBaseY(pickBottomY, fp, IrisObjectRotation.xFlip180()); + } + + static int invertedBaseZ(int minZ, int pickedZf, FloatingObjectFootprint fp) { + return invertedBaseZ(minZ, pickedZf, fp, IrisObjectRotation.xFlip180()); + } + + static int invertedBaseX(int minX, int pickedXf, FloatingObjectFootprint fp, IrisObjectRotation rotation) { + return minX + pickedXf - invertedFootprintAnchor(fp, rotation).getBlockX(); + } + + static int invertedBaseY(int pickBottomY, FloatingObjectFootprint fp, IrisObjectRotation rotation) { + return pickBottomY - 1 - invertedSolidAnchor(fp, rotation).getBlockY(); + } + + static int invertedBaseZ(int minZ, int pickedZf, FloatingObjectFootprint fp, IrisObjectRotation rotation) { + return minZ + pickedZf - invertedFootprintAnchor(fp, rotation).getBlockZ(); + } + + private static IrisBlockVector invertedFootprintAnchor(FloatingObjectFootprint fp, IrisObjectRotation rotation) { + return rotation.rotate(new IrisBlockVector(fp.getTallestKx(), 0, fp.getTallestKz()), 0, 0, 0); + } + + private static IrisBlockVector invertedSolidAnchor(FloatingObjectFootprint fp, IrisObjectRotation rotation) { + return rotation.rotate(new IrisBlockVector(fp.getTallestKx(), fp.getLowestSolidKeyY(), fp.getTallestKz()), 0, 0, 0); + } + + private static boolean shouldWritePlacementMarker(IObjectPlacer placer, PlatformBlockState state, int x, int y, int z) { + if (state == null) { + return false; + } + PlatformBlockState existingState = placer.get(x, y, z); + boolean wouldReplace = B.isSolid(existingState) && B.isVineBlock(state); + String material = IrisProceduralBlocks.materialKey(state); + boolean placesBlock = !material.equals("minecraft:air") && !material.equals("minecraft:cave_air") && !wouldReplace; + return state.isCustom() || placesBlock; + } + + static boolean isFootprintFlat(FloatingObjectFootprint fp, int pickedX, int pickedZ, int pickTopY, + IslandObjectPlacer.SampleProvider samples, + IrisFloatingChildBiomes entry, int tolerance) { + int tallestKx = fp.getTallestKx(); + int tallestKz = fp.getTallestKz(); + long[] cells = fp.footprintXZ(); + if (cells.length == 0) { + return false; + } + for (int i = 0, n = cells.length; i < n; i++) { + long encoded = cells[i]; + int kx = (int) (encoded >> 32); + int kz = (int) (encoded & 0xFFFFFFFFL); + int columnX = pickedX + (kx - tallestKx); + int columnZ = pickedZ + (kz - tallestKz); + FloatingIslandSample sample = samples.sample(columnX, columnZ); + if (!IslandObjectPlacer.matchesAnchor(sample, entry, IslandObjectPlacer.AnchorFace.TOP) + || Math.abs(sample.topY() - pickTopY) > tolerance) { + return false; + } + } + return true; + } + + private static KList interiorColumns(IslandObjectPlacer.SampleProvider samples, + KList columns, int minX, int minZ, + IrisFloatingChildBiomes entry, + IslandObjectPlacer.AnchorFace face) { + KList interior = new KList<>(); + for (int key : columns) { + int x = minX + (key & 15); + int z = minZ + (key >> 4); + if (!IslandObjectPlacer.matchesAnchor(samples.sample(x + 1, z), entry, face)) { + continue; + } + if (!IslandObjectPlacer.matchesAnchor(samples.sample(x - 1, z), entry, face)) { + continue; + } + if (!IslandObjectPlacer.matchesAnchor(samples.sample(x, z + 1), entry, face)) { + continue; + } + if (!IslandObjectPlacer.matchesAnchor(samples.sample(x, z - 1), entry, face)) { + continue; + } + interior.add(key); + } + return interior; + } + + private static String placementMarker(IrisObject object, int id) { + if (object == null) { + return null; + } + String key = object.getLoadKey(); + if (key == null || key.isEmpty() || key.equals("null")) { + return null; + } + return key + "@" + id; + } + + private static ObjectPlaceMode translateStiltModeForFloating(ObjectPlaceMode m) { + return switch (m) { + case STILT -> ObjectPlaceMode.MAX_HEIGHT; + case FAST_STILT -> ObjectPlaceMode.FAST_MAX_HEIGHT; + case MIN_STILT -> ObjectPlaceMode.MIN_HEIGHT; + case FAST_MIN_STILT -> ObjectPlaceMode.FAST_MIN_HEIGHT; + case CENTER_STILT -> ObjectPlaceMode.CENTER_HEIGHT; + case ERODE_STILT -> ObjectPlaceMode.MAX_HEIGHT; + case STRUCTURE_PIECE -> ObjectPlaceMode.CENTER_HEIGHT; + default -> m; + }; + } + + @Override + protected int computeRadius() { + int maxObjectExtent = 16; + Map sizeCache = new HashMap<>(); + Set warnedLargeObjects = new HashSet<>(); + try { + IrisData data = getData(); + for (IrisBiome biome : getDimension().getReachableBiomes(this::getData)) { + KList entries = biome.getFloatingChildBiomes(); + if (entries == null || entries.isEmpty()) { + continue; + } + for (IrisFloatingChildBiomes entry : entries) { + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getFloatingObjects(), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getExtraObjects(), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getTopObjectOverrides(), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getBottomObjectOverrides(), data, sizeCache, warnedLargeObjects)); + try { + IrisBiome target = entry.getRealBiome(biome, data); + if (target != null) { + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveTopObjects(target), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveBottomObjects(target), data, sizeCache, warnedLargeObjects)); + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + return maxObjectExtent; + } + + private int computePlacementRadius(KList placements, IrisData data, + Map sizeCache, + Set warnedLargeObjects) { + int radius = 0; + if (placements == null) { + return radius; + } + for (IrisObjectPlacement placement : placements) { + if (placement == null || placement.getPlace() == null) { + continue; + } + for (String objectKey : placement.getPlace()) { + try { + IrisBlockVector size = sizeCache.get(objectKey); + if (size == null) { + File file = data.getObjectLoader().findFile(objectKey); + if (file == null) { + continue; + } + size = IrisObject.sampleSize(file); + sizeCache.put(objectKey, size); + } + int reach = MantleObjectComponent.calculatePlacementReach(size, placement); + if (reach > 128 && warnedLargeObjects.add(objectKey)) { + IrisLogging.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + radius = Math.max(radius, reach); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + return radius; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java new file mode 100644 index 000000000..94ccb244e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java @@ -0,0 +1,1650 @@ +/* + * 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.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisObjectVacuum; +import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.mantle.ComponentFlag; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.mantle.IrisMantleComponent; +import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.TreeBlockMaterial; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.engine.object.placement.DecayControlPlacer; +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveAnchorMode; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +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.collection.KSet; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.volmlib.util.mantle.flag.ReservedFlag; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterStructurePOI; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.util.project.noise.NoiseType; +import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.IrisBlockVector; + +import java.io.IOException; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +@ComponentFlag(ReservedFlag.OBJECT) +public class MantleObjectComponent extends IrisMantleComponent { + private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L; + private static final int BEDROCK_CLEARANCE = 6; + private static final byte LIQUID_FORCED_AIR = 3; + private static final Map CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>(); + private static final Set MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet(); + + public MantleObjectComponent(EngineMantle engineMantle) { + super(engineMantle, ReservedFlag.OBJECT, 1); + } + + private static String placementMarker(IrisObject object, int id, String context) { + String key = object == null ? null : object.getLoadKey(); + if (key == null || key.isEmpty() || key.equals("null")) { + String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); + if (MISSING_LOAD_KEY_WARNED.add(fingerprint)) { + java.io.File file = object == null ? null : object.getLoadFile(); + IrisLogging.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context + + ", file=" + (file == null ? "" : file.getPath()) + "). " + + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); + } + return null; + } + return key + "@" + id; + } + + private static boolean isTreePlacement(IrisObject object, IrisObjectPlacement placement) { + String key = object == null ? null : object.getLoadKey(); + return (key != null && key.startsWith("trees/")) + || (placement != null && placement.getTrees() != null && placement.getTrees().isNotEmpty()); + } + + private static void writeTreeMaterial(IObjectPlacer placer, int x, int y, int z, PlatformBlockState data) { + placer.setData(x, y, z, TreeBlockMaterial.of(data)); + } + + @Override + public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + IrisComplex complex = context.getComplex(); + boolean traceRegen = isRegenTraceThread(); + RNG rng = applyNoise(x, z, Cache.key(x, z) + seed()); + int xxx = 8 + (x << 4); + int zzz = 8 + (z << 4); + IrisRegion region = complex.getRegionStream().get(xxx, zzz); + IrisBiome surfaceBiome = complex.getTrueBiomeStream().get(xxx, zzz); + int surfaceY = getEngineMantle().getEngine().getHeight(xxx, zzz, true); + IrisBiome caveBiome = resolveCaveObjectBiome(xxx, zzz, surfaceY, surfaceBiome); + if (IrisSettings.get().getGeneral().isDebug() && (x & 31) == 0 && (z & 31) == 0) { + int carvedBlocks = 0; + int minY = 1; + int maxY = Math.min(getEngineMantle().getEngine().getHeight() - 1, surfaceY - 14); + for (int sy = minY; sy < maxY; sy++) { + if (writer.isCarved(8 + (x << 4), sy, 8 + (z << 4))) { + carvedBlocks++; + } + } + IrisLogging.debug("Cave object diag: chunk=" + x + "," + z + + " surfaceBiome=" + surfaceBiome.getLoadKey() + + " caveBiome=" + caveBiome.getLoadKey() + + " surfaceY=" + surfaceY + + " maxAnchorY=" + maxY + + " carvedAtCenter=" + carvedBlocks + + " biomeCarvingObjects=" + caveBiome.getCarvingObjects().size() + + " regionCarvingObjects=" + region.getCarvingObjects().size() + + " sameBiome=" + (caveBiome == surfaceBiome || java.util.Objects.equals(caveBiome.getLoadKey(), surfaceBiome.getLoadKey()))); + } + if (traceRegen) { + IrisLogging.debug("Regen object layer start: chunk=" + x + "," + z + + " surfaceBiome=" + surfaceBiome.getLoadKey() + + " caveBiome=" + caveBiome.getLoadKey() + + " region=" + region.getLoadKey() + + " biomeSurfacePlacers=" + surfaceBiome.getSurfaceObjects().size() + + " biomeCavePlacers=" + caveBiome.getCarvingObjects().size() + + " regionSurfacePlacers=" + region.getSurfaceObjects().size() + + " regionCavePlacers=" + region.getCarvingObjects().size()); + } + ObjectPlacementSummary summary = placeObjects(writer, rng, x, z, surfaceBiome, caveBiome, region, complex, traceRegen); + placeProceduralObjects(writer, rng, x, z, surfaceBiome, caveBiome, region); + UpperDimensionContext upperCtx = getEngineMantle().getEngine().getUpperContext(); + IrisDimension dimension = getDimension(); + if (upperCtx != null && dimension.isUpperDimensionObjects()) { + placeUpperObjects(writer, rng, x, z, xxx, zzz, surfaceY, upperCtx, dimension, complex, traceRegen); + } + if (traceRegen) { + IrisLogging.debug("Regen object layer done: chunk=" + x + "," + z + + " biomeSurfacePlacersChecked=" + summary.biomeSurfacePlacersChecked() + + " biomeSurfacePlacersTriggered=" + summary.biomeSurfacePlacersTriggered() + + " biomeCavePlacersChecked=" + summary.biomeCavePlacersChecked() + + " biomeCavePlacersTriggered=" + summary.biomeCavePlacersTriggered() + + " regionSurfacePlacersChecked=" + summary.regionSurfacePlacersChecked() + + " regionSurfacePlacersTriggered=" + summary.regionSurfacePlacersTriggered() + + " regionCavePlacersChecked=" + summary.regionCavePlacersChecked() + + " regionCavePlacersTriggered=" + summary.regionCavePlacersTriggered() + + " objectAttempts=" + summary.objectAttempts() + + " objectPlaced=" + summary.objectPlaced() + + " objectRejected=" + summary.objectRejected() + + " objectNull=" + summary.objectNull() + + " objectErrors=" + summary.objectErrors()); + } + } + + private RNG applyNoise(int x, int z, long seed) { + CNG noise = CNG.signatureFast(new RNG(seed), NoiseType.WHITE, NoiseType.GLOB); + return new RNG((long) (seed * noise.noise(x, z))); + } + + private IrisBiome resolveCaveObjectBiome(int x, int z, int surfaceY, IrisBiome surfaceBiome) { + int legacySampleY = Math.max(1, surfaceY - 48); + IrisBiome legacyCaveBiome = getEngineMantle().getEngine().getCaveBiome(x, legacySampleY, z); + if (legacyCaveBiome == null) { + legacyCaveBiome = surfaceBiome; + } + + int[] sampleDepths = new int[]{48, 80, 112}; + IrisBiome ladderChoice = null; + for (int sampleDepth : sampleDepths) { + int sampleY = Math.max(1, surfaceY - sampleDepth); + IrisBiome sampled = getEngineMantle().getEngine().getCaveBiome(x, sampleY, z); + boolean sameSurface = sampled == surfaceBiome; + if (!sameSurface && sampled != null && surfaceBiome != null) { + String sampledKey = sampled.getLoadKey(); + String surfaceKey = surfaceBiome.getLoadKey(); + sameSurface = sampledKey != null && sampledKey.equals(surfaceKey); + } + + if (sampled == null || sameSurface) { + continue; + } + + if (!sampled.getCarvingObjects().isEmpty()) { + ladderChoice = sampled; + } + } + + if (ladderChoice != null) { + return ladderChoice; + } + + return legacyCaveBiome; + } + + @ChunkCoordinates + private ObjectPlacementSummary placeObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region, IrisComplex complex, boolean traceRegen) { + int biomeSurfaceChecked = 0; + int biomeSurfaceTriggered = 0; + int biomeCaveChecked = 0; + int biomeCaveTriggered = 0; + int regionSurfaceChecked = 0; + int regionSurfaceTriggered = 0; + int regionCaveChecked = 0; + int regionCaveTriggered = 0; + int attempts = 0; + int placed = 0; + int rejected = 0; + int nullObjects = 0; + int errors = 0; + IrisCaveProfile biomeCaveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); + IrisCaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome.getCaveProfile()); + CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); + + for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) { + biomeSurfaceChecked++; + boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); + if (traceRegen) { + IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + + " scope=biome-surface" + + " chanceResult=" + chance + + " chanceBase=" + i.getChance() + + " densityMid=" + i.getDensity() + + " objects=" + i.getPlace().size()); + } + if (chance) { + biomeSurfaceTriggered++; + try { + ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "biome-surface"); + attempts += result.attempts(); + placed += result.placed(); + rejected += result.rejected(); + nullObjects += result.nullObjects(); + errors += result.errors(); + } catch (Throwable e) { + errors++; + IrisLogging.reportError(e); + IrisLogging.error("Failed to place objects in the following biome: " + surfaceBiome.getName()); + IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); + IrisLogging.error("Are these objects missing?"); + } + } + } + + for (IrisObjectPlacement i : caveBiome.getCarvingObjects()) { + if (!i.getCarvingSupport().supportsCarving()) { + continue; + } + biomeCaveChecked++; + boolean chance = rng.chance(i.getChance()); + if (traceRegen) { + IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + + " scope=biome-cave" + + " chanceResult=" + chance + + " chanceBase=" + i.getChance() + + " densityMid=" + i.getDensity() + + " objects=" + i.getPlace().size()); + } + if (chance) { + biomeCaveTriggered++; + try { + ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, biomeCaveProfile, complex, traceRegen, x, z, "biome-cave", caveBiome.getLoadKey(), caveAnchorCache); + attempts += result.attempts(); + placed += result.placed(); + rejected += result.rejected(); + nullObjects += result.nullObjects(); + errors += result.errors(); + } catch (Throwable e) { + errors++; + IrisLogging.reportError(e); + IrisLogging.error("Failed to place cave objects in the following biome: " + caveBiome.getName()); + IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); + IrisLogging.error("Are these objects missing?"); + } + } + } + + for (IrisObjectPlacement i : region.getSurfaceObjects()) { + regionSurfaceChecked++; + boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); + if (traceRegen) { + IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + + " scope=region-surface" + + " chanceResult=" + chance + + " chanceBase=" + i.getChance() + + " densityMid=" + i.getDensity() + + " objects=" + i.getPlace().size()); + } + if (chance) { + regionSurfaceTriggered++; + try { + ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "region-surface"); + attempts += result.attempts(); + placed += result.placed(); + rejected += result.rejected(); + nullObjects += result.nullObjects(); + errors += result.errors(); + } catch (Throwable e) { + errors++; + IrisLogging.reportError(e); + IrisLogging.error("Failed to place objects in the following region: " + region.getName()); + IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); + IrisLogging.error("Are these objects missing?"); + } + } + } + + for (IrisObjectPlacement i : region.getCarvingObjects()) { + if (!i.getCarvingSupport().supportsCarving()) { + continue; + } + regionCaveChecked++; + boolean chance = rng.chance(i.getChance()); + if (traceRegen) { + IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + + " scope=region-cave" + + " chanceResult=" + chance + + " chanceBase=" + i.getChance() + + " densityMid=" + i.getDensity() + + " objects=" + i.getPlace().size()); + } + if (chance) { + regionCaveTriggered++; + try { + ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, regionCaveProfile, complex, traceRegen, x, z, "region-cave", null, caveAnchorCache); + attempts += result.attempts(); + placed += result.placed(); + rejected += result.rejected(); + nullObjects += result.nullObjects(); + errors += result.errors(); + } catch (Throwable e) { + errors++; + IrisLogging.reportError(e); + IrisLogging.error("Failed to place cave objects in the following region: " + region.getName()); + IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); + IrisLogging.error("Are these objects missing?"); + } + } + } + + return new ObjectPlacementSummary( + biomeSurfaceChecked, + biomeSurfaceTriggered, + biomeCaveChecked, + biomeCaveTriggered, + regionSurfaceChecked, + regionSurfaceTriggered, + regionCaveChecked, + regionCaveTriggered, + attempts, + placed, + rejected, + nullObjects, + errors + ); + } + + @ChunkCoordinates + private void placeProceduralObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region) { + IrisCaveProfile surfaceCaveProfile = resolveCaveProfile(surfaceBiome.getCaveProfile(), region.getCaveProfile()); + IrisCaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome == null ? null : caveBiome.getCaveProfile()); + placeProceduralFrom(writer, rng, x, z, surfaceBiome.getProceduralObjects(), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); + placeProceduralFrom(writer, rng, x, z, region.getProceduralObjects(), region.getName(), regionCaveProfile, null); + if (caveBiome != null && caveBiome != surfaceBiome) { + IrisCaveProfile caveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); + placeProceduralFrom(writer, rng, x, z, caveBiome.getProceduralObjects(), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); + } + } + + @ChunkCoordinates + private void placeProceduralFrom( + MantleWriter writer, + RNG rng, + int x, + int z, + IrisProceduralObjects proceduralObjects, + String scope, + IrisCaveProfile caveProfile, + String expectedCaveBiomeKey + ) { + if (proceduralObjects == null || proceduralObjects.isEmpty()) { + return; + } + + int blockX = x << 4; + int blockZ = z << 4; + boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(x, z); + CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); + for (IrisProceduralPlacement p : proceduralObjects.getAllPlacements()) { + boolean treePlacement = p instanceof IrisProceduralTree; + boolean chancePassed = passesProceduralChance(rng, p.getChance()); + if (golden) { + IrisLogging.debug("Goldendebug procedural chance: chunk=" + x + "," + z + + " scope=" + scope + + " placement=" + p.getName() + + " passed=" + chancePassed); + } + if (!chancePassed) { + continue; + } + + IrisObjectPlacement placement = p.asPlacement(); + boolean carving = placement.getCarvingSupport() == CarvingMode.CARVING_ONLY; + IrisCaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); + if (placement.getMode() == ObjectPlaceMode.CEILING_HANG) { + anchorMode = IrisCaveAnchorMode.CEILING; + } + int anchorScanStep = resolveAnchorScanStep(caveProfile); + int minDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); + int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); + IObjectPlacer basePlacer = p.isPlausible() ? new DecayControlPlacer(writer) : writer; + IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName()) : basePlacer; + int density = Math.max(1, p.getDensity()); + for (int i = 0; i < density; i++) { + IrisObject variant = p.getVariantObject(getData(), rng); + if (variant == null) { + if (golden) { + IrisLogging.debug("Goldendebug procedural pick: chunk=" + x + "," + z + + " placement=" + p.getName() + + " densityIndex=" + i + + " variant=null"); + } + continue; + } + CavePlacementAnchor caveAnchor = null; + if (carving) { + caveAnchor = findCavePlacementAnchor( + writer, + rng, + blockX, + blockZ, + anchorMode, + anchorScanStep, + minDepthBelowSurface, + anchorSearchAttempts, + expectedCaveBiomeKey, + placement.isUnderwater(), + caveAnchorCache + ); + } + if (carving && caveAnchor == null) { + if (golden) { + IrisLogging.debug("Goldendebug procedural cave anchor rejected: chunk=" + x + "," + z + + " placement=" + p.getName() + + " minDepthBelowSurface=" + minDepthBelowSurface); + } + continue; + } + int xx = caveAnchor == null ? rng.i(blockX, blockX + 16) : caveAnchor.x(); + int zz = caveAnchor == null ? rng.i(blockZ, blockZ + 16) : caveAnchor.z(); + int id = rng.i(0, Integer.MAX_VALUE); + if (golden) { + KList pool = p.getVariantObjects(getData()); + IrisLogging.debug("Goldendebug procedural pick: chunk=" + x + "," + z + + " placement=" + p.getName() + + " densityIndex=" + i + + " variant=" + variant.getLoadKey() + + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() + + " xx=" + xx + + " zz=" + zz + + " mode=" + placement.getMode() + + " carving=" + carving); + } + try { + int placeResult = -1; + CaveObjectPlacementTransaction.CommitResult commitResult = CaveObjectPlacementTransaction.CommitResult.EMPTY; + if (carving) { + int caveFloorY = caveAnchor.y(); + if (golden) { + IrisLogging.debug("Goldendebug procedural caveFloor: chunk=" + x + "," + z + + " placement=" + p.getName() + + " xx=" + xx + + " zz=" + zz + + " caveFloorY=" + caveFloorY); + } + IrisObjectPlacement effectivePlacement = resolveCavePlacement(placement, variant, caveProfile); + ContainedPlacementResult contained = placeContainedCaveObject( + placer, + variant, + xx, + caveFloorY, + zz, + effectivePlacement, + minDepthBelowSurface, + id, + "procedural", + treePlacement, + rng + ); + placeResult = contained.resultY(); + commitResult = contained.commitResult(); + } else { + String marker = placementMarker(variant, id, "procedural"); + placeResult = variant.place(xx, -1, zz, placer, placement, rng, (b, data) -> { + if (marker != null) { + placer.setData(b.getX(), b.getY(), b.getZ(), marker); + } + if (treePlacement && marker != null) { + writeTreeMaterial(placer, b.getX(), b.getY(), b.getZ(), data); + } + }, null, getData()); + } + if (golden) { + IrisLogging.debug("Goldendebug procedural result: chunk=" + x + "," + z + + " placement=" + p.getName() + + " variant=" + variant.getLoadKey() + + " xx=" + xx + + " zz=" + zz + + " resultY=" + placeResult + + " commit=" + commitResult); + } + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.error("Failed to place procedural object '" + p.getName() + "' in " + scope); + } + } + } + } + + static boolean passesProceduralChance(RNG rng, double chance) { + if (chance <= 0.0) { + return false; + } + if (chance >= 1.0) { + return true; + } + return rng.chance(Math.max(0.0, Math.min(1.0, chance + rng.d(-0.005, 0.005)))); + } + + private CavePlacementAnchor findCavePlacementAnchor( + MantleWriter writer, + RNG rng, + int minX, + int minZ, + IrisCaveAnchorMode anchorMode, + int anchorScanStep, + int minDepthBelowSurface, + int searchAttempts, + String expectedCaveBiomeKey, + boolean underwater, + CaveAnchorCache anchorCache + ) { + for (int search = 0; search < searchAttempts; search++) { + int candidateX = rng.i(minX, minX + 16); + int candidateZ = rng.i(minZ, minZ + 16); + int candidateY = findCaveAnchorY( + writer, + rng, + candidateX, + candidateZ, + anchorMode, + anchorScanStep, + minDepthBelowSurface, + anchorCache + ); + if (candidateY < 0 + || caveAnchorBiomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiomeKey) + || !acceptsCaveAnchorFluid( + underwater, + writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), + candidateY, + getDimension().getCaveLavaHeight())) { + continue; + } + return new CavePlacementAnchor(candidateX, candidateY, candidateZ); + } + return null; + } + + static boolean acceptsCaveAnchorFluid(boolean underwater, MatterCavern cavern, int y, int lavaHeight) { + if (cavern == null || !cavern.isCavern()) { + return false; + } + if (underwater || cavern.getLiquid() == LIQUID_FORCED_AIR) { + return true; + } + return cavern.isAir() && y > lavaHeight; + } + + private ContainedPlacementResult placeContainedCaveObject( + IObjectPlacer placer, + IrisObject object, + int x, + int anchorY, + int z, + IrisObjectPlacement placement, + int minDepthBelowSurface, + int id, + String markerContext, + boolean treePlacement, + RNG rng + ) { + CaveObjectPlacementTransaction transaction = new CaveObjectPlacementTransaction(placer, anchorY, minDepthBelowSurface); + int placeY = anchorY; + if (placement.getMode() == ObjectPlaceMode.CEILING_HANG) { + placeY = Math.max(1, transaction.getCaveCeiling(x, z) - 1 - Math.floorDiv(object.getH(), 2)); + } + String marker = placementMarker(object, id, markerContext); + int result = object.place(x, placeY, z, transaction, placement, rng, (block, data) -> { + if (marker != null) { + transaction.setData(block.getX(), block.getY(), block.getZ(), marker); + } + if (treePlacement && marker != null) { + writeTreeMaterial(transaction, block.getX(), block.getY(), block.getZ(), data); + } + if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { + transaction.setData(block.getX(), block.getY(), block.getZ(), MatterStructurePOI.BURIED_TREASURE); + } + }, null, getData()); + if (result < 0) { + transaction.discard(); + return new ContainedPlacementResult(result, CaveObjectPlacementTransaction.CommitResult.EMPTY); + } + return new ContainedPlacementResult(result, transaction.commit()); + } + + @BlockCoordinates + private ObjectPlacementResult placeObject( + MantleWriter writer, + RNG rng, + int x, + int z, + IrisObjectPlacement objectPlacement, + IrisComplex complex, + boolean traceRegen, + int chunkX, + int chunkZ, + String scope + ) { + int attempts = 0; + int placed = 0; + int rejected = 0; + int nullObjects = 0; + int errors = 0; + int density = objectPlacement.getDensity(rng, x, z, getData()); + boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ); + + for (int i = 0; i < density; i++) { + attempts++; + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + if (v == null) { + nullObjects++; + if (traceRegen) { + IrisLogging.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + + " scope=" + scope + + " densityIndex=" + i + + " density=" + density + + " placementKeys=" + objectPlacement.getPlace().toString(",")); + } + continue; + } + int xx = rng.i(x, x + 16); + int zz = rng.i(z, z + 16); + IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v); + boolean treePlacement = isTreePlacement(v, effectivePlacement); + int id = rng.i(0, Integer.MAX_VALUE); + IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey()) : writer; + if (golden) { + IrisLogging.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + + " scope=" + scope + + " object=" + v.getLoadKey() + + " densityIndex=" + i + + " xx=" + xx + + " zz=" + zz + + " mode=" + effectivePlacement.getMode()); + } + try { + String marker = placementMarker(v, id, "surface"); + int result = v.place(xx, -1, zz, placePlacer, effectivePlacement, rng, (b, data) -> { + if (marker != null) { + writer.setData(b.getX(), b.getY(), b.getZ(), marker); + } + if (treePlacement && marker != null) { + writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); + } + if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) { + writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); + } + }, null, getData()); + + if (result >= 0) { + placed++; + } else { + rejected++; + } + + if (golden) { + IrisLogging.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + + " scope=" + scope + + " object=" + v.getLoadKey() + + " resultY=" + result + + " fallback=surface"); + } + + if (traceRegen) { + IrisLogging.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + + " scope=" + scope + + " object=" + v.getLoadKey() + + " resultY=" + result + + " px=" + xx + + " pz=" + zz + + " fallback=surface" + + " densityIndex=" + i + + " density=" + density); + } + } catch (Throwable e) { + errors++; + IrisLogging.reportError(e); + IrisLogging.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + + " scope=" + scope + + " object=" + v.getLoadKey() + + " densityIndex=" + i + + " density=" + density + + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage()); + } + } + + return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors); + } + + @ChunkCoordinates + private boolean caveAnchorBiomeConflicts(int x, int y, int z, String expectedCaveBiomeKey) { + if (expectedCaveBiomeKey == null) { + return false; + } + Engine engine = getEngineMantle().getEngine(); + IrisBiome at = engine.getCaveBiome(x, y, z); + IrisBiome surface = engine.getSurfaceBiome(x, z); + return caveAnchorBiomeConflicts(at, surface, expectedCaveBiomeKey); + } + + static boolean caveAnchorBiomeConflicts(IrisBiome at, IrisBiome surface, String expectedCaveBiomeKey) { + if (expectedCaveBiomeKey == null || at == null) { + return false; + } + String atKey = at.getLoadKey(); + if (atKey == null || atKey.equals(expectedCaveBiomeKey)) { + return false; + } + if (surface != null && atKey.equals(surface.getLoadKey())) { + return false; + } + return true; + } + + private ObjectPlacementResult placeCaveObject( + MantleWriter writer, + RNG rng, + int chunkX, + int chunkZ, + IrisObjectPlacement objectPlacement, + IrisCaveProfile caveProfile, + IrisComplex complex, + boolean traceRegen, + int metricChunkX, + int metricChunkZ, + String scope, + String expectedCaveBiomeKey, + CaveAnchorCache anchorCache + ) { + int attempts = 0; + int placed = 0; + int rejected = 0; + int nullObjects = 0; + int errors = 0; + int minX = chunkX << 4; + int minZ = chunkZ << 4; + int density = objectPlacement.getDensity(rng, minX, minZ, getData()); + IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); + if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) { + anchorMode = IrisCaveAnchorMode.CEILING; + } + int anchorScanStep = resolveAnchorScanStep(caveProfile); + int objectMinDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); + int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); + + for (int i = 0; i < density; i++) { + attempts++; + IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + if (object == null) { + nullObjects++; + if (traceRegen) { + IrisLogging.debug("Regen cave object placement null object: chunk=" + metricChunkX + "," + metricChunkZ + + " scope=" + scope + + " densityIndex=" + i + + " density=" + density + + " placementKeys=" + objectPlacement.getPlace().toString(",")); + } + logCaveReject( + scope, + "NULL_OBJECT", + metricChunkX, + metricChunkZ, + objectPlacement, + null, + i, + density, + anchorMode, + anchorSearchAttempts, + anchorScanStep, + objectMinDepthBelowSurface, + null, + null + ); + continue; + } + + CavePlacementAnchor anchor = findCavePlacementAnchor( + writer, + rng, + minX, + minZ, + anchorMode, + anchorScanStep, + objectMinDepthBelowSurface, + anchorSearchAttempts, + expectedCaveBiomeKey, + objectPlacement.isUnderwater(), + anchorCache + ); + + if (anchor == null) { + rejected++; + logCaveReject( + scope, + "NO_ANCHOR", + metricChunkX, + metricChunkZ, + objectPlacement, + object, + i, + density, + anchorMode, + anchorSearchAttempts, + anchorScanStep, + objectMinDepthBelowSurface, + null, + null + ); + continue; + } + + int x = anchor.x(); + int y = anchor.y(); + int z = anchor.z(); + + int id = rng.i(0, Integer.MAX_VALUE); + IrisObjectPlacement effectivePlacement = resolveCavePlacement(objectPlacement, object, caveProfile); + + try { + ContainedPlacementResult contained = placeContainedCaveObject( + writer, + object, + x, + y, + z, + effectivePlacement, + objectMinDepthBelowSurface, + id, + "cave", + isTreePlacement(object, effectivePlacement), + rng + ); + int result = contained.resultY(); + boolean wroteBlocks = contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.COMMITTED; + if (wroteBlocks) { + placed++; + } else { + rejected++; + String rejectReason; + if (result < 0) { + rejectReason = "PLACE_NEGATIVE"; + } else if (contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.REJECTED_BOUNDS) { + rejectReason = "CONTAINMENT"; + } else { + rejectReason = "NO_WRITES"; + } + logCaveReject( + scope, + rejectReason, + metricChunkX, + metricChunkZ, + objectPlacement, + object, + i, + density, + anchorMode, + anchorSearchAttempts, + anchorScanStep, + objectMinDepthBelowSurface, + y, + null + ); + } + + if (traceRegen) { + IrisLogging.debug("Regen cave object placement result: chunk=" + metricChunkX + "," + metricChunkZ + + " scope=" + scope + + " object=" + object.getLoadKey() + + " resultY=" + result + + " anchorY=" + y + + " px=" + x + + " pz=" + z + + " wroteBlocks=" + wroteBlocks + + " densityIndex=" + i + + " density=" + density); + } + } catch (Throwable e) { + errors++; + IrisLogging.reportError(e); + IrisLogging.error("Regen cave object placement exception: chunk=" + metricChunkX + "," + metricChunkZ + + " scope=" + scope + + " object=" + object.getLoadKey() + + " densityIndex=" + i + + " density=" + density + + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage()); + logCaveReject( + scope, + "EXCEPTION", + metricChunkX, + metricChunkZ, + objectPlacement, + object, + i, + density, + anchorMode, + anchorSearchAttempts, + anchorScanStep, + objectMinDepthBelowSurface, + y, + e + ); + } + } + + return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors); + } + + @ChunkCoordinates + private void placeUpperObjects( + MantleWriter writer, + RNG rng, + int chunkX, + int chunkZ, + int centerX, + int centerZ, + int lowerSurfaceCenterY, + UpperDimensionContext upperCtx, + IrisDimension dimension, + IrisComplex complex, + boolean traceRegen + ) { + IrisBiome upperBiome = upperCtx.getUpperBiome(centerX, centerZ); + IrisRegion upperRegion = upperCtx.getUpperRegion(centerX, centerZ); + if (upperBiome == null && upperRegion == null) { + return; + } + + boolean forcePlace = dimension.isUpperObjectsForcePlace(); + if (upperBiome != null) { + for (IrisObjectPlacement i : upperBiome.getSurfaceObjects()) { + if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { + continue; + } + try { + placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-biome-surface"); + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.error("Failed to place upper-dimension objects in biome " + upperBiome.getName() + + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")"); + } + } + } + + if (upperRegion != null) { + for (IrisObjectPlacement i : upperRegion.getSurfaceObjects()) { + if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { + continue; + } + try { + placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-region-surface"); + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.error("Failed to place upper-dimension objects in region " + upperRegion.getName() + + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")"); + } + } + } + } + + @ChunkCoordinates + private void placeUpperObject( + MantleWriter writer, + RNG rng, + int chunkX, + int chunkZ, + IrisObjectPlacement objectPlacement, + UpperDimensionContext upperCtx, + IrisDimension dimension, + IrisComplex complex, + boolean forcePlace, + boolean traceRegen, + String scope + ) { + int chunkHeight = getEngineMantle().getEngine().getHeight(); + int upperGap = dimension.getUpperDimensionGap(); + int minX = chunkX << 4; + int minZ = chunkZ << 4; + int density = objectPlacement.getDensity(rng, minX, minZ, getData()); + + for (int i = 0; i < density; i++) { + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + if (v == null) { + continue; + } + + int xx = rng.i(minX, minX + 16); + int zz = rng.i(minZ, minZ + 16); + int columnLowerSurfaceY = getEngineMantle().getEngine().getHeight(xx, zz, true); + int rawUpperSurface = upperCtx.getUpperSurfaceY(xx, zz); + int upperSurfaceY = Math.max(rawUpperSurface, columnLowerSurfaceY + upperGap); + if (upperSurfaceY >= chunkHeight - 2) { + continue; + } + + int halfH = Math.floorDiv(v.getH(), 2); + int anchorY = upperSurfaceY - 1 - halfH; + if (anchorY <= 1) { + continue; + } + + int id = rng.i(0, Integer.MAX_VALUE); + IrisObjectPlacement placement = objectPlacement.toPlacement(v.getLoadKey()); + placement.setMode(ObjectPlaceMode.CENTER_HEIGHT); + placement.setRotation(buildUpsideDownRotation()); + placement.setCarvingSupport(CarvingMode.ANYWHERE); + if (forcePlace) { + placement.setForcePlace(true); + } + boolean treePlacement = isTreePlacement(v, objectPlacement); + String marker = placementMarker(v, id, "upper"); + + int result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> { + if (marker != null) { + writer.setData(b.getX(), b.getY(), b.getZ(), marker); + } + if (treePlacement && marker != null) { + writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); + } + if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { + writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); + } + }, null, getData()); + + if (traceRegen) { + IrisLogging.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + + " scope=" + scope + + " object=" + v.getLoadKey() + + " anchorY=" + anchorY + + " upperSurfaceY=" + upperSurfaceY + + " resultY=" + result + + " forcePlace=" + forcePlace); + } + } + } + + private IrisObjectRotation buildUpsideDownRotation() { + IrisObjectRotation rt = new IrisObjectRotation(); + rt.setEnabled(true); + rt.setXAxis(new IrisAxisRotationClamp(true, true, 180D, 180D, 90D)); + rt.setYAxis(new IrisAxisRotationClamp(true, false, 0D, 0D, 90D)); + rt.setZAxis(new IrisAxisRotationClamp()); + return rt; + } + + private void logCaveReject( + String scope, + String reason, + int chunkX, + int chunkZ, + IrisObjectPlacement objectPlacement, + IrisObject object, + int densityIndex, + int density, + IrisCaveAnchorMode anchorMode, + int anchorSearchAttempts, + int anchorScanStep, + int objectMinDepthBelowSurface, + Integer anchorY, + Throwable error + ) { + if (!IrisSettings.get().getGeneral().isDebug()) { + return; + } + + String placementKeys = objectPlacement == null ? "none" : objectPlacement.getPlace().toString(","); + String objectKey = object == null ? "null" : object.getLoadKey(); + String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; + CaveRejectLogState state = CAVE_REJECT_LOG_STATE.computeIfAbsent(throttleKey, (k) -> new CaveRejectLogState()); + long now = System.currentTimeMillis(); + long last = state.lastLogMs.get(); + if ((now - last) < CAVE_REJECT_LOG_THROTTLE_MS) { + state.suppressed.incrementAndGet(); + return; + } + + if (!state.lastLogMs.compareAndSet(last, now)) { + state.suppressed.incrementAndGet(); + return; + } + + int suppressed = state.suppressed.getAndSet(0); + String anchorYText = anchorY == null ? "none" : String.valueOf(anchorY); + String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + String.valueOf(error.getMessage()); + IrisLogging.debug("Cave object reject: scope=" + scope + + " reason=" + reason + + " chunk=" + chunkX + "," + chunkZ + + " object=" + objectKey + + " placements=" + placementKeys + + " densityIndex=" + densityIndex + + " density=" + density + + " anchorMode=" + anchorMode + + " anchorSearchAttempts=" + anchorSearchAttempts + + " anchorScanStep=" + anchorScanStep + + " minDepthBelowSurface=" + objectMinDepthBelowSurface + + " anchorY=" + anchorYText + + " forcePlace=" + (objectPlacement != null && objectPlacement.isForcePlace()) + + " carvingSupport=" + (objectPlacement == null ? "none" : objectPlacement.getCarvingSupport()) + + " bottom=" + (objectPlacement != null && objectPlacement.isBottom()) + + " suppressed=" + suppressed + + " error=" + errorText); + } + + private IrisObjectPlacement resolveEffectivePlacement(IrisObjectPlacement objectPlacement, IrisObject object) { + if (objectPlacement == null || object == null) { + return objectPlacement; + } + + return applyDimensionSurfaceSupport(resolveImportedPlacement(objectPlacement, object)); + } + + /** Dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ + private IrisObjectPlacement applyDimensionSurfaceSupport(IrisObjectPlacement placement) { + IrisDimension dimension = getDimension(); + boolean require = placement.isRequireSurfaceSupport() && dimension.isRequireObjectSurfaceSupport(); + int buffer = Math.max(placement.getSurfaceSupportBuffer(), dimension.getObjectSurfaceSupportBuffer()); + if (require == placement.isRequireSurfaceSupport() && buffer == placement.getSurfaceSupportBuffer()) { + return placement; + } + + IrisObjectPlacement resolved = placement.toPlacement(placement.getPlace().toArray(new String[0])); + resolved.setRequireSurfaceSupport(require); + resolved.setSurfaceSupportBuffer(buffer); + return resolved; + } + + private IrisObjectPlacement resolveImportedPlacement(IrisObjectPlacement objectPlacement, IrisObject object) { + String loadKey = object.getLoadKey(); + if (loadKey == null || loadKey.isBlank()) { + return objectPlacement; + } + + String normalized = loadKey.toLowerCase(Locale.ROOT); + boolean imported = normalized.startsWith("imports/") + || normalized.contains("/imports/") + || normalized.contains("imports/"); + + if (!imported) { + return objectPlacement; + } + + ObjectPlaceMode mode = objectPlacement.getMode(); + if (mode == ObjectPlaceMode.FLOATING || mode == ObjectPlaceMode.STRUCTURE_PIECE) { + return objectPlacement; + } + boolean needsModeChange = mode != ObjectPlaceMode.FAST_MIN_STILT; + if (!needsModeChange) { + return objectPlacement; + } + + IrisObjectPlacement effectivePlacement = objectPlacement.toPlacement(loadKey); + effectivePlacement.setMode(ObjectPlaceMode.FAST_MIN_STILT); + return effectivePlacement; + } + + private IrisObjectPlacement resolveCavePlacement(IrisObjectPlacement objectPlacement, IrisObject object, IrisCaveProfile caveProfile) { + IrisObjectPlacement resolvedPlacement = resolveEffectivePlacement(objectPlacement, object); + if (resolvedPlacement.getMode() != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { + return resolvedPlacement; + } + + ObjectPlaceMode profileMode = caveProfile.getDefaultObjectPlaceMode(); + if (profileMode == null) { + return resolvedPlacement; + } + + String loadKey = object.getLoadKey(); + if (loadKey == null || loadKey.isBlank()) { + resolvedPlacement = resolvedPlacement.toPlacement(); + } else { + resolvedPlacement = resolvedPlacement.toPlacement(loadKey); + } + resolvedPlacement.setMode(profileMode); + return resolvedPlacement; + } + + static int caveAnchorScanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) { + int maxAnchorY = CaveObjectPlacementTransaction.maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface); + if (maxAnchorY <= 1) { + return 0; + } + return maxAnchorY + 1; + } + + private int findCaveAnchorY(MantleWriter writer, RNG rng, int x, int z, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, CaveAnchorCache anchorCache) { + KList anchors = anchorCache.get(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z); + if (anchors.isEmpty()) { + return -1; + } + + if (anchors.size() == 1) { + return anchors.get(0); + } + + return anchors.get(rng.i(anchors.size())); + } + + private KList scanCaveAnchorColumn(MantleWriter writer, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z, CaveAnchorCache anchorCache) { + int height = getEngineMantle().getEngine().getHeight(); + int step = Math.max(1, anchorScanStep); + int surfaceY = anchorCache.getSurfaceHeight(x, z); + int maxAnchorExclusive = caveAnchorScanUpperBound(height, surfaceY, objectMinDepthBelowSurface); + if (maxAnchorExclusive == 0) { + return new KList<>(); + } + + int carvedHeight = Math.min(height, maxAnchorExclusive + 3); + byte[] carvedColumn = anchorCache.getCarvedColumn(writer, x, z, carvedHeight); + return scanCaveAnchorRange(anchorMode, step, carvedHeight, BEDROCK_CLEARANCE, maxAnchorExclusive, carvedColumn); + } + + private KList scanCaveAnchorRange(IrisCaveAnchorMode anchorMode, int step, int height, int minAnchorY, int maxAnchorY, byte[] carvedColumn) { + KList anchors = new KList<>(); + int startY = alignAnchorScanStart(minAnchorY, step); + for (int y = startY; y < maxAnchorY; y += step) { + if (!isCarved(carvedColumn, y)) { + continue; + } + + boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1); + boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1); + if (matchesCaveAnchor(anchorMode, solidBelow, solidAbove)) { + anchors.add(y); + } + } + return anchors; + } + + private int alignAnchorScanStart(int minAnchorY, int step) { + if (minAnchorY <= BEDROCK_CLEARANCE) { + return BEDROCK_CLEARANCE; + } + + int delta = minAnchorY - BEDROCK_CLEARANCE; + int steps = (delta + step - 1) / step; + return BEDROCK_CLEARANCE + (steps * step); + } + + private boolean isCarved(byte[] carvedColumn, int y) { + return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1; + } + + private boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) { + for (int d = 1; d <= 3; d++) { + int ny = y + (direction * d); + if (ny < 0 || ny >= height) { + return true; + } + if (!isCarved(carvedColumn, ny)) { + return true; + } + } + return false; + } + + private boolean matchesCaveAnchor(IrisCaveAnchorMode anchorMode, boolean solidBelow, boolean solidAbove) { + return switch (anchorMode) { + case PROFILE_DEFAULT, FLOOR -> solidBelow; + case CEILING -> solidAbove; + case CENTER -> !solidBelow && !solidAbove; + case ANY -> true; + }; + } + + private IrisCaveProfile resolveCaveProfile(IrisCaveProfile preferred, IrisCaveProfile secondary) { + IrisCaveProfile dimensionProfile = getDimension().getCaveProfile(); + if (preferred != null && preferred.isEnabled()) { + return preferred; + } + + if (secondary != null && secondary.isEnabled()) { + return secondary; + } + + if (dimensionProfile != null) { + return dimensionProfile; + } + + return new IrisCaveProfile(); + } + + private IrisCaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, IrisCaveProfile caveProfile) { + IrisCaveAnchorMode placementMode = objectPlacement.getCaveAnchorMode(); + if (placementMode != null && !placementMode.equals(IrisCaveAnchorMode.PROFILE_DEFAULT)) { + return placementMode; + } + + if (caveProfile == null) { + return IrisCaveAnchorMode.FLOOR; + } + + IrisCaveAnchorMode profileMode = caveProfile.getDefaultObjectAnchor(); + if (profileMode == null || profileMode.equals(IrisCaveAnchorMode.PROFILE_DEFAULT)) { + return IrisCaveAnchorMode.FLOOR; + } + + return profileMode; + } + + private int resolveAnchorScanStep(IrisCaveProfile caveProfile) { + if (caveProfile == null) { + return 1; + } + + return Math.max(1, caveProfile.getAnchorScanStep()); + } + + private int resolveObjectMinDepthBelowSurface(IrisCaveProfile caveProfile) { + if (caveProfile == null) { + return 6; + } + + return Math.max(0, caveProfile.getObjectMinDepthBelowSurface()); + } + + private int resolveAnchorSearchAttempts(IrisCaveProfile caveProfile) { + if (caveProfile == null) { + return 6; + } + + return Math.max(1, caveProfile.getAnchorSearchAttempts()); + } + + private boolean isRegenTraceThread() { + return Thread.currentThread().getName().startsWith("Iris-Regen-") + && IrisSettings.get().getGeneral().isDebug(); + } + + private record ObjectPlacementSummary( + int biomeSurfacePlacersChecked, + int biomeSurfacePlacersTriggered, + int biomeCavePlacersChecked, + int biomeCavePlacersTriggered, + int regionSurfacePlacersChecked, + int regionSurfacePlacersTriggered, + int regionCavePlacersChecked, + int regionCavePlacersTriggered, + int objectAttempts, + int objectPlaced, + int objectRejected, + int objectNull, + int objectErrors + ) { + } + + private record ObjectPlacementResult(int attempts, int placed, int rejected, int nullObjects, int errors) { + } + + private record CavePlacementAnchor(int x, int y, int z) { + } + + private record ContainedPlacementResult( + int resultY, + CaveObjectPlacementTransaction.CommitResult commitResult + ) { + } + + private static final class CaveRejectLogState { + private final AtomicLong lastLogMs = new AtomicLong(0L); + private final AtomicInteger suppressed = new AtomicInteger(0); + } + + @BlockCoordinates + private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { + Set f = new KSet<>(); + for (int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) { + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(getComplex(), rng)); + if (v == null) { + continue; + } + + f.add(v.getLoadKey()); + } + + return f; + } + + public Set guess(int x, int z) { + // todo The guess doesnt bring into account that the placer may return -1 + RNG rng = applyNoise(x, z, Cache.key(x, z) + seed()); + IrisBiome biome = getEngineMantle().getEngine().getSurfaceBiome((x << 4) + 8, (z << 4) + 8); + IrisRegion region = getEngineMantle().getEngine().getRegion((x << 4) + 8, (z << 4) + 8); + Set v = new KSet<>(); + for (IrisObjectPlacement i : biome.getSurfaceObjects()) { + if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { + v.addAll(guessPlacedKeys(rng, x, z, i)); + } + } + + for (IrisObjectPlacement i : region.getSurfaceObjects()) { + if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { + v.addAll(guessPlacedKeys(rng, x, z, i)); + } + } + + return v; + } + + protected int computeRadius() { + IrisDimension dimension = getDimension(); + KMap sizeCache = new KMap<>(); + KSet warnedLargeObjects = new KSet<>(); + int radius = 0; + for (IrisRegion region : dimension.getAllRegions(this::getData)) { + if (region == null) { + continue; + } + radius = Math.max(radius, computePlacementRadius(region.getObjects(), sizeCache, warnedLargeObjects)); + radius = Math.max(radius, computeProceduralRadius(region.getProceduralObjects())); + } + for (IrisBiome biome : dimension.getReachableBiomes(this::getData)) { + if (biome == null) { + continue; + } + radius = Math.max(radius, computePlacementRadius(biome.getObjects(), sizeCache, warnedLargeObjects)); + radius = Math.max(radius, computeProceduralRadius(biome.getProceduralObjects())); + } + + return radius; + } + + private int computePlacementRadius( + KList placements, + KMap sizeCache, + KSet warnedLargeObjects + ) { + int radius = 0; + for (IrisObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.getPlace()) { + try { + IrisBlockVector size = loadObjectSize(sizeCache, objectKey); + if (size == null) { + continue; + } + int reach = calculatePlacementReach(size, placement); + if (reach > 128 && warnedLargeObjects.add(objectKey)) { + IrisLogging.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + radius = Math.max(radius, reach); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + return radius; + } + + private int computeProceduralRadius(IrisProceduralObjects procedural) { + if (procedural == null || procedural.isEmpty()) { + return 0; + } + int radius = 0; + for (IrisProceduralPlacement placement : procedural.getAllPlacements()) { + if (placement == null) { + continue; + } + KList variants = placement.getVariantObjects(getData()); + if (variants == null) { + continue; + } + IrisObjectPlacement objectPlacement = placement.asPlacement(); + for (IrisObject variant : variants) { + if (variant == null) { + continue; + } + IrisBlockVector size = new IrisBlockVector(variant.getW(), variant.getH(), variant.getD()); + radius = Math.max(radius, calculatePlacementReach(size, objectPlacement)); + } + } + return radius; + } + + static int calculatePlacementReach(IrisBlockVector size, IrisObjectPlacement placement) { + if (size == null) { + return 0; + } + if (placement == null) { + return Math.max(Math.abs(size.getBlockX()), Math.abs(size.getBlockZ())); + } + + double scale = placement.getScale() != null ? Math.max(1D, placement.getScale().getMaxScale()) : 1D; + int width = scaledDimension(size.getBlockX(), scale); + int height = scaledDimension(size.getBlockY(), scale); + int depth = scaledDimension(size.getBlockZ(), scale); + IrisObjectRotation rotation = placement.getRotation(); + boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().isEnabled(); + boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().isEnabled(); + int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); + int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); + int warp = placement.getWarp() != null && !placement.getWarp().isFlat() + ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) + : 0; + int vacuum = IrisObjectVacuum.isVacuumMode(placement.getMode()) + ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode(), placement.getVacuumSettings()) + : 0; + long reach = (long) footprint + translation + warp + vacuum; + return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + } + + private static int scaledDimension(int dimension, double scale) { + int absoluteDimension = Math.abs(dimension); + if (scale <= 1D) { + return absoluteDimension; + } + return (int) Math.ceil((absoluteDimension * scale) + (scale * 2D)); + } + + private static int calculateTranslationReach(IrisObjectTranslate translate, IrisObjectRotation rotation, boolean rotateVertically) { + if (translate == null || !translate.canTranslate()) { + return 0; + } + double x = translate.getX(); + double y = translate.getY(); + double z = translate.getZ(); + if (rotateVertically) { + return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); + } + boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().isEnabled(); + return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); + } + + private IrisBlockVector loadObjectSize(KMap sizeCache, String objectKey) { + return sizeCache.computeIfAbsent(objectKey, k -> { + try { + return IrisObject.sampleSize(getData().getObjectLoader().findFile(objectKey)); + } catch (IOException e) { + IrisLogging.reportError(e); + } + + return null; + }); + } + + private final class CaveAnchorCache { + private final Long2ObjectOpenHashMap>> settingCaches; + private final Long2ObjectOpenHashMap carvedColumns; + private final Long2IntOpenHashMap surfaceHeights; + + private CaveAnchorCache() { + this.settingCaches = new Long2ObjectOpenHashMap<>(); + this.carvedColumns = new Long2ObjectOpenHashMap<>(); + this.surfaceHeights = new Long2IntOpenHashMap(); + this.surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); + } + + private KList get(MantleWriter writer, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z) { + if (anchorScanStep > 65535 || objectMinDepthBelowSurface > 65535) { + return scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); + } + + long settingKey = ((long) anchorMode.ordinal() << 32) | ((long) anchorScanStep << 16) | objectMinDepthBelowSurface; + Long2ObjectOpenHashMap> columnCache = settingCaches.get(settingKey); + if (columnCache == null) { + columnCache = new Long2ObjectOpenHashMap<>(); + settingCaches.put(settingKey, columnCache); + } + + long columnKey = Cache.key(x, z); + KList anchors = columnCache.get(columnKey); + if (anchors != null) { + return anchors; + } + + anchors = scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); + columnCache.put(columnKey, anchors); + return anchors; + } + + private byte[] getCarvedColumn(MantleWriter writer, int x, int z, int height) { + long columnKey = Cache.key(x, z); + byte[] carvedColumn = carvedColumns.get(columnKey); + if (carvedColumn != null && carvedColumn.length == height) { + return carvedColumn; + } + + carvedColumn = writer.getCarvedColumn(x, z, height); + carvedColumns.put(columnKey, carvedColumn); + return carvedColumn; + } + + private int getSurfaceHeight(int x, int z) { + long columnKey = Cache.key(x, z); + int surfaceY = surfaceHeights.get(columnKey); + if (surfaceY != Integer.MIN_VALUE) { + return surfaceY; + } + + surfaceY = getEngineMantle().getEngine().getHeight(x, z); + surfaceHeights.put(columnKey, surfaceY); + return surfaceY; + } + } + +} 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 new file mode 100644 index 000000000..e5420b6fa --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java @@ -0,0 +1,147 @@ +/* + * 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.engine.object.structure.IrisStructureCarveShape; +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(IrisStructureCarveShape shape, double distanceSquared, + double noise, double strength) { + if (distanceSquared <= 0.0) { + return true; + } + IrisStructureCarveShape resolvedShape = shape == null ? IrisStructureCarveShape.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 new file mode 100644 index 000000000..0d3548522 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java @@ -0,0 +1,456 @@ +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.iris.util.common.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 new file mode 100644 index 000000000..3ac2c9737 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java @@ -0,0 +1,79 @@ +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/SurfaceFluidBoundaryPlan.java b/src/main/java/art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan.java new file mode 100644 index 000000000..ec0cf02e9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan.java @@ -0,0 +1,94 @@ +/* + * 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.volmlib.util.math.PowerOfTwoCoordinates; + +final class SurfaceFluidBoundaryPlan { + static final int NO_BOUNDARY = Integer.MAX_VALUE; + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + + private SurfaceFluidBoundaryPlan() { + } + + static void fill( + int[] chunkSurfaceHeights, + double[] fieldSurfaceHeights, + boolean[] fieldHasFluid, + int fieldSize, + int padding, + int fluidHeight, + int[] boundaryStartY + ) { + if (chunkSurfaceHeights == null || chunkSurfaceHeights.length < CHUNK_AREA + || boundaryStartY == null || boundaryStartY.length < CHUNK_AREA + || padding < 1 || fieldSize < CHUNK_SIZE + (padding * 2) + || fieldSurfaceHeights == null || fieldSurfaceHeights.length < fieldSize * fieldSize + || fieldHasFluid == null || fieldHasFluid.length < fieldSize * fieldSize) { + throw new IllegalArgumentException("Surface fluid boundary fields do not cover a padded chunk"); + } + + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + int fieldX = localX + padding; + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { + int fieldZ = localZ + padding; + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + int boundaryY = NO_BOUNDARY; + int surfaceY = chunkSurfaceHeights[columnIndex]; + int fieldIndex = (fieldX * fieldSize) + fieldZ; + if (fieldHasFluid[fieldIndex] && surfaceY < fluidHeight) { + boundaryY = surfaceY; + } + + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + ((fieldX - 1) * fieldSize) + fieldZ, fluidHeight); + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + ((fieldX + 1) * fieldSize) + fieldZ, fluidHeight); + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + (fieldX * fieldSize) + fieldZ - 1, fluidHeight); + boundaryY = lowerBoundary(boundaryY, fieldSurfaceHeights, fieldHasFluid, + (fieldX * fieldSize) + fieldZ + 1, fluidHeight); + boundaryStartY[columnIndex] = boundaryY; + } + } + } + + static boolean protects(int[] boundaryStartY, int columnIndex, int y, int fluidHeight) { + return boundaryStartY != null + && columnIndex >= 0 + && columnIndex < boundaryStartY.length + && y >= boundaryStartY[columnIndex] + && y <= fluidHeight; + } + + private static int lowerBoundary( + int currentBoundaryY, + double[] fieldSurfaceHeights, + boolean[] fieldHasFluid, + int fieldIndex, + int fluidHeight + ) { + int neighborSurfaceY = (int) Math.round(fieldSurfaceHeights[fieldIndex]); + if (!fieldHasFluid[fieldIndex] || neighborSurfaceY >= fluidHeight) { + return currentBoundaryY; + } + return Math.min(currentBoundaryY, neighborSurfaceY + 1); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java b/src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java new file mode 100644 index 000000000..09d2f9f15 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java @@ -0,0 +1,38 @@ +/* + * 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.mode; + +import art.arcane.iris.engine.actuator.IrisBiomeActuator; +import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.framework.IrisEngineMode; + +public class ModeEnclosure extends IrisEngineMode implements EngineMode { + public ModeEnclosure(Engine engine) { + super(engine); + var terrain = new IrisTerrainNormalActuator(getEngine()); + var biome = new IrisBiomeActuator(getEngine()); + + registerStage(burst( + (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c), + (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c) + )); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeIslands.java b/src/main/java/art/arcane/iris/engine/mode/ModeIslands.java new file mode 100644 index 000000000..494b46bc8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mode/ModeIslands.java @@ -0,0 +1,38 @@ +/* + * 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.mode; + +import art.arcane.iris.engine.actuator.IrisBiomeActuator; +import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.framework.IrisEngineMode; + +public class ModeIslands extends IrisEngineMode implements EngineMode { + public ModeIslands(Engine engine) { + super(engine); + var terrain = new IrisTerrainNormalActuator(getEngine()); + var biome = new IrisBiomeActuator(getEngine()); + + registerStage(burst( + (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c), + (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c) + )); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java b/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java new file mode 100644 index 000000000..a2f1e161c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java @@ -0,0 +1,133 @@ +/* + * 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.mode; + +import art.arcane.iris.engine.actuator.IrisBiomeActuator; +import art.arcane.iris.engine.actuator.IrisDecorantActuator; +import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.framework.EnginePlatformHooks; +import art.arcane.iris.engine.framework.EngineStage; +import art.arcane.iris.engine.framework.IrisEngineMode; +import art.arcane.iris.engine.modifier.IrisCarveModifier; +import art.arcane.iris.engine.modifier.IrisCustomModifier; +import art.arcane.iris.engine.modifier.IrisDepositModifier; +import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier; +import art.arcane.iris.engine.modifier.IrisPerfectionModifier; +import art.arcane.iris.engine.modifier.IrisPostModifier; +import art.arcane.iris.spi.IrisLogging; + +import java.util.concurrent.atomic.AtomicLong; + +public class ModeOverworld extends IrisEngineMode implements EngineMode { + private static final AtomicLong lastMaintenanceBypassLog = new AtomicLong(0L); + private final EnginePlatformHooks platformHooks; + + public ModeOverworld(Engine engine) { + super(engine); + platformHooks = engine.getPlatformHooks(); + IrisTerrainNormalActuator terrain = new IrisTerrainNormalActuator(getEngine()); + IrisBiomeActuator biome = new IrisBiomeActuator(getEngine()); + IrisDecorantActuator decorant = new IrisDecorantActuator(getEngine()); + IrisCarveModifier cave = new IrisCarveModifier(getEngine()); + IrisPostModifier post = new IrisPostModifier(getEngine()); + IrisDepositModifier deposit = new IrisDepositModifier(getEngine()); + IrisPerfectionModifier perfection = new IrisPerfectionModifier(getEngine()); + IrisCustomModifier custom = new IrisCustomModifier(getEngine()); + IrisFloatingChildBiomeModifier floatingChildBiomes = new IrisFloatingChildBiomeModifier(getEngine()); + EngineStage sBiome = (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c); + EngineStage sGenMatter = (x, z, k, p, m, c) -> { + if (shouldBypassMantleStages()) { + return; + } + generateMatter( + x >> 4, + z >> 4, + m || getEngine().isStudio(), + c); + }; + EngineStage sTerrain = (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c); + EngineStage sDecorant = (x, z, k, p, m, c) -> decorant.actuate(x, z, k, m, c); + EngineStage sCave = (x, z, k, p, m, c) -> { + if (shouldBypassMantleStages()) { + return; + } + cave.modify(x >> 4, z >> 4, k, m, c); + }; + EngineStage sDeposit = (x, z, k, p, m, c) -> { + if (shouldBypassMantleStages()) { + return; + } + deposit.modify(x, z, k, m, c); + }; + EngineStage sPost = (x, z, k, p, m, c) -> { + if (shouldBypassMantleStages()) { + return; + } + post.modify(x, z, k, m, c); + }; + EngineStage sInsertMatter = (x, z, K, p, m, c) -> { + if (shouldBypassMantleStages()) { + return; + } + getMantle().insertMatter(x >> 4, z >> 4, K, m); + }; + EngineStage sFloatingTerrainSolid = (x, z, k, p, m, c) -> floatingChildBiomes.modify(x, z, k, m, c); + EngineStage sFloatingDecorate = (x, z, k, p, m, c) -> floatingChildBiomes.decorateColumns(x, z, k, m, c); + EngineStage sPerfection = (x, z, k, p, m, c) -> perfection.modify(x, z, k, m, c); + EngineStage sCustom = (x, z, k, p, m, c) -> { + if (shouldBypassMantleStages()) { + return; + } + custom.modify(x, z, k, m, c); + }; + + registerStage(burst( + sBiome, + sGenMatter, + sTerrain + )); + registerStage(sCave); + registerStage(sPost); + registerStage(sFloatingTerrainSolid); + // Never burst these three: all of them write the same block hunk (and sDecorant reads + // the surface sInsertMatter writes), so parallel order is scheduler-dependent. The + // production path already runs them inline in this order; sequential registration + // makes studio (the only multicore path) match production and the goldenhash baseline. + registerStage(sDeposit); + registerStage(sInsertMatter); + registerStage(sDecorant); + registerStage(sFloatingDecorate); + registerStage(sPerfection); + registerStage(sCustom); + } + + private boolean shouldBypassMantleStages() { + boolean active = platformHooks.shouldBypassMantleStages(getEngine()); + if (active) { + long now = System.currentTimeMillis(); + long last = lastMaintenanceBypassLog.get(); + if (now - last >= 5000L && lastMaintenanceBypassLog.compareAndSet(last, now)) { + IrisLogging.info("Maintenance regen bypass: skipping mantle-backed overworld stages for Folia safety."); + } + } + return active; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java b/src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java new file mode 100644 index 000000000..6cc04308b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java @@ -0,0 +1,38 @@ +/* + * 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.mode; + +import art.arcane.iris.engine.actuator.IrisBiomeActuator; +import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.framework.IrisEngineMode; + +public class ModeSuperFlat extends IrisEngineMode implements EngineMode { + public ModeSuperFlat(Engine engine) { + super(engine); + var terrain = new IrisTerrainNormalActuator(getEngine()); + var biome = new IrisBiomeActuator(getEngine()); + + registerStage(burst( + (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c), + (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c) + )); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java new file mode 100644 index 000000000..ec65c6323 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java @@ -0,0 +1,777 @@ +/* + * 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.modifier; + +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.actuator.IrisDecorantActuator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.engine.object.world.biome.InferredType; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.mantle.runtime.TectonicPlate; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.M; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.slices.MarkerMatter; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import lombok.Data; +import art.arcane.iris.spi.PlatformBlockState; + +import java.util.Map; + +public class IrisCarveModifier extends EngineAssignedModifier { + private static final byte LIQUID_FLUID = 1; + private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(IrisCarveScratch::new); + private static final int CAVE_BIOME_BLEND_RADIUS = 3; + private static final int CAVE_BIOME_BLEND_CENTER_WEIGHT = 4; + private static final int CAVE_BIOME_BLEND_TOTAL_WEIGHT = 8; + private static final MatterCavern BASIC_CAVERN = new MatterCavern(true, "", (byte) 0); + private final RNG rng; + private final PlatformBlockState AIR = B.getState("CAVE_AIR"); + private final PlatformBlockState LAVA = B.getState("LAVA"); + private final IrisDecorantActuator decorant; + + public IrisCarveModifier(Engine engine) { + super(engine, "Carve"); + rng = new RNG(getEngine().getSeedManager().getCarve()); + decorant = new IrisDecorantActuator(engine); + } + + @Override + @ChunkCoordinates + public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start(); + Mantle mantle = getEngine().getMantle().getMantle(); + IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); + Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(2048); + IrisCarveScratch scratch = SCRATCH.get(); + scratch.reset(); + CarveWallBuffer walls = scratch.walls; + CarveColumnMask[] columnMasks = scratch.columnMasks; + CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; + int[] surfaceHeights = scratch.surfaceHeights; + Map customBiomeCache = scratch.customBiomeCache; + UpperDimensionContext upperCtx = getEngine().getUpperContext(); + boolean protectUpper = upperCtx != null && !getEngine().getDimension().isUpperDimensionCarving(); + int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; + int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(x); + int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(z); + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ); + if (protectUpper) { + int worldX = localX + chunkBlockX; + int worldZ = localZ + chunkBlockZ; + int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); + int gap = getEngine().getDimension().getUpperDimensionGap(); + upperSurfaceHeights[columnIndex] = Math.max(rawUpper, surfaceHeights[columnIndex] + gap); + } + } + + MantleChunk mantleChunk = mantle.getChunk(x, z).use(); + try { + PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); + int worldHeightSpan = getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight(); + int caveLavaHeight = getEngine().getDimension().getCaveLavaHeight(); + mantleChunk.iterate(MatterCavern.class, (xx, yy, zz, cavern) -> { + if (cavern == null) { + return; + } + + if (yy >= worldHeightSpan || yy <= 0) { + return; + } + + int rx = xx & 15; + int rz = zz & 15; + int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); + + if (upperSurfaceHeights != null && yy >= upperSurfaceHeights[columnIndex]) { + return; + } + + PlatformBlockState current = output.getRaw(rx, yy, rz); + boolean explicitCarveIntent = hasExplicitCarveIntent(cavern); + + if (shouldPreserveExistingFluid(cavern, current)) { + return; + } + + columnMasks[columnIndex].add(yy); + + if (!cavern.getCustomBiome().isEmpty()) { + scratch.customCaveBiomePresent = true; + } + + if (current.isAir() && !explicitCarveIntent) { + return; + } + + if (explicitCarveIntent) { + // Only a fluid cavern consumes the fluid sample, and on the maintenance path that + // sample is a full procedural stream evaluation, so never take it per voxel. + PlatformBlockState fluid = isFluidIntent(cavern) ? context.getFluid().get(rx, rz) : null; + output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR)); + } else if (usesDefaultLava(caveLavaHeight, yy)) { + output.setRaw(rx, yy, rz, LAVA); + } else { + output.setRaw(rx, yy, rz, AIR); + } + }); + if (scratch.customCaveBiomePresent) { + addInternalWallsFromMantle(mantleChunk, walls, columnMasks); + } else { + addInternalWallsFromMasks(walls, columnMasks); + } + addCrossChunkBoundaryWalls(mantle, mantleChunk, walls, boundaryMasks, x, z, surfaceHeights); + getEngine().getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); + + PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); + try { + walls.forEach((rx, yy, rz, cavern) -> { + int worldX = rx + chunkBlockX; + int worldZ = rz + chunkBlockZ; + String customBiome = cavern.getCustomBiome(); + IrisBiome biome = customBiome.isEmpty() + ? resolveCaveBiome(caveBiomeCache, worldX, yy, worldZ, resolverState) + : resolveCustomBiome(customBiomeCache, customBiome); + + if (biome != null) { + PlatformBlockState data = biome.getWall().get(rng, worldX, yy, worldZ, getData()); + int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); + + if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { + output.setRaw(rx, yy, rz, data); + } + } + }); + + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + processColumnFromMask(output, mantleChunk, mantle, columnMasks[columnIndex], columnIndex, x, z, resolverState, caveBiomeCache, customBiomeCache); + } + + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { + continue; + } + processBoundaryColumnFromMask(output, boundaryMasks[columnIndex], walls, columnIndex, x, z, resolverState, caveBiomeCache, customBiomeCache); + } + + // Surface-break carving must not leave an ore cap suspended across the opening. + for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { + int surfaceY = surfaceHeights[columnIndex]; + if (surfaceY <= 0 || surfaceY >= output.getHeight()) { + continue; + } + + int belowY = surfaceY - 1; + if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) { + continue; + } + + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + PlatformBlockState surface = output.getRaw(localX, surfaceY, localZ); + PlatformBlockState below = output.getRaw(localX, belowY, localZ); + if (isUnsupportedSurfaceOre(surface, below)) { + output.setRaw(localX, surfaceY, localZ, AIR); + } + } + } finally { + getEngine().getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); + } + } finally { + getEngine().getMetrics().getCave().put(caveStopwatch.getMilliseconds()); + mantleChunk.release(); + } + } + + static boolean hasExplicitCarveIntent(MatterCavern cavern) { + return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == 3); + } + + static boolean isFluidIntent(MatterCavern cavern) { + return cavern != null && cavern.getLiquid() == LIQUID_FLUID; + } + + static boolean shouldPreserveExistingFluid(MatterCavern cavern, PlatformBlockState current) { + return B.isFluid(current) && !hasExplicitCarveIntent(cavern); + } + + static boolean usesDefaultLava(int caveLavaHeight, int y) { + return y <= caveLavaHeight; + } + + static boolean isUnsupportedSurfaceOre(PlatformBlockState surface, PlatformBlockState below) { + return B.isOre(surface) && !B.isSolid(below); + } + + static PlatformBlockState resolveExplicitCarveState(MatterCavern cavern, PlatformBlockState fluid, + PlatformBlockState lava, PlatformBlockState air) { + if (cavern == null) { + return null; + } + if (isFluidIntent(cavern)) { + return fluid; + } + if (cavern.isLava()) { + return lava; + } + return cavern.getLiquid() == 3 ? air : null; + } + + private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { + walls.put(rx, yy, rz + 1, BASIC_CAVERN); + } + if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { + walls.put(rx + 1, yy, rz, BASIC_CAVERN); + } + if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { + walls.put(rx, yy, rz - 1, BASIC_CAVERN); + } + if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { + walls.put(rx - 1, yy, rz, BASIC_CAVERN); + } + yy = columnMask.nextSetBit(yy + 1); + } + } + } + + private void addInternalWallsFromMantle(MantleChunk mc, CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < 256; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + MatterCavern cavern = mc.get(rx, yy, rz, MatterCavern.class); + if (cavern != null) { + if (rz < 15 && mc.get(rx, yy, rz + 1, MatterCavern.class) == null) { + walls.put(rx, yy, rz + 1, cavern); + } + if (rx < 15 && mc.get(rx + 1, yy, rz, MatterCavern.class) == null) { + walls.put(rx + 1, yy, rz, cavern); + } + if (rz > 0 && mc.get(rx, yy, rz - 1, MatterCavern.class) == null) { + walls.put(rx, yy, rz - 1, cavern); + } + if (rx > 0 && mc.get(rx - 1, yy, rz, MatterCavern.class) == null) { + walls.put(rx - 1, yy, rz, cavern); + } + } + yy = columnMask.nextSetBit(yy + 1); + } + } + } + + private void addCrossChunkBoundaryWalls( + Mantle mantle, + MantleChunk mc, + CarveWallBuffer walls, + CarveColumnMask[] boundaryMasks, + int chunkX, + int chunkZ, + int[] surfaceHeights + ) { + int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int maxSurfaceY = 0; + for (int index = 0; index < surfaceHeights.length; index++) { + if (surfaceHeights[index] > maxSurfaceY) { + maxSurfaceY = surfaceHeights[index]; + } + } + int maxY = Math.min(getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight() - 1, maxSurfaceY + 1); + if (maxY < 1) { + return; + } + + MantleChunk west = existingMantleChunk(mantle, chunkX - 1, chunkZ); + MantleChunk east = existingMantleChunk(mantle, chunkX + 1, chunkZ); + MantleChunk north = existingMantleChunk(mantle, chunkX, chunkZ - 1); + MantleChunk south = existingMantleChunk(mantle, chunkX, chunkZ + 1); + if (west == null && east == null && north == null && south == null) { + return; + } + + for (int yy = 1; yy <= maxY; yy++) { + for (int offset = 0; offset < 16; offset++) { + if (west != null) { + tryAddBoundaryWall(mc, west, walls, boundaryMasks, 0, yy, offset, 15, offset); + } + if (east != null) { + tryAddBoundaryWall(mc, east, walls, boundaryMasks, 15, yy, offset, 0, offset); + } + if (north != null) { + tryAddBoundaryWall(mc, north, walls, boundaryMasks, offset, yy, 0, offset, 15); + } + if (south != null) { + tryAddBoundaryWall(mc, south, walls, boundaryMasks, offset, yy, 15, offset, 0); + } + } + } + } + + private void tryAddBoundaryWall( + MantleChunk mc, + MantleChunk neighborChunk, + CarveWallBuffer walls, + CarveColumnMask[] boundaryMasks, + int localX, + int yy, + int localZ, + int neighborX, + int neighborZ + ) { + if (mc.get(localX, yy, localZ, MatterCavern.class) != null) { + return; + } + + MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class); + if (neighbor == null) { + return; + } + + walls.put(localX, yy, localZ, neighbor); + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + boundaryMasks[columnIndex].add(yy); + } + + private MantleChunk existingMantleChunk(Mantle mantle, int chunkX, int chunkZ) { + TectonicPlate plate = mantle.getLoadedRegions().get(Mantle.key(chunkX >> 5, chunkZ >> 5)); + if (plate == null || plate.isClosed()) { + return null; + } + return plate.get(chunkX & 31, chunkZ & 31); + } + + private void processColumnFromMask( + Hunk output, + MantleChunk mc, + Mantle mantle, + CarveColumnMask columnMask, + int columnIndex, + int chunkX, + int chunkZ, + IrisDimensionCarvingResolver.State resolverState, + Long2ObjectOpenHashMap caveBiomeCache, + Map customBiomeCache + ) { + if (columnMask == null || columnMask.isEmpty()) { + return; + } + + int firstHeight = columnMask.nextSetBit(0); + if (firstHeight < 0) { + return; + } + + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int rz = columnIndex & 15; + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + CaveZone zone = new CaveZone(); + zone.setFloor(firstHeight); + int buf = firstHeight - 1; + int y = firstHeight; + + while (y >= 0) { + if (y <= getEngine().getHeight()) { + if (y == buf + 1) { + buf = y; + zone.ceiling = buf; + } else { + if (zone.isValid(getEngine())) { + processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache); + } + zone = new CaveZone(); + zone.setFloor(y); + buf = y; + } + } + + y = columnMask.nextSetBit(y + 1); + } + + if (zone.isValid(getEngine())) { + processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache); + } + } + + private void processBoundaryColumnFromMask( + Hunk output, + CarveColumnMask boundaryMask, + CarveWallBuffer walls, + int columnIndex, + int chunkX, + int chunkZ, + IrisDimensionCarvingResolver.State resolverState, + Long2ObjectOpenHashMap caveBiomeCache, + Map customBiomeCache + ) { + int firstHeight = boundaryMask.nextSetBit(0); + if (firstHeight < 0) { + return; + } + + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int rz = columnIndex & 15; + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int zoneFloor = firstHeight; + int zoneCeiling = firstHeight; + int y = boundaryMask.nextSetBit(firstHeight + 1); + + while (y >= 0) { + if (y == zoneCeiling + 1) { + zoneCeiling = y; + } else { + paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, resolverState, caveBiomeCache, customBiomeCache); + zoneFloor = y; + zoneCeiling = y; + } + y = boundaryMask.nextSetBit(y + 1); + } + + paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, resolverState, caveBiomeCache, customBiomeCache); + } + + private void paintBoundaryZone( + Hunk output, + CarveWallBuffer walls, + int rx, + int rz, + int worldX, + int worldZ, + int zoneFloor, + int zoneCeiling, + IrisDimensionCarvingResolver.State resolverState, + Long2ObjectOpenHashMap caveBiomeCache, + Map customBiomeCache + ) { + IrisBiome floorBiome = resolveCaveBoundaryBiome( + walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, + resolverState, caveBiomeCache, customBiomeCache); + IrisBiome ceilingBiome = resolveCaveBoundaryBiome( + walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, + resolverState, caveBiomeCache, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } + + if (floorBiome != null) { + KList floorLayers = floorBiome.generateLayers( + getDimension(), worldX, worldZ, rng, 3, zoneFloor, getData(), getComplex()); + for (int i = 0; i < zoneFloor - 1; i++) { + if (!floorLayers.hasIndex(i)) { + break; + } + int floorY = zoneFloor - i - 1; + if (floorY < 0) { + break; + } + PlatformBlockState existing = output.getRaw(rx, floorY, rz); + PlatformBlockState layer = floorLayers.get(i); + if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, floorY, rz, layer)) { + continue; + } + if (B.isOre(existing)) { + output.setRaw(rx, floorY, rz, B.toDeepSlateOre(existing, layer)); + continue; + } + output.setRaw(rx, floorY, rz, layer); + } + } + + if (ceilingBiome != null) { + int worldMaxY = getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight(); + KList ceilingLayers = ceilingBiome.generateCeilingLayers( + getDimension(), worldX, worldZ, rng, 3, zoneCeiling, getData(), getComplex()); + for (int i = 0; i < ceilingLayers.size(); i++) { + int ceilingY = zoneCeiling + i + 1; + if (ceilingY >= worldMaxY) { + break; + } + PlatformBlockState existing = output.getRaw(rx, ceilingY, rz); + if (!B.isSolid(existing)) { + continue; + } + PlatformBlockState layer = ceilingLayers.get(i); + if (B.isOre(existing)) { + output.setRaw(rx, ceilingY, rz, B.toDeepSlateOre(existing, layer)); + continue; + } + output.setRaw(rx, ceilingY, rz, layer); + } + } + } + + /** + * 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt). + * Deterministic per seed and position, thread-order independent, allocation free. + */ + private boolean markerRoll(int x, int y, int z, long salt) { + long h = (getEngine().getSeedManager().getCarve() + salt) ^ BlockPosition.toLong(x, y, z); + h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; + h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; + h ^= h >>> 31; + return (h & 15L) == 0L; + } + + private void processZone(Hunk output, MantleChunk mc, Mantle mantle, CaveZone zone, int rx, int rz, int xx, int zz, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { + int maxY = output.getHeight(); + + if (zone.ceiling + 1 < maxY && B.isDecorant(output.getRaw(rx, zone.ceiling + 1, rz))) { + output.setRaw(rx, zone.ceiling + 1, rz, AIR); + } + + if (B.isDecorant(output.getRaw(rx, zone.ceiling, rz))) { + output.setRaw(rx, zone.ceiling, rz, AIR); + } + + // Seed-derived and position-keyed, never Math.random(): these markers persist into the + // mantle and drive cave spawning, so the same seed must stamp the same markers on + // every run and every platform. Inline mix, no allocation on this hot path. + if (markerRoll(xx, zone.ceiling, zz, 0x9E3779B97F4A7C15L)) { + mantle.set(xx, zone.ceiling, zz, MarkerMatter.CAVE_CEILING); + } + + if (markerRoll(xx, zone.floor, zz, 0xC2B2AE3D27D4EB4FL)) { + mantle.set(xx, zone.floor, zz, MarkerMatter.CAVE_FLOOR); + } + + IrisBiome floorBiome = resolveCaveBoundaryBiome(mc, rx, zone.floor, rz, xx, zz, resolverState, caveBiomeCache, customBiomeCache); + IrisBiome ceilingBiome = resolveCaveBoundaryBiome(mc, rx, zone.ceiling, rz, xx, zz, resolverState, caveBiomeCache, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } + + if (floorBiome != null) { + KList floorBlocks = floorBiome.generateLayers(getDimension(), xx, zz, rng, 3, zone.floor, getData(), getComplex()); + for (int i = 0; i < zone.floor - 1; i++) { + if (!floorBlocks.hasIndex(i)) { + break; + } + int y = zone.floor - i - 1; + PlatformBlockState block = floorBlocks.get(i); + PlatformBlockState existing = output.getRaw(rx, y, rz); + if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, block)) { + continue; + } + if (B.isOre(existing)) { + output.setRaw(rx, y, rz, B.toDeepSlateOre(existing, block)); + continue; + } + output.setRaw(rx, y, rz, block); + } + } + + if (ceilingBiome != null) { + KList ceilingBlocks = ceilingBiome.generateCeilingLayers(getDimension(), xx, zz, rng, 3, zone.ceiling, getData(), getComplex()); + for (int i = 0; i < ceilingBlocks.size(); i++) { + int cy = zone.ceiling + i + 1; + if (cy >= maxY) { + break; + } + PlatformBlockState block = ceilingBlocks.get(i); + PlatformBlockState existing = output.getRaw(rx, cy, rz); + if (!B.isSolid(existing)) { + continue; + } + if (B.isOre(existing)) { + output.setRaw(rx, cy, rz, B.toDeepSlateOre(existing, block)); + continue; + } + output.setRaw(rx, cy, rz, block); + } + } + + IrisDecorator[] surfaceDecorators = floorBiome == null + ? new IrisDecorator[0] + : floorBiome.getDecoratorBucket(IrisDecorationPart.NONE); + if (surfaceDecorators.length > 0 && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { + decorant.getSurfaceDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); + } + + IrisDecorator[] ceilingDecorators = ceilingBiome == null + ? new IrisDecorator[0] + : ceilingBiome.getDecoratorBucket(IrisDecorationPart.CEILING); + if (ceilingDecorators.length > 0 && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { + decorant.getCeilingDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); + } + } + + IrisBiome resolveCaveBoundaryBiome(MantleChunk mantleChunk, int x, int y, int z, int worldX, int worldZ, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { + MatterCavern cavern = dataIfPresent(mantleChunk, x, y, z, MatterCavern.class); + return resolveCaveBoundaryBiome( + cavern, worldX, y, worldZ, resolverState, caveBiomeCache, customBiomeCache); + } + + private static T dataIfPresent(MantleChunk mantleChunk, int x, int y, int z, Class type) { + int section = y >> 4; + if (y < 0 || !mantleChunk.exists(section)) { + return null; + } + Matter matter = mantleChunk.get(section); + if (matter == null || !matter.hasSlice(type)) { + return null; + } + return matter.getSlice(type).get(x & 15, y & 15, z & 15); + } + + IrisBiome resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { + if (cavern != null && !cavern.getCustomBiome().isEmpty()) { + return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); + } + return resolveCaveBiome(caveBiomeCache, worldX, y, worldZ, resolverState); + } + + static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, PlatformBlockState layer) { + return !isGravityAffected(layer) || y > 0 && B.isSolid(output.getRaw(x, y - 1, z)); + } + + static boolean hasStableCaveFloorSupport(Hunk output, int x, int floorY, int z) { + if (floorY <= 0) { + return false; + } + PlatformBlockState support = output.getRaw(x, floorY - 1, z); + if (!B.isSolid(support)) { + return false; + } + return !isGravityAffected(support) || floorY > 1 && B.isSolid(output.getRaw(x, floorY - 2, z)); + } + + static boolean isGravityAffected(PlatformBlockState state) { + if (state == null) { + return false; + } + String key = IrisProceduralBlocks.materialKey(state); + return key.equals("minecraft:sand") + || key.equals("minecraft:red_sand") + || key.equals("minecraft:gravel") + || key.equals("minecraft:suspicious_sand") + || key.equals("minecraft:suspicious_gravel") + || key.endsWith("_concrete_powder"); + } + + private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) { + IrisBiome center = sampleCaveBiome(caveBiomeCache, x, y, z, resolverState); + if (center == null) { + return null; + } + + IrisBiome xPos = sampleCaveBiome(caveBiomeCache, x + CAVE_BIOME_BLEND_RADIUS, y, z, resolverState); + IrisBiome xNeg = sampleCaveBiome(caveBiomeCache, x - CAVE_BIOME_BLEND_RADIUS, y, z, resolverState); + IrisBiome zPos = sampleCaveBiome(caveBiomeCache, x, y, z + CAVE_BIOME_BLEND_RADIUS, resolverState); + IrisBiome zNeg = sampleCaveBiome(caveBiomeCache, x, y, z - CAVE_BIOME_BLEND_RADIUS, resolverState); + + if (xPos == center && xNeg == center && zPos == center && zNeg == center) { + return center; + } + + int roll = Math.floorMod(rng.nextParallelRNG(BlockPosition.toLong(x, y, z)).nextInt(), CAVE_BIOME_BLEND_TOTAL_WEIGHT); + if (roll < CAVE_BIOME_BLEND_CENTER_WEIGHT) { + return center; + } + roll -= CAVE_BIOME_BLEND_CENTER_WEIGHT; + if (roll == 0) { + return xPos != null ? xPos : center; + } + if (roll == 1) { + return xNeg != null ? xNeg : center; + } + if (roll == 2) { + return zPos != null ? zPos : center; + } + return zNeg != null ? zNeg : center; + } + + private IrisBiome sampleCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) { + long key = BlockPosition.toLong(x, y, z); + IrisBiome cachedBiome = caveBiomeCache.get(key); + if (cachedBiome != null) { + return cachedBiome; + } + + IrisBiome resolvedBiome = getEngine().getCaveBiome(x, y, z, resolverState); + if (resolvedBiome != null) { + caveBiomeCache.put(key, resolvedBiome); + } + return resolvedBiome; + } + + private IrisBiome resolveCustomBiome(Map customBiomeCache, String customBiome) { + if (customBiomeCache.containsKey(customBiome)) { + return customBiomeCache.get(customBiome); + } + + IrisBiome loaded = getEngine().getData().getBiomeLoader().load(customBiome); + customBiomeCache.put(customBiome, loaded); + return loaded; + } + + @Data + public static class CaveZone { + private int ceiling = -1; + private int floor = -1; + + public int airThickness() { + return (ceiling - floor) - 1; + } + + public boolean isValid(Engine engine) { + return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= engine.getHeight() && airThickness() > 0; + } + + public String toString() { + return floor + "-" + ceiling; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java new file mode 100644 index 000000000..a2e51e88d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java @@ -0,0 +1,277 @@ +/* + * 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.modifier; + +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +final class IrisCarveScratch { + final CarveColumnMask[] columnMasks = new CarveColumnMask[256]; + final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256]; + final int[] surfaceHeights = new int[256]; + final CarveWallBuffer walls = new CarveWallBuffer(512); + final Map customBiomeCache = new HashMap<>(); + int[] upperSurfaceHeights; + boolean customCaveBiomePresent; + + IrisCarveScratch() { + for (int index = 0; index < columnMasks.length; index++) { + columnMasks[index] = new CarveColumnMask(); + boundaryMasks[index] = new CarveColumnMask(); + } + } + + int[] getOrCreateUpperSurfaceHeights() { + if (upperSurfaceHeights == null) { + upperSurfaceHeights = new int[256]; + } + return upperSurfaceHeights; + } + + void reset() { + for (int index = 0; index < columnMasks.length; index++) { + columnMasks[index].clear(); + boundaryMasks[index].clear(); + } + walls.clear(); + customBiomeCache.clear(); + customCaveBiomePresent = false; + } +} + +final class CarveColumnMask { + private long[] words = new long[8]; + private int maxWord = -1; + + void add(int y) { + if (y < 0) { + return; + } + + int wordIndex = y >> 6; + if (wordIndex >= words.length) { + words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1)); + } + + words[wordIndex] |= 1L << (y & 63); + if (wordIndex > maxWord) { + maxWord = wordIndex; + } + } + + int nextSetBit(int fromBit) { + if (maxWord < 0) { + return -1; + } + + int startBit = Math.max(0, fromBit); + int wordIndex = startBit >> 6; + if (wordIndex > maxWord) { + return -1; + } + + long word = words[wordIndex] & (-1L << (startBit & 63)); + while (true) { + if (word != 0L) { + return (wordIndex << 6) + Long.numberOfTrailingZeros(word); + } + + wordIndex++; + if (wordIndex > maxWord) { + return -1; + } + word = words[wordIndex]; + } + } + + boolean isEmpty() { + return maxWord < 0; + } + + boolean contains(int y) { + if (y < 0) { + return false; + } + + int wordIndex = y >> 6; + if (wordIndex > maxWord) { + return false; + } + + return (words[wordIndex] & (1L << (y & 63))) != 0L; + } + + void clear() { + if (maxWord < 0) { + return; + } + + for (int index = 0; index <= maxWord; index++) { + words[index] = 0L; + } + maxWord = -1; + } +} + +final class CarveWallBuffer { + private static final int EMPTY_KEY = -1; + private static final double LOAD_FACTOR = 0.75D; + + private int[] keys; + private MatterCavern[] values; + private int mask; + private int resizeAt; + private int size; + + CarveWallBuffer(int expectedSize) { + int capacity = 1; + int minimumCapacity = Math.max(8, expectedSize); + while (capacity < minimumCapacity) { + capacity <<= 1; + } + + keys = new int[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new MatterCavern[capacity]; + mask = capacity - 1; + resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); + } + + void put(int x, int y, int z, MatterCavern value) { + int key = pack(x, y, z); + int index = mix(key) & mask; + + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + keys[index] = key; + values[index] = value; + size++; + if (size >= resizeAt) { + resize(); + } + return; + } + + if (existingKey == key) { + values[index] = value; + return; + } + + index = (index + 1) & mask; + } + } + + MatterCavern get(int x, int y, int z) { + int key = pack(x, y, z); + int index = mix(key) & mask; + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + return null; + } + if (existingKey == key) { + return values[index]; + } + index = (index + 1) & mask; + } + } + + void forEach(Consumer consumer) { + for (int index = 0; index < keys.length; index++) { + int key = keys[index]; + if (key == EMPTY_KEY) { + continue; + } + + MatterCavern cavern = values[index]; + if (cavern != null) { + consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern); + } + } + } + + void clear() { + Arrays.fill(keys, EMPTY_KEY); + Arrays.fill(values, null); + size = 0; + } + + private void resize() { + int[] oldKeys = keys; + MatterCavern[] oldValues = values; + int nextCapacity = oldKeys.length << 1; + keys = new int[nextCapacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new MatterCavern[nextCapacity]; + mask = nextCapacity - 1; + resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); + size = 0; + + for (int index = 0; index < oldKeys.length; index++) { + int key = oldKeys[index]; + MatterCavern value = oldValues[index]; + if (key != EMPTY_KEY && value != null) { + reinsert(key, value); + } + } + } + + private void reinsert(int key, MatterCavern value) { + int index = mix(key) & mask; + while (keys[index] != EMPTY_KEY) { + index = (index + 1) & mask; + } + + keys[index] = key; + values[index] = value; + size++; + } + + private int pack(int x, int y, int z) { + return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15); + } + + private int unpackX(int key) { + return PowerOfTwoCoordinates.unpackLocal16X(key & 255); + } + + private int unpackY(int key) { + return key >> 8; + } + + private int unpackZ(int key) { + return PowerOfTwoCoordinates.unpackLocal16Z(key); + } + + private int mix(int value) { + int mixed = value * 0x9E3779B9; + return mixed ^ (mixed >>> 16); + } + + @FunctionalInterface + interface Consumer { + void accept(int x, int y, int z, MatterCavern cavern); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java new file mode 100644 index 000000000..328fea675 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java @@ -0,0 +1,64 @@ +package art.arcane.iris.engine.modifier; + +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.parallel.BurstExecutor; +import art.arcane.iris.util.common.parallel.MultiBurst; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.mantle.flag.MantleFlag; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; + +public class IrisCustomModifier extends EngineAssignedModifier { + public IrisCustomModifier(Engine engine) { + super(engine, "Custom"); + } + + @Override + public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + MantleChunk mc = getEngine().getMantle().getMantle().getChunk(x >> 4, z >> 4); + if (!mc.isFlagged(MantleFlag.CUSTOM_ACTIVE)) { + return; + } + mc.use(); + + BurstExecutor burst = MultiBurst.burst.burst(output.getHeight()); + burst.setMulticore(multicore); + // complete() must run before release() even when queueing throws — detached burst + // tasks must never write into a released chunk, and a lost permit wedges close(). + try { + for (int y = 0; y < output.getHeight(); y++) { + int finalY = y; + burst.queue(() -> { + for (int rX = 0; rX < output.getWidth(); rX++) { + for (int rZ = 0; rZ < output.getDepth(); rZ++) { + PlatformBlockState b = output.get(rX, finalY, rZ); + if (b == null || !b.isCustom()) { + continue; + } + String placementKey = b.deferredPlacementKey(); + PlatformBlockState baseState = b.placementBaseState(); + if (placementKey == null || baseState == null) { + continue; + } + + mc.getOrCreate(finalY >> 4) + .slice(Identifier.class) + .set(rX, finalY & 15, rZ, Identifier.fromString(placementKey)); + output.set(rX, finalY, rZ, baseState); + } + } + }); + } + } finally { + try { + burst.complete(); + } finally { + mc.release(); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java new file mode 100644 index 000000000..796c5d103 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java @@ -0,0 +1,357 @@ +/* + * 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.modifier; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositHeightDistribution; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositPlacementScope; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.volmlib.util.data.HeightMap; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.iris.util.common.parallel.BurstExecutor; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; + +public class IrisDepositModifier extends EngineAssignedModifier { + private final RNG rng; + + public IrisDepositModifier(Engine engine) { + super(engine, "Deposit"); + rng = new RNG(getEngine().getSeedManager().getDeposit()); + } + + @Override + public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + generateDeposits(output, Math.floorDiv(x, 16), Math.floorDiv(z, 16), multicore, context); + getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); + } + + public void generateDeposits(Hunk terrain, int x, int z, boolean multicore, ChunkContext context) { + IrisRegion region = context.getRegion().get(7, 7); + IrisBiome biome = context.getBiome().get(7, 7); + BurstExecutor burst = burst().burst(multicore); + + long seed = x * 341873128712L + z * 132897987541L; + long mask = 0; + MantleChunk chunk = getEngine().getMantle().getMantle().getChunk(x, z).use(); + try { + for (IrisDepositGenerator k : getDimension().getDeposits()) { + long finalSeed = seed * ++mask; + burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); + } + + for (IrisDepositGenerator k : region.getDeposits()) { + long finalSeed = seed * ++mask; + burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); + } + + for (IrisDepositGenerator k : biome.getDeposits()) { + long finalSeed = seed * ++mask; + burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); + } + } finally { + // complete() must run before release() even when queueing throws — already + // submitted burst tasks must never write into a released chunk. + try { + burst.complete(); + } finally { + chunk.release(); + } + } + } + + public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, ChunkContext context) { + generate(k, chunk, data, rng, cx, cz, safe, null, context); + } + + public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) { + IrisDimensionCarvingResolver.State carvingState = new IrisDimensionCarvingResolver.State(); + if (k.getSpawnChance() < rng.d()) + return; + + for (int l = 0; l < rng.i(k.getMinPerChunk(), k.getMaxPerChunk() + 1); l++) { + if (k.getPerClumpSpawnChance() < rng.d()) + continue; + + IrisObject clump = k.getClump(getEngine(), rng, getData()); + + int dim = clump.getW(); + int min = dim / 2; + int max = (int) (16D - dim / 2D); + + if (min > max || min < 0 || max > 15) { + min = 6; + max = 9; + } + + int x = rng.i(min, max + 1); + int z = rng.i(min, max + 1); + int terrainSurface = getDepositTerrainSurface(cx, cz, x, z, he, context); + int height = k.getPlacementScope() == IrisDepositPlacementScope.TERRAIN + ? depositSurfaceLimit(terrainSurface, k.getSurfaceClearance()) + : getEngine().getHeight() - 1; + + if (height < 0) { + continue; + } + + int y = sampleHeight( + k.getHeightDistribution(), rng, k.getMinHeight(), k.getMaxHeight(), + Math.min(height, getEngine().getHeight() - 1)); + if (y == Integer.MIN_VALUE) { + continue; + } + + boolean clippedHeight = k.getHeightDistribution() == IrisDepositHeightDistribution.CLIPPED_UNIFORM; + if (clippedHeight && y > height - 2) + continue; + + int biomeY = Math.max(0, Math.min(getEngine().getHeight() - 1, y)); + boolean oreDeposit = k.isOre(getData()); + IrisBiome surfaceBiome = context.getBiome().get(x, z); + IrisBiome depositBiome = oreDeposit || k.usesCaveBiomeFilter() + ? getEngine().getCaveBiome( + (cx << 4) + x, biomeY, (cz << 4) + z, carvingState) + : null; + if (!k.matchesBiome(surfaceBiome, depositBiome)) { + continue; + } + + if (oreDeposit) { + if (depositBiome != null) { + double frequencyMultiplier = depositBiome.getOreDepositFrequencyMultiplier(); + if (frequencyMultiplier < 1D + && !passesOreFrequency(frequencyMultiplier, rng.d())) { + continue; + } + + double sizeMultiplier = depositBiome.getOreDepositSizeMultiplier(); + if (sizeMultiplier != 1D) { + IrisObject scaledClump = k.getClump(getEngine(), rng, getData(), sizeMultiplier); + int scaledDimension = scaledClump.getW(); + x = clampDepositCenter(x, scaledDimension, 16); + if (clippedHeight) { + y = clampDepositCenter(y, scaledDimension, getEngine().getHeight()); + } + z = clampDepositCenter(z, scaledDimension, 16); + clump = scaledClump; + } + } + } + + IrisDimension dimension = getDimension(); + + for (art.arcane.iris.util.common.math.IrisBlockVector j : clump.getBlocks().keys()) { + int nx = j.getBlockX() + x; + int ny = j.getBlockY() + y; + int nz = j.getBlockZ() + z; + + if (nx > 15 || nx < 0 || ny >= getEngine().getHeight() || ny < 0 || nz < 0 || nz > 15) { + continue; + } + int columnSurface = getDepositTerrainSurface(cx, cz, nx, nz, he, context); + if (!placementSurfaceAllows( + k.getPlacementScope(), ny, columnSurface, k.getSurfaceClearance())) { + continue; + } + + PlatformBlockState current = data.get(nx, ny, nz); + if (!canReplaceDepositTarget(current)) { + continue; + } + if (!k.canReplace(current)) { + continue; + } + if (!k.isReplaceBedrock() && IrisProceduralBlocks.materialKey(current).equals("minecraft:bedrock")) { + continue; + } + if (shouldDiscardExposed( + k.getDiscardChanceOnAirExposure(), rng.d(), isAdjacentToAir(data, nx, ny, nz))) { + continue; + } + + if (chunk.get(nx, ny, nz, MatterCavern.class) == null) { + PlatformBlockState ore = clump.getBlocks().get(j); + PlatformBlockState remapped = resolveDepositVariant( + cx, cz, nx, ny, nz, ore, dimension, context, carvingState); + PlatformBlockState finalBlock = remapped != null + ? remapped + : B.toDeepSlateOre(current, ore); + data.set(nx, ny, nz, finalBlock); + } + } + } + } + + private int getDepositTerrainSurface( + int cx, int cz, int localX, int localZ, HeightMap heightMap, + ChunkContext context) { + return heightMap != null + ? heightMap.getHeight((cx << 4) + localX, (cz << 4) + localZ) + : context.getRoundedHeight(localX, localZ); + } + + static int depositSurfaceLimit(int surfaceY) { + return depositSurfaceLimit(surfaceY, 7); + } + + static int depositSurfaceLimit(int surfaceY, int surfaceClearance) { + return surfaceY - Math.max(0, surfaceClearance); + } + + static boolean placementSurfaceAllows( + IrisDepositPlacementScope scope, int candidateY, int surfaceY, int surfaceClearance) { + int clearance = Math.max(0, surfaceClearance); + return switch (scope) { + case ABOVE_TERRAIN -> candidateY > surfaceY + clearance; + case FULL_HEIGHT -> true; + case TERRAIN -> candidateY <= surfaceY - clearance; + }; + } + + static int absoluteWorldY(int minHeight, int localY) { + return minHeight + localY; + } + + static boolean canReplaceDepositTarget(PlatformBlockState state) { + return state != null && !state.isAir() && !state.isFluid(); + } + + static int sampleHeight( + IrisDepositHeightDistribution distribution, RNG rng, + int configuredMinimum, int configuredMaximum, int clippedMaximum) { + int minimum = distribution == IrisDepositHeightDistribution.CLIPPED_UNIFORM + ? Math.max(0, configuredMinimum) + : configuredMinimum; + int maximum = distribution == IrisDepositHeightDistribution.CLIPPED_UNIFORM + ? Math.min(clippedMaximum, configuredMaximum) + : configuredMaximum; + if (minimum > maximum) { + return Integer.MIN_VALUE; + } + if (minimum == maximum) { + return minimum; + } + if (distribution != IrisDepositHeightDistribution.TRIANGLE) { + return minimum + rng.nextInt(maximum - minimum + 1); + } + + int span = maximum - minimum; + int lowerHalf = span / 2; + int upperHalf = span - lowerHalf; + return minimum + rng.nextInt(upperHalf + 1) + rng.nextInt(lowerHalf + 1); + } + + static boolean shouldDiscardExposed(double chance, double sample, boolean adjacentToAir) { + return adjacentToAir && chance > 0D && sample < Math.min(1D, chance); + } + + static boolean isAdjacentToAir(Hunk data, int x, int y, int z) { + return isAirAt(data, x - 1, y, z) + || isAirAt(data, x + 1, y, z) + || isAirAt(data, x, y - 1, z) + || isAirAt(data, x, y + 1, z) + || isAirAt(data, x, y, z - 1) + || isAirAt(data, x, y, z + 1); + } + + private static boolean isAirAt(Hunk data, int x, int y, int z) { + if (x < 0 || x >= data.getWidth() + || y < 0 || y >= data.getHeight() + || z < 0 || z >= data.getDepth()) { + return false; + } + PlatformBlockState state = data.getRaw(x, y, z); + return state == null || state.isAir(); + } + + static boolean passesOreFrequency(double multiplier, double sample) { + return multiplier >= 1D || sample < Math.max(0D, multiplier); + } + + static int clampDepositCenter(int center, int dimension, int limit) { + int minimum = dimension / 2; + int maximum = (int) (limit - dimension / 2D); + return Math.max(minimum, Math.min(center, maximum)); + } + + private PlatformBlockState resolveDepositVariant(int cx, int cz, int nx, int localY, int nz, PlatformBlockState ore, IrisDimension dimension, ChunkContext context, IrisDimensionCarvingResolver.State carvingState) { + int worldX = (cx << 4) + nx; + int worldZ = (cz << 4) + nz; + int worldY = absoluteWorldY(getEngine().getMinHeight(), localY); + + IrisBiome biome = getEngine().getCaveBiome(worldX, localY, worldZ, carvingState); + if (biome != null) { + PlatformBlockState match = matchDepositVariant(biome.getDepositVariants(), ore, worldY); + if (match != null) { + return match; + } + } + + IrisRegion region = context.getRegion().get(nx, nz); + if (region != null) { + PlatformBlockState match = matchDepositVariant(region.getDepositVariants(), ore, worldY); + if (match != null) { + return match; + } + } + + if (dimension != null) { + PlatformBlockState match = matchDepositVariant(dimension.getDepositVariants(), ore, worldY); + if (match != null) { + return match; + } + } + + return null; + } + + private PlatformBlockState matchDepositVariant(java.util.List variants, PlatformBlockState ore, int y) { + if (variants == null || variants.isEmpty()) { + return null; + } + + for (IrisDepositVariant variant : variants) { + if (y < variant.getMinHeight() || y > variant.getMaxHeight()) { + continue; + } + + PlatformBlockState swapped = variant.remapOrNull(ore, getData()); + if (swapped != null) { + return swapped; + } + } + + return null; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java new file mode 100644 index 000000000..0b661a9cc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java @@ -0,0 +1,406 @@ +/* + * 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.modifier; + + +import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.decorator.FloatingDecorator; +import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.engine.framework.EngineDecorator; +import art.arcane.iris.engine.object.terrain.floating.FloatingBottomPaletteMode; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; +import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; +import art.arcane.iris.engine.object.placement.IrisSlopeClip; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.MatterBiomeInject; +import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; + +import java.util.IdentityHashMap; + +import static art.arcane.iris.engine.mantle.EngineMantle.AIR; + +public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier { + public static final long FLOATING_BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; + private static final Runnable NOOP_DECORATION_MISS = () -> { + }; + private final RNG rng; + private final EngineDecorator seaSurfaceDecorator; + + private static KList generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { + if (entry == null || entry.getBottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.getBottomPalette() == null || entry.getBottomPalette().isEmpty()) { + return null; + } + return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex); + } + + private static KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) { + KList generated = new KList<>(); + if (layers == null || layers.isEmpty() || maxDepth <= 0) { + return generated; + } + + int generatorSeed = 7235; + for (int i = 0; i < layers.size(); i++) { + IrisBiomePaletteLayer layer = layers.get(i); + CNG heightGenerator = layer.getHeightGenerator(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed), data); + if (heightGenerator == null) { + continue; + } + double layerDepth = heightGenerator.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / layer.getZoom(), wz / layer.getZoom()); + IrisSlopeClip slopeClip = layer.getSlopeCondition(); + + if (slopeClip != null && !slopeClip.isDefault() && complex != null && !slopeClip.isValid(complex.getSlopeStream().get(wx, wz))) { + layerDepth = 0; + } + + if (layerDepth <= 0) { + continue; + } + + for (int j = 0; j < layerDepth; j++) { + if (generated.size() >= maxDepth) { + break; + } + + try { + generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.getZoom(), j, (wz - j) / layer.getZoom(), data)); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + if (generated.size() >= maxDepth) { + break; + } + + if (dimension != null && dimension.isExplodeBiomePalettes()) { + PlatformBlockState barrier = B.getState("minecraft:barrier"); + for (int j = 0; j < dimension.getExplodeBiomePaletteSize(); j++) { + generated.add(barrier); + + if (generated.size() >= maxDepth) { + break; + } + } + } + } + + return generated; + } + + private static boolean usesBottomPalette(IrisFloatingChildBiomes entry) { + FloatingBottomPaletteMode mode = entry == null || entry.getBottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.getBottomPaletteMode(); + return mode != FloatingBottomPaletteMode.DEPTH; + } + + private static int[] bottomDepths(FloatingIslandSample sample, int chunkHeight) { + int[] bottomDepths = new int[sample.solidMask.length]; + for (int i = 0; i < bottomDepths.length; i++) { + bottomDepths[i] = -1; + } + + IdentityHashMap depthByEntry = new IdentityHashMap<>(); + int max = Math.min(sample.topIdx, sample.solidMask.length - 1); + for (int k = 0; k <= max; k++) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunkHeight) { + continue; + } + IrisFloatingChildBiomes entry = sample.entryAt(k); + int depth = depthByEntry.getOrDefault(entry, 0); + bottomDepths[k] = depth; + depthByEntry.put(entry, depth + 1); + } + + return bottomDepths; + } + + private static PlatformBlockState selectPaletteBlock(IrisFloatingChildBiomes entry, KList topBlocks, KList bottomBlocks, int topDepth, int bottomDepth, PlatformBlockState fallbackSolid) { + FloatingBottomPaletteMode mode = entry == null || entry.getBottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.getBottomPaletteMode(); + if (mode == FloatingBottomPaletteMode.MIRROR_TOP) { + return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth), fallbackSolid); + } + if (mode == FloatingBottomPaletteMode.CUSTOM && bottomDepth < topDepth) { + if (bottomBlocks != null && !bottomBlocks.isEmpty()) { + return paletteBlock(bottomBlocks, bottomDepth, fallbackSolid); + } + return paletteBlock(topBlocks, bottomDepth, fallbackSolid); + } + return paletteBlock(topBlocks, topDepth, fallbackSolid); + } + + private static PlatformBlockState paletteBlock(KList blocks, int depth, PlatformBlockState fallbackSolid) { + if (blocks == null || blocks.isEmpty()) { + return fallbackSolid; + } + PlatformBlockState block = blocks.hasIndex(depth) ? blocks.get(depth) : blocks.getLast(); + return block == null ? fallbackSolid : block; + } + + private PaletteContext createPaletteContext(IrisBiome parent, IrisFloatingChildBiomes entry, IrisDimension dimension, int wx, int wz, long colSeed, int paletteDepth, IrisData data, IrisComplex complex) { + IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); + int entrySeed = entry == null || entry.getBiome() == null ? 0 : entry.getBiome().hashCode(); + RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed)); + KList topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); + if (topBlocks == null || topBlocks.isEmpty()) { + topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); + } + KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex); + return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone")); + } + + private static final class PaletteContext { + private final KList topBlocks; + private final KList bottomBlocks; + private final PlatformBlockState fallbackSolid; + + private PaletteContext(KList topBlocks, KList bottomBlocks, PlatformBlockState fallbackSolid) { + this.topBlocks = topBlocks; + this.bottomBlocks = bottomBlocks; + this.fallbackSolid = fallbackSolid; + } + } + + public IrisFloatingChildBiomeModifier(Engine engine) { + super(engine, "FloatingChildBiomes"); + rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); + seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); + } + + @Override + public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + int chunkHeight = output.getHeight(); + IrisData data = getData(); + IrisDimension dimension = getDimension(); + IrisComplex complex = getComplex(); + long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; + FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); + FloatingIslandSample.clearChunkMemo(); + + for (int xf = 0; xf < 16; xf++) { + for (int zf = 0; zf < 16; zf++) { + int wx = x + xf; + int wz = z + zf; + IrisBiome parent = boundarySampler.parent(wx, wz); + if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) { + continue; + } + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, getEngine(), boundarySampler); + if (sample == null) { + continue; + } + + long colSeed = FloatingIslandSample.columnSeed(baseSeed, wx, wz); + int paletteDepth = Math.max(4, sample.solidCount + 4); + IdentityHashMap paletteContexts = new IdentityHashMap<>(); + IdentityHashMap topDepthByEntry = new IdentityHashMap<>(); + int[] bottomDepths = bottomDepths(sample, chunkHeight); + for (int k = sample.topIdx; k >= 0; k--) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunkHeight) { + continue; + } + IrisFloatingChildBiomes entry = sample.entryAt(k); + PaletteContext paletteContext = paletteContexts.get(entry); + if (paletteContext == null) { + paletteContext = createPaletteContext(parent, entry, dimension, wx, wz, colSeed, paletteDepth, data, complex); + paletteContexts.put(entry, paletteContext); + } + int depth = topDepthByEntry.getOrDefault(entry, 0); + int bottomDepth = bottomDepths == null || bottomDepths[k] < 0 ? depth : bottomDepths[k]; + PlatformBlockState block = selectPaletteBlock(entry, paletteContext.topBlocks, paletteContext.bottomBlocks, depth, bottomDepth, paletteContext.fallbackSolid); + if (block != null) { + output.set(xf, y, zf, block); + } + topDepthByEntry.put(entry, depth + 1); + } + + IrisFloatingChildBiomes entry = sample.entry; + Integer localFluidHeight = entry.getLocalFluidHeight(); + if (localFluidHeight != null && localFluidHeight > 0) { + PlatformBlockState fluid = B.getStateOrNull(entry.getFluidBlock()); + if (fluid == null) { + fluid = B.getState("minecraft:water"); + } + int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); + for (int k = 1; k <= fluidCap; k++) { + if (sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunkHeight) { + continue; + } + boolean hasSolidBelow = false; + for (int kb = k - 1; kb >= 0; kb--) { + if (sample.solidMask[kb]) { + hasSolidBelow = true; + break; + } + } + if (hasSolidBelow) { + output.set(xf, y, zf, fluid); + } + } + } + + writeIslandSkyBiomes(parent, wx, wz, sample, chunkHeight, data); + } + } + + getEngine().getMetrics().getTerrain().put(p.getMilliseconds()); + } + + public void decorateColumns(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + int chunkHeight = output.getHeight(); + IrisData data = getData(); + IrisComplex complex = getComplex(); + long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; + FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); + + for (int xf = 0; xf < 16; xf++) { + for (int zf = 0; zf < 16; zf++) { + int wx = x + xf; + int wz = z + zf; + IrisBiome parent = boundarySampler.parent(wx, wz); + if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) { + continue; + } + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, getEngine(), boundarySampler); + if (sample == null) { + continue; + } + IrisFloatingChildBiomes entry = sample.entry; + IrisBiome target = entry.getRealBiome(parent, data); + + if (!entry.isInheritDecorators() || target == null) { + continue; + } + + int topY = sample.topY(); + int max = Math.max(1, chunkHeight - topY); + if (topY + 1 < chunkHeight) { + PlatformBlockState above = output.get(xf, topY + 1, zf); + if (above == null || above.isAir()) { + try { + RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(baseSeed, wx, wz)); + FloatingDecorator.decorateColumn(getEngine(), target, IrisDecorationPart.NONE, xf, zf, wx, wz, topY, max, output, colRng, NOOP_DECORATION_MISS); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + + Integer localFluidHeight = entry.getLocalFluidHeight(); + if (localFluidHeight != null && localFluidHeight > 0) { + int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); + int fluidTopY = -1; + for (int k = 1; k <= fluidCap; k++) { + if (sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunkHeight) { + continue; + } + boolean hasSolidBelow = false; + for (int kb = k - 1; kb >= 0; kb--) { + if (sample.solidMask[kb]) { + hasSolidBelow = true; + break; + } + } + if (hasSolidBelow && y > fluidTopY) { + fluidTopY = y; + } + } + if (fluidTopY > 0 && fluidTopY + 1 < chunkHeight && B.isAir(output.get(xf, fluidTopY + 1, zf))) { + try { + seaSurfaceDecorator.decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, output, target, fluidTopY, chunkHeight); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + } + } + } + + private void writeIslandSkyBiomes(IrisBiome parent, int wx, int wz, FloatingIslandSample sample, int chunkHeight, IrisData data) { + try { + IdentityHashMap matterByEntry = new IdentityHashMap<>(); + for (int k = 0; k <= sample.topIdx; k++) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunkHeight) { + continue; + } + IrisFloatingChildBiomes entry = sample.entryAt(k); + MatterBiomeInject matter = matterByEntry.get(entry); + if (matter == null) { + IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); + if (target == null) { + continue; + } + matter = createSkyBiomeMatter(target, wx, wz); + matterByEntry.put(entry, matter); + } + getEngine().getMantle().getMantle().set(wx, y, wz, matter); + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + private MatterBiomeInject createSkyBiomeMatter(IrisBiome target, int wx, int wz) { + if (target.isCustom()) { + IrisBiomeCustom custom = target.getCustomBiome(rng, getEngine(), wx, 0, wz); + return BiomeInjectMatter.get(IrisPlatforms.get().biomeWriter().biomeIdFor(getDimension().getLoadKey() + ":" + custom.getId())); + } + + return BiomeInjectMatter.get(IrisPlatforms.get().biomeWriter().biomeIdFor(target.getSkyBiomeKey(rng, getEngine(), wx, 0, wz))); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java new file mode 100644 index 000000000..163cda7dc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java @@ -0,0 +1,200 @@ +/* + * 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.modifier; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.iris.util.common.parallel.BurstExecutor; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.PlatformBlockState; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +public class IrisPerfectionModifier extends EngineAssignedModifier { + private static final class States { + private static final PlatformBlockState AIR = B.getState("AIR"); + private static final PlatformBlockState WATER = B.getState("WATER"); + private static final Map ORE_BASES = buildOreBases(); + } + + public IrisPerfectionModifier(Engine engine) { + super(engine, "Perfection"); + } + + private static Map buildOreBases() { + Map map = new HashMap<>(); + PlatformBlockState stone = B.getState("STONE"); + PlatformBlockState deepslate = B.getState("DEEPSLATE"); + PlatformBlockState netherrack = B.getState("NETHERRACK"); + PlatformBlockState blackstone = B.getState("BLACKSTONE"); + map.put("minecraft:coal_ore", stone); + map.put("minecraft:copper_ore", stone); + map.put("minecraft:iron_ore", stone); + map.put("minecraft:gold_ore", stone); + map.put("minecraft:redstone_ore", stone); + map.put("minecraft:lapis_ore", stone); + map.put("minecraft:diamond_ore", stone); + map.put("minecraft:emerald_ore", stone); + map.put("minecraft:deepslate_coal_ore", deepslate); + map.put("minecraft:deepslate_copper_ore", deepslate); + map.put("minecraft:deepslate_iron_ore", deepslate); + map.put("minecraft:deepslate_gold_ore", deepslate); + map.put("minecraft:deepslate_redstone_ore", deepslate); + map.put("minecraft:deepslate_lapis_ore", deepslate); + map.put("minecraft:deepslate_diamond_ore", deepslate); + map.put("minecraft:deepslate_emerald_ore", deepslate); + map.put("minecraft:nether_gold_ore", netherrack); + map.put("minecraft:nether_quartz_ore", netherrack); + map.put("minecraft:ancient_debris", netherrack); + map.put("minecraft:gilded_blackstone", blackstone); + return map; + } + + private static String baseKey(PlatformBlockState state) { + String key = state.key(); + int bracket = key.indexOf('['); + return bracket < 0 ? key : key.substring(0, bracket); + } + + @Override + public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + if (getDimension().isHideOresForHiddenOre()) { + hideOres(output, multicore); + } + AtomicBoolean changed = new AtomicBoolean(true); + BurstExecutor burst = burst().burst(multicore); + while (changed.get()) { + changed.set(false); + for (int i = 0; i < 16; i++) { + int finalI = i; + burst.queue(() -> { + List surfaces = new ArrayList<>(); + List ceilings = new ArrayList<>(); + for (int j = 0; j < 16; j++) { + surfaces.clear(); + ceilings.clear(); + int top = getHeight(output, finalI, j); + boolean inside = true; + surfaces.add(top); + + for (int k = top; k >= 0; k--) { + PlatformBlockState b = output.get(finalI, k, j); + boolean now = b != null && !(B.isAir(b) || B.isFluid(b)); + + if (now != inside) { + inside = now; + + if (inside) { + surfaces.add(k); + } else { + ceilings.add(k + 1); + } + } + } + + for (int k : surfaces) { + PlatformBlockState tip = output.get(finalI, k, j); + + if (tip == null) { + continue; + } + + boolean remove = false; + boolean remove2 = false; + + if (B.isDecorant(tip)) { + PlatformBlockState bel = output.get(finalI, k - 1, j); + + if (bel == null) { + remove = true; + } else if (!B.canPlaceOnto(tip, bel)) { + remove = true; + } else if (IrisProceduralBlocks.hasProperty(bel, "half")) { + PlatformBlockState bb = output.get(finalI, k - 2, j); + if (bb == null || !B.canPlaceOnto(bel, bb)) { + remove = true; + remove2 = true; + } + } + + if (remove) { + changed.set(true); + output.set(finalI, k, j, States.AIR); + + if (remove2) { + output.set(finalI, k - 1, j, States.AIR); + } + } + } + } + } + }); + } + burst.complete(); + } + + getEngine().getMetrics().getPerfection().put(p.getMilliseconds()); + } + + private void hideOres(Hunk output, boolean multicore) { + BurstExecutor burst = burst().burst(multicore); + int height = output.getHeight(); + for (int i = 0; i < 16; i++) { + int finalI = i; + burst.queue(() -> { + for (int j = 0; j < 16; j++) { + for (int k = height - 1; k >= 0; k--) { + PlatformBlockState block = output.get(finalI, k, j); + if (block == null) { + continue; + } + PlatformBlockState base = States.ORE_BASES.get(baseKey(block)); + if (base != null) { + output.set(finalI, k, j, base); + } + } + } + }); + } + burst.complete(); + } + + private int getHeight(Hunk output, int x, int z) { + for (int i = output.getHeight() - 1; i >= 0; i--) { + PlatformBlockState b = output.get(x, i, z); + + if (b != null) { + if (!B.isAir(b) && !B.isFluid(b)) { + return i; + } + } + } + + return 0; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java new file mode 100644 index 000000000..cf4b008af --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java @@ -0,0 +1,345 @@ +/* + * 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.modifier; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.engine.mantle.EngineMantle; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.placement.IrisSlopeClip; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.spi.PlatformBlockState; + +public class IrisPostModifier extends EngineAssignedModifier { + private static final class States { + private static final PlatformBlockState AIR = B.getState("AIR"); + } + + private final RNG rng; + + public IrisPostModifier(Engine engine) { + super(engine, "Post"); + rng = new RNG(getEngine().getSeedManager().getPost()); + } + + @Override + public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + // The post stage runs sequentially on production (multicore false); an uncontended + // monitor per probe is still a monitor times ~10k probes per chunk. + Hunk sync = multicore ? output.synchronize() : output; + int width = output.getWidth(); + int depth = output.getDepth(); + int planeWidth = width + 2; + int[] heights = heightPlane(x, z, width, depth, planeWidth); + IrisDimension dimension = getDimension(); + boolean walls = dimension.isPostProcessingWalls(); + boolean slabs = dimension.isPostProcessingSlabs(); + int fluidHeight = dimension.getFluidHeight(); + for (int i = 0; i < width; i++) { + for (int j = 0; j < depth; j++) { + post(i, j, sync, i + x, j + z, context, heights, planeWidth, walls, slabs, fluidHeight); + } + } + + getEngine().getMetrics().getPost().put(p.getMilliseconds()); + } + + /** + * Every column reads its own height plus its four neighbours, so adjacent columns would otherwise + * resolve the same height stream entry up to five times. Resolve the padded plane once instead. The + * four diagonal corners are never read, so they are left unresolved. + */ + private int[] heightPlane(int x, int z, int width, int depth, int planeWidth) { + int[] heights = new int[planeWidth * (depth + 2)]; + EngineMantle mantle = getEngine().getMantle(); + + for (int j = -1; j <= depth; j++) { + boolean edge = j == -1 || j == depth; + int from = edge ? 0 : -1; + int to = edge ? width - 1 : width; + int row = (j + 1) * planeWidth; + + for (int i = from; i <= to; i++) { + heights[row + i + 1] = mantle.trueHeight(x + i, z + j); + } + } + + return heights; + } + + private void post(int currentPostX, int currentPostZ, Hunk currentData, int x, int z, ChunkContext context, int[] heights, int planeWidth, boolean walls, boolean slabs, int fluidHeight) { + // x/z are world coordinates, the hunk is indexed relative to this chunk origin. + int originX = x - currentPostX; + int originZ = z - currentPostZ; + int center = (currentPostZ + 1) * planeWidth + currentPostX + 1; + int h = heights[center]; + int ha = heights[center + 1]; + int hb = heights[center + planeWidth]; + int hc = heights[center - 1]; + int hd = heights[center - planeWidth]; + + // Floating Nibs + int g = 0; + + if (h < 1) { + return; + } + + g += ha < h - 1 ? 1 : 0; + g += hb < h - 1 ? 1 : 0; + g += hc < h - 1 ? 1 : 0; + g += hd < h - 1 ? 1 : 0; + + if (g == 4 && isAir(x, h - 1, z, originX, originZ, currentData)) { + setPostBlock(x, h, z, States.AIR, originX, originZ, currentData); + + for (int i = h - 1; i > 0; i--) { + if (!isAir(x, i, z, originX, originZ, currentData)) { + h = i; + break; + } + } + } + + // Nibs + g = 0; + g += ha == h - 1 ? 1 : 0; + g += hb == h - 1 ? 1 : 0; + g += hc == h - 1 ? 1 : 0; + g += hd == h - 1 ? 1 : 0; + + if (g >= 4) { + PlatformBlockState bcState = getPostBlock(x, h, z, originX, originZ, currentData); + PlatformBlockState bState = getPostBlock(x, h + 1, z, originX, originZ, currentData); + + if (bState.isOccluding() && bState.isSolid()) { + if (bcState.isSolid()) { + setPostBlock(x, h, z, bState, originX, originZ, currentData); + h--; + } + } + } else { + // Potholes + g = 0; + g += ha == h + 1 ? 1 : 0; + g += hb == h + 1 ? 1 : 0; + g += hc == h + 1 ? 1 : 0; + g += hd == h + 1 ? 1 : 0; + + if (g >= 4) { + PlatformBlockState ba = getPostBlock(x, ha, z, originX, originZ, currentData); + PlatformBlockState bb = getPostBlock(x, hb, z, originX, originZ, currentData); + PlatformBlockState bc = getPostBlock(x, hc, z, originX, originZ, currentData); + PlatformBlockState bd = getPostBlock(x, hd, z, originX, originZ, currentData); + g = 0; + g = B.isSolid(ba) ? g + 1 : g; + g = B.isSolid(bb) ? g + 1 : g; + g = B.isSolid(bc) ? g + 1 : g; + g = B.isSolid(bd) ? g + 1 : g; + + if (g >= 3) { + setPostBlock(x, h + 1, z, getPostBlock(x, h, z, originX, originZ, currentData), originX, originZ, currentData); + h++; + } + } + } + + // Wall Patcher + IrisBiome biome = context.getBiome().get(currentPostX, currentPostZ); + + if (walls) { + if (!biome.getWall().getPalette().isEmpty()) { + if (ha < h - 2 || hb < h - 2 || hc < h - 2 || hd < h - 2) { + boolean brokeGround = false; + int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); + + for (int i = h; i > h - max; i--) { + PlatformBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getData()); + + if (d != null) { + if (isAirOrWater(x, i, z, originX, originZ, currentData)) { + if (brokeGround) { + break; + } + + continue; + } + + setPostBlock(x, i, z, d, originX, originZ, currentData); + brokeGround = true; + } + } + } + } + } + + // Slab + if (slabs) { + //@builder + if ((ha == h + 1 && isSolidNonSlab(x + 1, ha, z, originX, originZ, currentData)) + || (hb == h + 1 && isSolidNonSlab(x, hb, z + 1, originX, originZ, currentData)) + || (hc == h + 1 && isSolidNonSlab(x - 1, hc, z, originX, originZ, currentData)) + || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, originX, originZ, currentData))) + //@done + { + IrisSlopeClip sc = biome.getSlab().getSlopeCondition(); + PlatformBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getData()) : null; + + if (d != null) { + boolean cancel = B.isAir(d); + + if (IrisProceduralBlocks.materialKey(d).equals("minecraft:snow") && h + 1 <= fluidHeight) { + cancel = true; + } + + if (isSnowLayer(x, h, z, originX, originZ, currentData)) { + cancel = true; + } + + if (!cancel && isAirOrWater(x, h + 1, z, originX, originZ, currentData)) { + setPostBlock(x, h + 1, z, d, originX, originZ, currentData); + h++; + } + } + } + } + + // Waterlogging + PlatformBlockState b = getPostBlock(x, h, z, originX, originZ, currentData); + + if (IrisProceduralBlocks.hasProperty(b, "waterlogged")) { + boolean w = false; + + if (h <= fluidHeight + 1) { + if (isWaterOrWaterlogged(x, h + 1, z, originX, originZ, currentData)) { + w = true; + } else if ((isWaterOrWaterlogged(x + 1, h, z, originX, originZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, originX, originZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, originX, originZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, originX, originZ, currentData))) { + w = true; + } + } + + if (w != "true".equals(IrisProceduralBlocks.propertyValue(b, "waterlogged"))) { + setPostBlock(x, h, z, b.withProperty("waterlogged", String.valueOf(w)), originX, originZ, currentData); + } + } + + // Foliage + b = getPostBlock(x, h + 1, z, originX, originZ, currentData); + + if (B.isVineBlock(b)) { + PlatformBlockState result = b; + int finalH = h + 1; + + for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { + if (!IrisProceduralBlocks.hasProperty(b, face)) { + continue; + } + int[] mod = IrisProceduralBlocks.faceOffset(face); + PlatformBlockState d = getPostBlock(x + mod[0], finalH + mod[1], z + mod[2], originX, originZ, currentData); + result = result.withProperty(face, String.valueOf(!B.isAir(d) && !B.isVineBlock(d))); + } + if (!result.equals(b)) { + setPostBlock(x, h + 1, z, result, originX, originZ, currentData); + } + } + + if (B.isFoliage(b) || IrisProceduralBlocks.materialKey(b).equals("minecraft:dead_bush")) { + PlatformBlockState onto = getPostBlock(x, h, z, originX, originZ, currentData); + + if (!B.canPlaceOnto(b, onto) && !B.isDecorant(b)) { + setPostBlock(x, h + 1, z, States.AIR, originX, originZ, currentData); + } + } + } + + public boolean isAir(int x, int y, int z, int originX, int originZ, Hunk currentData) { + String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)); + return material.equals("minecraft:air") || material.equals("minecraft:cave_air"); + } + + public boolean hasGravity(int x, int y, int z, int originX, int originZ, Hunk currentData) { + String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)); + return material.equals("minecraft:sand") || material.equals("minecraft:red_sand") || material.endsWith("_concrete_powder"); + } + + public boolean isSolid(int x, int y, int z, int originX, int originZ, Hunk currentData) { + PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData); + return B.isSolid(d) && !B.isVineBlock(d); + } + + public boolean isSolidNonSlab(int x, int y, int z, int originX, int originZ, Hunk currentData) { + PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData); + return B.isSolid(d) && !IrisProceduralBlocks.materialKey(d).endsWith("_slab"); + } + + public boolean isAirOrWater(int x, int y, int z, int originX, int originZ, Hunk currentData) { + String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)); + return material.equals("minecraft:water") || material.equals("minecraft:air") || material.equals("minecraft:cave_air"); + } + + public boolean isSlab(int x, int y, int z, int originX, int originZ, Hunk currentData) { + return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).endsWith("_slab"); + } + + public boolean isSnowLayer(int x, int y, int z, int originX, int originZ, Hunk currentData) { + return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).equals("minecraft:snow"); + } + + public boolean isWater(int x, int y, int z, int originX, int originZ, Hunk currentData) { + return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).equals("minecraft:water"); + } + + public boolean isWaterOrWaterlogged(int x, int y, int z, int originX, int originZ, Hunk currentData) { + PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData); + return IrisProceduralBlocks.materialKey(d).equals("minecraft:water") || "true".equals(IrisProceduralBlocks.propertyValue(d, "waterlogged")); + } + + public boolean isLiquid(int x, int y, int z, int originX, int originZ, Hunk currentData) { + return IrisProceduralBlocks.hasProperty(getPostBlock(x, y, z, originX, originZ, currentData), "level"); + } + + public void setPostBlock(int x, int y, int z, PlatformBlockState d, int originX, int originZ, Hunk currentData) { + int lx = x - originX; + int lz = z - originZ; + + if (lx < 0 || lz < 0 || lx >= currentData.getWidth() || lz >= currentData.getDepth() || y < 0 || y >= currentData.getHeight()) { + return; + } + + currentData.set(lx, y, lz, d); + } + + /** + * Neighbour columns can sit one block outside this chunk, and the blocks of an adjacent chunk are not + * available while generating this one. Resolve the hunk index relative to the chunk origin and let + * getClosest clamp to the nearest in-chunk column instead of wrapping to the opposite chunk edge. + */ + public PlatformBlockState getPostBlock(int x, int y, int z, int originX, int originZ, Hunk h) { + PlatformBlockState b = h.getClosest(x - originX, y, z - originZ); + + return b == null ? States.AIR : b; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java b/src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java new file mode 100644 index 000000000..8c07ecbe1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/ArrayType.java @@ -0,0 +1,35 @@ +/* + * 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.annotations; + +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 ArrayType { + Class type(); + + int min() default 0; +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java b/src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java new file mode 100644 index 000000000..05c175a76 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java @@ -0,0 +1,31 @@ +/* + * 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.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({FIELD}) +public @interface DependsOn { + String[] value(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/Desc.java b/src/main/java/art/arcane/iris/engine/object/annotations/Desc.java new file mode 100644 index 000000000..20f7887e0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/Desc.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 Desc { + String value(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java b/src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java new file mode 100644 index 000000000..a50844724 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/MaxNumber.java @@ -0,0 +1,31 @@ +/* + * 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.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({FIELD}) +public @interface MaxNumber { + double value(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java b/src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java new file mode 100644 index 000000000..1e286d941 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/MinNumber.java @@ -0,0 +1,31 @@ +/* + * 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.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({FIELD}) +public @interface MinNumber { + double value(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java new file mode 100644 index 000000000..538c1b367 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java @@ -0,0 +1,37 @@ +/* + * 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.object.annotations; + +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; + +/** + * Marks a String field (or a list of Strings) as a live biome-registry key, so schema completion offers every + * vanilla, datapack, and mod biome instead of nothing. + */ +@Retention(RUNTIME) +@Target({PARAMETER, TYPE, FIELD}) +public @interface RegistryListBiome { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java new file mode 100644 index 000000000..9c698782d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 RegistryListBlockType { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java new file mode 100644 index 000000000..918fe7343 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java @@ -0,0 +1,14 @@ +package art.arcane.iris.engine.object.annotations; + +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 RegistryListEnchantment { +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java new file mode 100644 index 000000000..74473f2c5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java @@ -0,0 +1,33 @@ +/* + * 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.object.annotations; + +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 RegistryListEntityType { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java new file mode 100644 index 000000000..83a8dc660 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 RegistryListFont { + +} 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 new file mode 100644 index 000000000..d1157b77a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFunction.java @@ -0,0 +1,18 @@ +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/RegistryListItemType.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java new file mode 100644 index 000000000..b1ff189dd --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 RegistryListItemType { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java new file mode 100644 index 000000000..8fcf6d18d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java @@ -0,0 +1,14 @@ +package art.arcane.iris.engine.object.annotations; + +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 RegistryListNativeJigsawPool { +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java new file mode 100644 index 000000000..9b8493c8f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java @@ -0,0 +1,14 @@ +package art.arcane.iris.engine.object.annotations; + +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 RegistryListPotionEffect { +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java new file mode 100644 index 000000000..7f8e40b19 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java @@ -0,0 +1,35 @@ +/* + * 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.annotations; + +import art.arcane.iris.core.loader.IrisRegistrant; + +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 RegistryListResource { + Class value(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java new file mode 100644 index 000000000..528c33c47 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 RegistryListSpecialEntity { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java new file mode 100644 index 000000000..8f985907c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 RegistryListStructure { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java new file mode 100644 index 000000000..1560df858 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java @@ -0,0 +1,41 @@ +/* + * 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.annotations; + +import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; +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 RegistryListVanillaStructure { + /** + * When true the field accepts family/namespace prefixes in addition to exact registered keys + * (the {@code IrisImportedStructureControl.matchesKey} contract: "minecraft:village" matches + * every village variant, "nova_structures:" matches a whole namespace). The generated editor + * schema then validates entries against the registry enum OR a key/prefix pattern instead of + * rejecting anything that is not an exact registered key. + */ + boolean prefixes() default false; +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java new file mode 100644 index 000000000..e877e6ff5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 RegistryListVanillaStructureSet { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java new file mode 100644 index 000000000..c313daf93 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface RegistryMapBlockState { + String value(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/Required.java b/src/main/java/art/arcane/iris/engine/object/annotations/Required.java new file mode 100644 index 000000000..a449f470c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/Required.java @@ -0,0 +1,33 @@ +/* + * 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.annotations; + +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 Required { + +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java b/src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java new file mode 100644 index 000000000..980e818bd --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/Snippet.java @@ -0,0 +1,31 @@ +/* + * 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.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Retention(RUNTIME) +@Target({TYPE}) +public @interface Snippet { + String 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 new file mode 100644 index 000000000..eabc3086e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/functions/ComponentFlagFunction.java @@ -0,0 +1,42 @@ +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.engine.mantle.ComponentFlag; +import art.arcane.iris.engine.mantle.MantleComponent; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.io.JarScanner; +import art.arcane.volmlib.util.mantle.flag.MantleFlag; + +import java.util.Objects; + +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) { + var engine = data.getEngine(); + if (engine != null) return engine.getMantle().getComponentFlags().toStringList(); + JarScanner scanner = new JarScanner(IrisPlatforms.get().pluginJar(), "art.arcane.iris.engine.mantle.components"); + J.attempt(scanner::scan); + return scanner.getClasses() + .stream() + .filter(c -> c.isAnnotationPresent(ComponentFlag.class)) + .filter(MantleComponent.class::isAssignableFrom) + .map(c -> c.getDeclaredAnnotation(ComponentFlag.class)) + .filter(Objects::nonNull) + .map(ComponentFlag::value) + .map(MantleFlag::toString) + .collect(KList.collector()); + } +} 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 new file mode 100644 index 000000000..37107e219 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/annotations/functions/LootTableKeyFunction.java @@ -0,0 +1,23 @@ +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 new file mode 100644 index 000000000..62ee6fec4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompat.java @@ -0,0 +1,381 @@ +/* + * 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 new file mode 100644 index 000000000..5ca1bfa6b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java @@ -0,0 +1,72 @@ +/* + * 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.engine.data.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 new file mode 100644 index 000000000..2579ed62b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java @@ -0,0 +1,69 @@ +/* + * 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.iris.engine.data.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/decoration/IrisDecorationPart.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationPart.java new file mode 100644 index 000000000..38ec3f688 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationPart.java @@ -0,0 +1,39 @@ +/* + * 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.decoration; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Represents a location where decorations should go") +public enum IrisDecorationPart { + @Desc("The default, decorate anywhere") + NONE, + + @Desc("Targets shore lines (typically for sugar cane)") + SHORE_LINE, + + @Desc("Target sea surfaces (typically for lilypads)") + SEA_SURFACE, + + @Desc("Targets the sea floor (entire placement must be bellow sea level)") + SEA_FLOOR, + + @Desc("Decorates on cave & carving ceilings or underside of overhangs") + CEILING, +} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java new file mode 100644 index 000000000..a2ee1d3ab --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java @@ -0,0 +1,96 @@ +/* + * 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.decoration; + +import art.arcane.iris.engine.object.annotations.Desc; + +import java.util.Locale; + +/** + * Pure-JVM mirror of Minecraft's decoration generation steps, in registry (ordinal) order. The ordinals and + * serialized names match {@code GenerationStep.Decoration} on MC 26.2 so a platform can convert either way + * without core depending on a Minecraft type. Verified against MC 26.2 GenerationStep.Decoration. + */ +@Desc("A vanilla decoration generation step. Placed features are grouped into these steps and run in this order.") +public enum IrisDecorationStep { + @Desc("Raw generation - the earliest step, before lakes.") + RAW_GENERATION("raw_generation"), + + @Desc("Lakes.") + LAKES("lakes"), + + @Desc("Local modifications such as amethyst geodes, icebergs and dripstone clusters.") + LOCAL_MODIFICATIONS("local_modifications"), + + @Desc("Underground structure features (not the structure system - features tagged as underground structures).") + UNDERGROUND_STRUCTURES("underground_structures"), + + @Desc("Surface structure features.") + SURFACE_STRUCTURES("surface_structures"), + + @Desc("Stronghold step.") + STRONGHOLDS("strongholds"), + + @Desc("Underground ores. This is the step that carries vanilla and mod ore veins.") + UNDERGROUND_ORES("underground_ores"), + + @Desc("Underground decoration such as glow lichen, sculk patches and cave vegetation.") + UNDERGROUND_DECORATION("underground_decoration"), + + @Desc("Fluid springs - the small water and lava spring features.") + FLUID_SPRINGS("fluid_springs"), + + @Desc("Vegetal decoration - trees, grass, flowers, kelp and most surface plant life.") + VEGETAL_DECORATION("vegetal_decoration"), + + @Desc("Top layer modification - freezing and snow placement.") + TOP_LAYER_MODIFICATION("top_layer_modification"); + + private final String serializedName; + + IrisDecorationStep(String serializedName) { + this.serializedName = serializedName; + } + + public String getSerializedName() { + return serializedName; + } + + /** + * Resolves a step by its vanilla ordinal. Returns null when the running Minecraft version declares more + * decoration steps than this enum knows about, which the callers treat as "unknown step, generate it". + */ + public static IrisDecorationStep byOrdinal(int ordinal) { + IrisDecorationStep[] values = values(); + return ordinal < 0 || ordinal >= values.length ? null : values[ordinal]; + } + + public static IrisDecorationStep byKey(String key) { + if (key == null || key.isBlank()) { + return null; + } + String normalized = key.trim().toLowerCase(Locale.ROOT); + for (IrisDecorationStep step : values()) { + if (step.serializedName.equals(normalized) || step.name().toLowerCase(Locale.ROOT).equals(normalized)) { + return step; + } + } + return null; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java new file mode 100644 index 000000000..8c3e6123c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java @@ -0,0 +1,356 @@ +/* + * 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.decoration; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.placement.IrisSlopeClip; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +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.math.RNG; +import art.arcane.iris.util.project.noise.CNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Snippet("decorator") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A biome decorator is used for placing flowers, grass, cacti and so on") +@Data +public class IrisDecorator { + private final transient AtomicCache layerGenerator = new AtomicCache<>(); + private final transient AtomicCache varianceGenerator = new AtomicCache<>(); + private final transient AtomicCache heightGenerator = new AtomicCache<>(); + private final transient AtomicCache> blockData = new AtomicCache<>(); + private final transient AtomicCache> blockDataTops = new AtomicCache<>(); + private final transient AtomicCache blockDataArray = new AtomicCache<>(); + private final transient AtomicCache blockDataTopsArray = new AtomicCache<>(); + private final transient AtomicCache whitelistArray = new AtomicCache<>(); + private final transient AtomicCache blacklistArray = new AtomicCache<>(); + @Desc("The varience dispersion is used when multiple blocks are put in the palette. Scatter scrambles them, Wispy shows streak-looking varience") + private IrisGeneratorStyle variance = NoiseStyle.STATIC.style(); + @Desc("Forcefully place this decorant anywhere it is supposed to go even if it should not go on a specific surface block. For example, you could force tallgrass to place on top of stone by using this.") + private boolean forcePlace = false; + @Desc("Forced the surface block of this decorant to be the specified block. Assumes forcePlace.") + private IrisBlockData forceBlock; + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("When set, the decorator can only place onto any of these blocks.") + private KList whitelist; + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("When set, the decorator will never place onto any of these blocks.") + private KList blacklist; + @Desc("The slope at which this decorator can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the decorator placement.") + private IrisSlopeClip slopeCondition = new IrisSlopeClip(); + @DependsOn({"scaleStack", "stackMin", "stackMax"}) + @Desc("If stackMax is set to true, use this to limit its max height for large caverns") + private int absoluteMaxStack = 30; + @Desc("Dispersion is used to pick places to spawn. Scatter randomly places them (vanilla) or Wispy for a streak like patch system.") + private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); + @DependsOn({"stackMin", "stackMax"}) + @Desc("If this decorator has a height more than 1 this changes how it picks the height between your maxes. Scatter = random, Wispy = wavy heights") + private IrisGeneratorStyle heightVariance = NoiseStyle.STATIC.style(); + @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") + private IrisDecorationPart partOf = IrisDecorationPart.NONE; + @DependsOn({"stackMin", "stackMax"}) + @MinNumber(1) + @MaxNumber(2032) + @Desc("The minimum repeat stack height (setting to 3 would stack 3 of on top of each other") + private int stackMin = 1; + @DependsOn({"stackMin", "stackMax"}) + @MinNumber(1) + @MaxNumber(2032) + @Desc("The maximum repeat stack height") + private int stackMax = 1; + @DependsOn({"stackMin", "stackMax"}) + @Desc(""" + Changes stackMin and stackMin from being absolute block heights and instead uses them as a percentage to scale the stack based on the cave height + + Within a cave, setting them stackMin/max to 50 would make the stack 50% of the cave height""") + private boolean scaleStack = false; + @Required + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") + private double chance = 0.1; + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The palette of blocks to pick from when this decorator needs to place.") + private KList palette = new KList().qadd(new IrisBlockData("grass")); + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The palette of blocks used at the very top of a 'stackMax' of higher than 1. For example, bamboo tops.") + private KList topPalette = new KList<>(); + @DependsOn("topPalette") + @MinNumber(0.01) + @MaxNumber(1.0) + @Desc("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.") + private double topThreshold = 1.0; + + public int getHeight(RNG rng, double x, double z, IrisData data) { + if (stackMin == stackMax) { + return stackMin; + } + + return getHeightGenerator(rng, data) + .fit(stackMin, stackMax, + x / heightVariance.getZoom(), + z / heightVariance.getZoom()); + } + + public CNG getHeightGenerator(RNG rng, IrisData data) { + CNG cached = heightGenerator.getIfPresent(); + + if (cached != null) { + return cached; + } + + return heightGenerator.aquire(() -> + heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data)); + } + + public CNG getGenerator(RNG rng, IrisData data) { + CNG cached = layerGenerator.getIfPresent(); + + if (cached != null) { + return cached; + } + + return layerGenerator.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data)); + } + + public CNG getVarianceGenerator(RNG rng, IrisData data) { + CNG cached = varianceGenerator.getIfPresent(); + + if (cached != null) { + return cached; + } + + return varianceGenerator.aquire(() -> + variance.create( + rng.nextParallelRNG(getBlockData(data).size()), data) + .scale(1D / variance.getZoom())); + } + + public KList add(String b) { + palette.add(new IrisBlockData(b)); + return palette; + } + + public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) { + if (getBlockData(data).isEmpty()) { + return false; + } + double xx = x / style.getZoom(); + double zz = z / style.getZoom(); + return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance; + } + + public PlatformBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) { + if (!passesChanceGate(rng, x, z, data)) { + return null; + } + if (getBlockData(data).size() == 1) { + return getBlockData(data).get(0); + } + return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x); + } + + public PlatformBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { + if (getBlockData(data).isEmpty()) { + IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName()); + return null; + } + + if (getBlockData(data).size() == 1) { + return getBlockData(data).get(0); + } + + return getVarianceGenerator(rng, data).fit(getBlockData(data), z, y, x); //X and Z must be switched + } + + public PlatformBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { + if (getBlockDataTops(data).isEmpty()) { + return getBlockData100(b, rng, x, y, z, data); + } + + double xx = x / style.getZoom(); + double zz = z / style.getZoom(); + + if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here + if (getBlockData(data).size() == 1) { + return getBlockDataTops(data).get(0); + } + + return getVarianceGenerator(rng, data).fit(getBlockDataTops(data), z, y, x); //X and Z must be switched + } + + return null; + } + + public KList getBlockData(IrisData data) { + KList cached = blockData.getIfPresent(); + + if (cached != null) { + return cached; + } + + return blockData.aquire(() -> + { + KList blockData = new KList<>(); + for (IrisBlockData i : palette) { + PlatformBlockState bx = i.getBlockData(data); + if (bx != null) { + for (int n = 0; n < i.getWeight(); n++) { + blockData.add(bx); + } + } + } + + return blockData; + }); + } + + public KList getBlockDataTops(IrisData data) { + KList cached = blockDataTops.getIfPresent(); + + if (cached != null) { + return cached; + } + + return blockDataTops.aquire(() -> + { + KList blockDataTops = new KList<>(); + for (IrisBlockData i : topPalette) { + PlatformBlockState bx = i.getBlockData(data); + if (bx != null) { + for (int n = 0; n < i.getWeight(); n++) { + blockDataTops.add(bx); + } + } + } + + return blockDataTops; + }); + } + + public PlatformBlockState[] getBlockDataArray(IrisData data) { + PlatformBlockState[] cached = blockDataArray.getIfPresent(); + + if (cached != null) { + return cached; + } + + return blockDataArray.aquire(() -> { + KList list = getBlockData(data); + return list.toArray(new PlatformBlockState[0]); + }); + } + + public PlatformBlockState[] getBlockDataTopsArray(IrisData data) { + PlatformBlockState[] cached = blockDataTopsArray.getIfPresent(); + + if (cached != null) { + return cached; + } + + return blockDataTopsArray.aquire(() -> { + KList list = getBlockDataTops(data); + return list.toArray(new PlatformBlockState[0]); + }); + } + + /** + * The resolved whitelist palette. Empty when no whitelist is configured; callers must still gate on + * {@link #getWhitelist()} being non null, because an explicitly empty whitelist blocks all placement. + */ + public PlatformBlockState[] getWhitelistArray(IrisData data) { + PlatformBlockState[] cached = whitelistArray.getIfPresent(); + + if (cached != null) { + return cached; + } + + return whitelistArray.aquire(() -> resolvePalette(whitelist, data)); + } + + public PlatformBlockState[] getBlacklistArray(IrisData data) { + PlatformBlockState[] cached = blacklistArray.getIfPresent(); + + if (cached != null) { + return cached; + } + + return blacklistArray.aquire(() -> resolvePalette(blacklist, data)); + } + + private static PlatformBlockState[] resolvePalette(KList list, IrisData data) { + if (list == null) { + return new PlatformBlockState[0]; + } + + PlatformBlockState[] resolved = new PlatformBlockState[list.size()]; + + for (int i = 0; i < resolved.length; i++) { + resolved[i] = list.get(i).getBlockData(data); + } + + return resolved; + } + + public PlatformBlockState pickBlockData(RNG rng, IrisData data, double x, double z) { + PlatformBlockState[] arr = getBlockDataArray(data); + if (arr.length == 0) { + return null; + } + if (arr.length == 1) { + return arr[0]; + } + return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))]; + } + + public PlatformBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) { + PlatformBlockState[] arr = getBlockDataTopsArray(data); + if (arr.length == 0) { + return pickBlockData(rng, data, x, z); + } + if (arr.length == 1) { + return arr[0]; + } + return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))]; + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean isStacking() { + return getStackMax() > 1; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java new file mode 100644 index 000000000..bf44eb3bc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java @@ -0,0 +1,107 @@ +/* + * 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.decoration; + +import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; +import art.arcane.iris.engine.object.annotations.ArrayType; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Objects; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation for this dimension (set as the dimension's 'importedFeatures' field). Placed features are ores, trees, plants, springs, geodes and every other decoration entry a biome declares. This is OFF by default: with 'enabled' false Iris generates exactly the terrain it always has and no native feature runs. With it true, every placed feature the biome's vanilla derivative declares runs over Iris terrain, in vanilla step order, on the same worldgen thread vanilla uses. Carvers are never imported - Iris has no NoiseGeneratorSettings, so there is nothing for a carver to carve against. Family matching on 'disabled' uses namespace, slash, or underscore boundaries, so 'minecraft:ore' covers every vanilla ore feature without matching unrelated names.") +@Data +public class IrisImportedFeatureControl { + @Desc("Master switch. False (the default) means no native placed feature generates and chunk output is identical to a pack without this block at all. True runs the vanilla decoration feature pass over Iris terrain.") + private boolean enabled = false; + + @ArrayType(type = String.class, min = 1) + @Desc("Placed feature keys to deny explicitly, e.g. 'minecraft:ore_diamond'. A namespace:path prefix also matches, so 'minecraft:ore' denies every vanilla ore and 'minecraft:trees' denies every tree placement. Every key not matched here generates while 'enabled' is true.") + private KList disabled = new KList<>(); + + @ArrayType(type = IrisDecorationStep.class, min = 1) + @Desc("Restrict feature generation to these decoration steps only. Empty (the default) means every step is eligible. Use this to import ores without importing vegetation: set it to UNDERGROUND_ORES.") + private KList steps = new KList<>(); + + @ArrayType(type = IrisDecorationStep.class, min = 1) + @Desc("Decoration steps to deny. Applied after 'steps', so a step listed here never generates even if 'steps' allows it. VEGETAL_DECORATION is the usual entry for packs that grow their own trees.") + private KList disabledSteps = new KList<>(); + + /** + * True when this dimension wants the native feature pass at all. Every other accessor on this class is + * meaningless while this is false, and the platform must not build any feature machinery. + */ + public boolean shouldGenerateFeatures() { + return enabled; + } + + public boolean shouldGenerateStep(IrisDecorationStep step) { + if (!enabled) { + return false; + } + KList allowed = Objects.requireNonNull( + steps, "importedFeatures.steps must not be null"); + KList denied = Objects.requireNonNull( + disabledSteps, "importedFeatures.disabledSteps must not be null"); + if (step == null) { + // A step this Iris build does not know about (newer Minecraft): allow it unless the pack + // narrowed generation to an explicit step list. + return allowed.isEmpty(); + } + if (!allowed.isEmpty() && !allowed.contains(step)) { + return false; + } + return !denied.contains(step); + } + + public boolean shouldGenerate(String placedFeatureKey) { + return resolve(placedFeatureKey, null) == NativeFeatureGenerationStatus.GENERATE_NATIVE; + } + + /** + * Resolves one placed feature against this control. A null step skips the step gate, which is what the + * key-only query does. + */ + public NativeFeatureGenerationStatus resolve(String placedFeatureKey, IrisDecorationStep step) { + if (!enabled) { + return NativeFeatureGenerationStatus.FEATURES_DISABLED; + } + if (placedFeatureKey == null || placedFeatureKey.isBlank()) { + return NativeFeatureGenerationStatus.INVALID_REGISTRY_KEY; + } + if (step != null && !shouldGenerateStep(step)) { + return NativeFeatureGenerationStatus.STEP_DISABLED; + } + KList deniedKeys = Objects.requireNonNull( + disabled, "importedFeatures.disabled must not be null"); + for (String entry : deniedKeys) { + if (IrisImportedStructureControl.matchesKey(entry, placedFeatureKey)) { + return NativeFeatureGenerationStatus.DISABLED_BY_PACK; + } + } + return NativeFeatureGenerationStatus.GENERATE_NATIVE; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java b/src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java new file mode 100644 index 000000000..8c828b99d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java @@ -0,0 +1,28 @@ +/* + * 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.decoration; + +public enum NativeFeatureGenerationStatus { + GENERATE_NATIVE, + FEATURES_DISABLED, + STEP_DISABLED, + DISABLED_BY_PACK, + CYCLE_DEGRADED, + INVALID_REGISTRY_KEY +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java new file mode 100644 index 000000000..fe7b4fe91 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java @@ -0,0 +1,154 @@ +/* + * 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.entity; + +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.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.attribute.Attributable; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; +import org.bukkit.attribute.AttributeModifier.Operation; +import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +@Snippet("attribute-modifier") +@Accessors(chain = true) +@AllArgsConstructor +@NoArgsConstructor +@Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") +@Data +public class IrisAttributeModifier { + private static final Set WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet(); + + @Required + @Desc("The Attribute type key such as max_health or minecraft:armor. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.") + private String attribute = null; + + @MinNumber(2) + @Required + @Desc("The Attribute Name is used internally only for the game. This value should be unique to all other attributes applied to this item/entity. It is not shown in game.") + private String name = ""; + + @Desc("The application operation: ADD_NUMBER (default), ADD_SCALAR or MULTIPLY_SCALAR_1. Add Number adds to the default value. \nAdd scalar_1 will multiply by 1 for example if the health is 20 and you multiply_scalar_1 by 0.5, the health will result in 30, not 10. Use negative values to achieve that.") + private String operation = "ADD_NUMBER"; + + @Desc("Minimum amount for this modifier. Iris randomly chooses an amount, this is the minimum it can choose randomly for this attribute.") + private double minAmount = 1; + + @Desc("Maximum amount for this modifier Iris randomly chooses an amount, this is the maximum it can choose randomly for this attribute.") + private double maxAmount = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.") + private double chance = 1; + + public void apply(RNG rng, ItemMeta meta) { + if (rng.nextDouble() < getChance()) { + Attribute resolved = resolveAttribute(); + if (resolved == null) { + return; + } + meta.addAttributeModifier(resolved, createModifier(rng)); + } + } + + public void apply(RNG rng, Attributable meta) { + if (rng.nextDouble() < getChance()) { + Attribute resolved = resolveAttribute(); + if (resolved == null) { + return; + } + meta.getAttribute(resolved).addModifier(createModifier(rng)); + } + } + + public double getAmount(RNG rng) { + return rng.d(getMinAmount(), getMaxAmount()); + } + + private Attribute resolveAttribute() { + if (attribute == null || attribute.isBlank()) { + return null; + } + String value = attribute.trim().toLowerCase(Locale.ROOT); + Attribute resolved; + if (value.contains(":")) { + NamespacedKey key = NamespacedKey.fromString(value); + resolved = key == null ? null : Registry.ATTRIBUTE.get(key); + } else { + resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value)); + if (resolved == null && value.startsWith("generic_")) { + resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic_".length()))); + } + if (resolved == null && value.startsWith("generic.")) { + resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic.".length()))); + } + } + if (resolved == null && WARNED_ATTRIBUTES.add(value)) { + IrisLogging.warn("Unknown attribute '" + attribute + "' in attribute-modifier '" + name + "'"); + } + return resolved; + } + + private Operation resolveOperation() { + if (operation == null || operation.isBlank()) { + return Operation.ADD_NUMBER; + } + try { + return Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return Operation.ADD_NUMBER; + } + } + + private AttributeModifier createModifier(RNG rng) { + NamespacedKey key = NamespacedKey.minecraft(generateModifierKey()); + return new AttributeModifier(key, getAmount(rng), resolveOperation(), EquipmentSlotGroup.ANY); + } + + private String generateModifierKey() { + String source = getName() == null ? "modifier" : getName(); + String normalized = source.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9/._-]", "_"); + if (normalized.isBlank()) { + normalized = "modifier"; + } + if (normalized.length() > 32) { + normalized = normalized.substring(0, 32); + } + String random = UUID.randomUUID().toString().replace("-", ""); + return normalized + "_" + random; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java new file mode 100644 index 000000000..93e9baa77 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java @@ -0,0 +1,323 @@ +/* + * 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.entity; + +import art.arcane.iris.engine.object.marker.IrisCommandRegistry; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +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.RegistryListPotionEffect; +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.math.RNG; +import art.arcane.volmlib.util.scheduling.ChronoLatch; +import art.arcane.iris.util.common.data.registry.RegistryUtil; +import art.arcane.iris.util.common.scheduling.J; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +@Snippet("effect") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("An iris effect") +@Data +public class IrisEffect { + private final transient AtomicCache pt = new AtomicCache<>(); + private final transient AtomicCache latch = new AtomicCache<>(); + private final transient AtomicCache particleEffectResolved = new AtomicCache<>(); + private final transient AtomicCache soundResolved = new AtomicCache<>(); + @RegistryListPotionEffect + @Desc("The potion effect to apply in this area") + private String potionEffect = ""; + @Desc("The particle effect to apply in the area") + private String particleEffect = null; + @DependsOn({"particleEffect"}) + @MinNumber(-32) + @MaxNumber(32) + @Desc("Randomly offset from the surface to this surface+value") + private int particleOffset = 0; + @DependsOn({"particleEffect"}) + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltX = 0; + @DependsOn({"particleEffect"}) + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltY = 0; + @DependsOn({"particleEffect"}) + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltZ = 0; + @DependsOn({"particleEffect"}) + @Desc("Randomize the altX by -altX to altX") + private boolean randomAltX = true; + @DependsOn({"particleEffect"}) + @Desc("Randomize the altY by -altY to altY") + private boolean randomAltY = false; + @DependsOn({"particleEffect"}) + @Desc("Randomize the altZ by -altZ to altZ") + private boolean randomAltZ = true; + @Desc("The sound to play") + private String sound = null; + @DependsOn({"sound"}) + @MinNumber(0) + @MaxNumber(512) + @Desc("The max distance from the player the sound will play") + private int soundDistance = 12; + @DependsOn({"sound", "maxPitch"}) + @MinNumber(0.01) + @MaxNumber(1.99) + @Desc("The minimum sound pitch") + private double minPitch = 0.5D; + @DependsOn({"sound", "minVolume"}) + @MinNumber(0.01) + @MaxNumber(1.99) + @Desc("The max sound pitch") + private double maxPitch = 1.5D; + @DependsOn({"sound"}) + @MinNumber(0.001) + @MaxNumber(512) + @Desc("The sound volume.") + private double volume = 1.5D; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(512) + @Desc("The particle count. Try setting to zero for using the alt xyz to a motion value instead of an offset") + private int particleCount = 0; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(64) + @Desc("How far away from the player particles can play") + private int particleDistance = 20; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(128) + @Desc("How wide the particles can play (player's view left and right) RADIUS") + private int particleDistanceWidth = 24; + @DependsOn({"particleEffect"}) + @Desc("An extra value for some particles... Which bukkit doesn't even document.") + private double extra = 0; + @DependsOn({"potionEffect"}) + @MinNumber(-1) + @MaxNumber(1024) + @Desc("The Potion Strength or -1 to disable") + private int potionStrength = -1; + @DependsOn({"potionEffect", "potionTicksMin"}) + @MinNumber(1) + @Desc("The max time the potion will last for") + private int potionTicksMax = 155; + @DependsOn({"potionEffect", "potionTicksMax"}) + @MinNumber(1) + @Desc("The min time the potion will last for") + private int potionTicksMin = 75; + @Required + @MinNumber(0) + @Desc("The effect interval in milliseconds") + private int interval = 150; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(16) + @Desc("The effect distance start away") + private int particleAway = 5; + @Required + @MinNumber(1) + @Desc("The chance is 1 in CHANCE per interval") + private int chance = 50; + @Desc("Run commands, with configurable location parameters") + private IrisCommandRegistry commandRegistry = null; + + + public boolean canTick() { + return latch.aquire(() -> new ChronoLatch(interval)).flip(); + } + + public boolean shouldApplyNow() { + return canTick() && RNG.r.nextInt(chance) == 0; + } + + public String getParticleEffectKey() { + return particleEffect; + } + + public String getSoundKey() { + return sound; + } + + public Particle getParticleEffect() { + if (particleEffect == null) { + return null; + } + return particleEffectResolved.aquire(() -> resolveKeyed(Particle.class, particleEffect)); + } + + public Sound getSound() { + if (sound == null) { + return null; + } + return soundResolved.aquire(() -> resolveKeyed(Sound.class, sound)); + } + + private static T resolveKeyed(Class type, String key) { + NamespacedKey namespacedKey = NamespacedKey.fromString(key); + return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey); + } + + public PotionEffectType getRealType() { + return pt.aquire(() -> + { + if (getPotionEffect() == null || getPotionEffect().isEmpty()) { + return PotionEffectType.LUCK; + } + + try { + PotionEffectType resolved = PotionEffectTypes.resolve(getPotionEffect()); + if (resolved != null) { + return resolved; + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + + if (PotionEffectTypes.shouldWarn(getPotionEffect())) { + IrisLogging.warn("Unknown Potion Effect Type: \"" + getPotionEffect() + "\". Valid types: " + PotionEffectTypes.knownTypesList()); + } + + return PotionEffectType.LUCK; + }); + } + + private static final class BukkitFx { + private static void run(Player p, Runnable r) { + J.runEntity(p, r); + } + } + + public void apply(Player p, Engine g) { + if (!shouldApplyNow()) { + return; + } + + BukkitFx.run(p, () -> { + Sound soundType = getSound(); + Particle particleType = getParticleEffect(); + if (soundType != null) { + Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); + p.playSound(part, soundType, (float) volume, (float) RNG.r.d(minPitch, maxPitch)); + } + + if (particleType != null) { + Location part = p.getLocation().clone().add(p.getLocation().getDirection().clone().multiply(RNG.r.i(particleDistance) + particleAway)).clone().add(p.getLocation().getDirection().clone().rotateAroundY(Math.toRadians(90)).multiply(RNG.r.d(-particleDistanceWidth, particleDistanceWidth))); + + part.setY(Math.round(g.getHeight(part.getBlockX(), part.getBlockZ())) + 1); + part.add(RNG.r.d(), 0, RNG.r.d()); + int offset = p.getWorld().getMinHeight(); + if (extra != 0) { + p.spawnParticle(particleType, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), + part.getZ(), + particleCount, + randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, + randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, + randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, + extra); + } else { + p.spawnParticle(particleType, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), part.getZ(), + particleCount, + randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, + randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, + randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ); + } + } + + if (commandRegistry != null) { + commandRegistry.run(p); + } + + if (potionStrength > -1) { + if (p.hasPotionEffect(getRealType())) { + PotionEffect e = p.getPotionEffect(getRealType()); + if (e != null && e.getAmplifier() > getPotionStrength()) { + return; + } + + p.removePotionEffect(getRealType()); + } + + p.addPotionEffect(new PotionEffect(getRealType(), + RNG.r.i(Math.min(potionTicksMax, potionTicksMin), + Math.max(potionTicksMax, potionTicksMin)), + getPotionStrength(), + true, false, false)); + } + }); + } + + public void apply(Entity p) { + if (!shouldApplyNow()) { + return; + } + + J.runEntity(p, () -> { + Sound soundType = getSound(); + Particle particleType = getParticleEffect(); + if (soundType != null) { + Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); + p.getWorld().playSound(part, soundType, (float) volume, (float) RNG.r.d(minPitch, maxPitch)); + } + + if (particleType != null) { + Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d())); + part.add(RNG.r.d(), 0, RNG.r.d()); + if (extra != 0) { + p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), + part.getZ(), + particleCount, + randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, + randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, + randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, + extra); + } else { + p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), part.getZ(), + particleCount, + randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, + randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, + randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ); + } + } + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java new file mode 100644 index 000000000..5821b383b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java @@ -0,0 +1,555 @@ +/* + * 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.entity; + +import art.arcane.iris.engine.object.entity.spawn.IrisSurface; +import art.arcane.iris.engine.object.loot.InventorySlotType; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.marker.IrisCommand; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.core.service.EntityRiseSVC; +import art.arcane.iris.core.service.ExternalDataSVC; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.platform.EngineBukkitOps; +import art.arcane.iris.engine.object.annotations.ArrayType; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.RegistryListEntityType; +import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.util.common.data.registry.RegistryUtil; +import art.arcane.iris.platform.bukkit.BukkitWorld; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.util.common.format.C; +import art.arcane.volmlib.util.math.M; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.util.common.plugin.Chunks; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Sound; +import org.bukkit.attribute.Attributable; +import org.bukkit.entity.Ageable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Panda; +import org.bukkit.entity.Villager; +import org.bukkit.entity.Panda.Gene; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.loot.LootContext; +import org.bukkit.loot.LootTable; +import org.bukkit.loot.Lootable; +import org.bukkit.util.Vector; + +import java.util.Collection; +import java.util.Locale; +import java.util.Random; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static art.arcane.iris.util.common.data.registry.Particles.ITEM; + +@SuppressWarnings("ALL") +@Accessors(chain = true) +@NoArgsConstructor + +@Desc("Represents an iris entity.") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisEntity extends IrisRegistrant { + @Required + @RegistryListEntityType + @Desc("The namespaced key of the entity type to spawn, such as minecraft:zombie or alexsmobs:grizzly_bear. To spawn a mob from another plugin or provider, set this type to unknown and define the special type.") + private String type = null; + + @Desc("The SpawnReason name to spawn the entity with, such as NATURAL or COMMAND.") + private String reason = null; + + @Desc("The custom name of this entity") + private String customName = ""; + + @Desc("Should the name on this entity be visible even if you arent looking at it.") + private boolean customNameVisible = false; + + @Desc("If this entity type is a mob, should it be aware of it's surroundings & interact with the world.") + private boolean aware = true; + + @Desc("If this entity type is a creature, should it have ai goals.") + private boolean ai = true; + + @Desc("Should this entity be glowing") + private boolean glowing = false; + + @Desc("Should gravity apply to this entity") + private boolean gravity = true; + + @Desc("When an entity is invulnerable it can only be damaged by players increative mode.") + private boolean invulnerable = false; + + @Desc("When an entity is silent it will not produce any sound.") + private boolean silent = false; + + @Desc("Should this entity be allowed to pickup items") + private boolean pickupItems = false; + + @Desc("Should this entity be removed when far away") + private boolean removable = false; + + @Desc("Entity helmet equipment") + private IrisLoot helmet = null; + + @Desc("Entity chestplate equipment") + private IrisLoot chestplate = null; + + @Desc("Entity boots equipment") + private IrisLoot boots = null; + + @Desc("Entity leggings equipment") + private IrisLoot leggings = null; + + @Desc("Entity main hand equipment") + private IrisLoot mainHand = null; + + @Desc("Entity off hand equipment") + private IrisLoot offHand = null; + + @Desc("Make other entities ride this entity") + @ArrayType(min = 1, type = IrisEntity.class) + private KList passengers = new KList<>(); + + @Desc("Attribute modifiers for this entity") + @ArrayType(min = 1, type = IrisAttributeModifier.class) + private KList attributes = new KList<>(); + + @Desc("Loot tables for drops. Only the tables list is honored for entities; mode and multiplier are ignored, and the tables replace vanilla drops entirely.") + private IrisLootReference loot = new IrisLootReference(); + + @Desc("If specified, this entity will be leashed by this entity. I.e. THIS ENTITY Leashed by SPECIFIED. This has no effect on EnderDragons, Withers, Players, or Bats.Non-living entities excluding leashes will not persist as leashholders.") + private IrisEntity leashHolder = null; + + @Desc("If specified, this entity will spawn with an effect") + private IrisEffect spawnEffect = null; + + @Desc("Simply moves the entity from below the surface slowly out of the ground as a spawn-in effect") + private boolean spawnEffectRiseOutOfGround = false; + + @Desc("The main gene for a panda if the entity type is a panda. One of NORMAL, LAZY, WORRIED, PLAYFUL, BROWN, WEAK or AGGRESSIVE.") + private String pandaMainGene = null; + + @Desc("The hidden gene for a panda if the entity type is a panda. One of NORMAL, LAZY, WORRIED, PLAYFUL, BROWN, WEAK or AGGRESSIVE.") + private String pandaHiddenGene = null; + + @Desc("The this entity is ageable, set it's baby status") + private boolean baby = false; + + @Desc("If the entity should never be culled.") + private boolean keepEntity = false; + + @Desc("The surface type to spawn this mob on") + private IrisSurface surface = IrisSurface.LAND; + + @RegistryListSpecialEntity + @Desc("Create a mob from another plugin, such as Mythic Mobs. Should be in the format of a namespace of PluginName:MobName") + private String specialType = ""; + + @Desc("Set to true if you want to apply all of the settings here to the mob, even though an external plugin has already done so.") + private boolean applySettingsToCustomMobAnyways = false; + + @ArrayType(min = 1, type = IrisCommand.class) + @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") + private KList rawCommands = new KList<>(); + + public EntityType getBukkitType() { + if (type == null || type.isBlank()) { + return EntityType.UNKNOWN; + } + + NamespacedKey key = NamespacedKey.fromString(type.trim().toLowerCase(Locale.ROOT)); + + if (key == null) { + return EntityType.UNKNOWN; + } + + EntityType entityType = RegistryUtil.lookup(EntityType.class).get(key); + return entityType == null ? EntityType.UNKNOWN : entityType; + } + + public CreatureSpawnEvent.SpawnReason getBukkitReason() { + if (reason == null || reason.isBlank()) { + return CreatureSpawnEvent.SpawnReason.NATURAL; + } + + try { + return CreatureSpawnEvent.SpawnReason.valueOf(reason.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return CreatureSpawnEvent.SpawnReason.NATURAL; + } + } + + public Gene getBukkitPandaMainGene() { + return resolveGene(pandaMainGene); + } + + public Gene getBukkitPandaHiddenGene() { + return resolveGene(pandaHiddenGene); + } + + private static Gene resolveGene(String gene) { + if (gene == null || gene.isBlank()) { + return Gene.NORMAL; + } + + try { + return Gene.valueOf(gene.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return Gene.NORMAL; + } + } + + public Entity spawn(Engine gen, Location at) { + return spawn(gen, at, new RNG(at.hashCode())); + } + + public Entity spawn(Engine gen, Location at, RNG rng) { + if (!Chunks.isSafe(at)) { + return null; + } + if (isSpawnEffectRiseOutOfGround()) { + AtomicReference f = new AtomicReference<>(at); + try { + J.sfut(() -> { + if (Chunks.hasPlayersNearby(f.get())) { + Location b = f.get().clone(); + Location start = new Location(b.getWorld(), b.getX(), b.getY() - 5, b.getZ()); + f.set(start); + } + }).get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + IrisLogging.reportError("Iris entity spawn preparation was interrupted.", e); + } catch (ExecutionException e) { + IrisLogging.reportError("Iris entity spawn preparation failed.", e); + } + at = f.get(); + } + + Entity ee = doSpawn(at); + + if (ee == null && !Chunks.isSafe(at)) { + return null; + } + + if (isSpecialType() && !applySettingsToCustomMobAnyways) { + return ee; + } + + if (ee == null) { + return null; + } + + Entity e = ee; + e.setCustomName(getCustomName() != null ? C.translateAlternateColorCodes('&', getCustomName()) : null); + e.setCustomNameVisible(isCustomNameVisible()); + e.setGlowing(isGlowing()); + e.setGravity(isGravity()); + e.setInvulnerable(isInvulnerable()); + e.setSilent(isSilent()); + e.setPersistent(isKeepEntity() || IrisSettings.get().getWorld().isForcePersistEntities()); + + int gg = 0; + for (IrisEntity i : passengers) { + Entity passenger = i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++)); + if (passenger == null) { + continue; + } + + if (Bukkit.isPrimaryThread()) { + e.addPassenger(passenger); + } else { + J.runEntity(e, () -> e.addPassenger(passenger)); + } + } + + if (e instanceof Attributable) { + Attributable a = (Attributable) e; + + for (IrisAttributeModifier i : getAttributes()) { + i.apply(rng, a); + } + } + + if (e instanceof Lootable) { + Lootable l = (Lootable) e; + + if (getLoot().getTables().isNotEmpty()) { + BukkitOps.bindLoot(this, gen, l, at, rng); + } + } + + if (e instanceof LivingEntity) { + LivingEntity l = (LivingEntity) e; + l.setAI(isAi()); + l.setCanPickupItems(isPickupItems()); + + if (getLeashHolder() != null) { + l.setLeashHolder(getLeashHolder().spawn(gen, at, rng.nextParallelRNG(234548))); + } + + l.setRemoveWhenFarAway(isRemovable()); + + if (getHelmet() != null && LootResolver.oneIn(rng, getHelmet().getRarity())) { + l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng)); + } + + if (getChestplate() != null && LootResolver.oneIn(rng, getChestplate().getRarity())) { + l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng)); + } + + if (getLeggings() != null && LootResolver.oneIn(rng, getLeggings().getRarity())) { + l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng)); + } + + if (getBoots() != null && LootResolver.oneIn(rng, getBoots().getRarity())) { + l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng)); + } + + if (getMainHand() != null && LootResolver.oneIn(rng, getMainHand().getRarity())) { + l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng)); + } + + if (getOffHand() != null && LootResolver.oneIn(rng, getOffHand().getRarity())) { + l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng)); + } + } + + if (e instanceof Ageable && isBaby()) { + ((Ageable) e).setBaby(); + } + + if (e instanceof Panda) { + ((Panda) e).setMainGene(getBukkitPandaMainGene()); + ((Panda) e).setHiddenGene(getBukkitPandaHiddenGene()); + } + + if (e instanceof Villager) { + Villager villager = (Villager) e; + villager.setRemoveWhenFarAway(false); + BukkitOps.persistVillager(villager); + } + + if (e instanceof Mob) { + Mob m = (Mob) e; + m.setAware(isAware()); + } + + if (spawnEffect != null) { + spawnEffect.apply(e); + } + + if (rawCommands.isNotEmpty()) { + final Location fat = at; + final PlatformWorld commandWorld = new BukkitWorld(fat.getWorld()); + rawCommands.forEach(r -> r.run(commandWorld, fat.getBlockX(), fat.getBlockY(), fat.getBlockZ())); + } + + Location finalAt1 = at; + + J.runEntity(e, () -> { + if (isSpawnEffectRiseOutOfGround() && e instanceof LivingEntity && Chunks.hasPlayersNearby(finalAt1)) { + LivingEntity living = (LivingEntity) e; + Location start = finalAt1.clone(); + boolean originalInvulnerable = e.isInvulnerable(); + boolean originalAi = living.hasAI(); + boolean originalCollidable = living.isCollidable(); + int originalNoDamageTicks = living.getNoDamageTicks(); + EntityRiseSVC.stamp(e, originalInvulnerable, originalAi, originalCollidable); + e.setInvulnerable(true); + living.setAI(false); + living.setCollidable(false); + living.setNoDamageTicks(100000); + Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi, + originalCollidable, originalNoDamageTicks); + AtomicInteger t = new AtomicInteger(0); + Runnable[] loop = new Runnable[1]; + loop[0] = () -> { + if (t.get() > 100 || e.isDead()) { + restore.run(); + return; + } + + t.incrementAndGet(); + if (e.getLocation().getBlock().getType().isSolid() || living.getEyeLocation().getBlock().getType().isSolid()) { + e.teleport(start.add(new Vector(0, 0.1, 0))); + ItemStack itemCrackData = new ItemStack(living.getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial()); + e.getWorld().spawnParticle(ITEM, living.getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData); + if (M.r(0.2)) { + e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f); + } + if (!J.runEntity(e, loop[0], 1, restore)) { + restore.run(); + } + } else { + restore.run(); + } + }; + if (!J.runEntity(e, loop[0], 0, restore)) { + restore.run(); + } + } + }); + + + return e; + } + + private static void restoreRiseState(Entity entity, LivingEntity living, boolean invulnerable, + boolean ai, boolean collidable, int noDamageTicks) { + living.setNoDamageTicks(noDamageTicks); + living.setCollidable(collidable); + living.setAI(ai); + entity.setInvulnerable(invulnerable); + EntityRiseSVC.clearStamp(entity); + } + + private int surfaceY(Location l) { + int m = l.getBlockY(); + + while (m-- > 0) { + Location ll = l.clone(); + ll.setY(m); + + if (ll.getBlock().getType().isSolid()) { + return m; + } + } + + return 0; + } + + private Entity doSpawn(Location at) { + if (!Chunks.isSafe(at)) { + return null; + } + + if (EntityType.UNKNOWN.equals(getBukkitType()) && !isSpecialType()) { + return null; + } + + if (!Bukkit.isPrimaryThread()) { + // Someone called spawn (worldedit maybe?) on a non server thread + // Due to the structure of iris, we will call it sync and busy wait until it's done. + AtomicReference ae = new AtomicReference<>(); + + try { + if (!J.runAt(at, () -> ae.set(doSpawn(at)))) { + return null; + } + } catch (Throwable e) { + return null; + } + PrecisionStopwatch p = PrecisionStopwatch.start(); + + while (ae.get() == null) { + J.sleep(25); + + if (p.getMilliseconds() > 500) { + return null; + } + } + + return ae.get(); + } + + if (isSpecialType()) { + return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(specialType)); + } + + + return BukkitPlatform.spawnEntity(at, getBukkitType(), getBukkitReason()); + } + + public boolean isSpecialType() { + return specialType != null && !specialType.equals(""); + } + + private static final class BukkitOps { + private static void persistVillager(Villager villager) { + villager.setPersistent(true); + } + + private static void bindLoot(IrisEntity entity, Engine gen, Lootable l, Location finalAt, RNG rng) { + l.setLootTable(new LootTable() { + @Override + public NamespacedKey getKey() { + return new NamespacedKey("iris", "loot-" + entity.hashCode()); + } + + @Override + public Collection populateLoot(Random random, LootContext context) { + KList items = new KList<>(); + + for (String fi : entity.getLoot().getTables()) { + IrisLootTable i = gen.getData().getLootLoader().load(fi); + items.addAll(i.getLoot(gen.isStudio(), gen.getSeedManager().getLoot(), InventorySlotType.STORAGE, finalAt.getWorld(), finalAt.getBlockX(), finalAt.getBlockY(), finalAt.getBlockZ())); + } + + return items; + } + + @Override + public void fillInventory(Inventory inventory, Random random, LootContext context) { + for (ItemStack i : populateLoot(random, context)) { + inventory.addItem(i); + } + + EngineBukkitOps.scramble(gen, inventory, rng); + } + }); + } + } + + @Override + public String getFolderName() { + return "entities"; + } + + @Override + public String getTypeName() { + return "Entity"; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java new file mode 100644 index 000000000..726b501b3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java @@ -0,0 +1,238 @@ +/* + * 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.entity; + +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.platform.bukkit.BukkitWorldBinding; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.object.annotations.Desc; +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.spi.IrisLogging; +import art.arcane.iris.util.common.format.C; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.math.Vector3d; +import art.arcane.volmlib.util.matter.MatterMarker; +import art.arcane.volmlib.util.matter.slices.MarkerMatter; +import art.arcane.iris.util.common.scheduling.J; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.Entity; + +@Snippet("entity-spawn") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents an entity spawn during initial chunk generation") +@Data +public class IrisEntitySpawn implements IRare { + private final transient AtomicCache rng = new AtomicCache<>(); + private final transient AtomicCache ent = new AtomicCache<>(); + @RegistryListResource(IrisEntity.class) + @Required + @Desc("The entity") + private String entity = ""; + @MinNumber(1) + @Desc("The 1 in RARITY chance for this entity to spawn") + private int rarity = 1; + @MinNumber(1) + @Desc("The minumum of this entity to spawn") + private int minSpawns = 1; + @MinNumber(1) + @Desc("The max of this entity to spawn") + private int maxSpawns = 1; + private transient IrisSpawner referenceSpawner; + private transient IrisMarker referenceMarker; + + public int spawn(Engine gen, Chunk c, RNG rng) { + int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns); + int s = 0; + + if (spawns > 0) { + for (int id = 0; id < spawns; id++) { + int x = (c.getX() * 16) + rng.i(16); + int z = (c.getZ() * 16) + rng.i(16); + World world = BukkitWorldBinding.tryBind(gen.getWorld()) ? BukkitWorldBinding.world(gen.getWorld()) : null; + int h = gen.getHeight(x, z, true) + (world == null ? -64 : world.getMinHeight()); + int hf = gen.getHeight(x, z, false) + (world == null ? -64 : world.getMinHeight()); + Location l = switch (getReferenceSpawner().getGroup()) { + case NORMAL -> new Location(c.getWorld(), x, hf + 1, z); + case CAVE -> findCaveSpawnLocation(gen, c, rng); + case UNDERWATER, BEACH -> new Location(c.getWorld(), x, rng.i(h + 1, hf), z); + }; + + if (l != null) { + if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { + if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { + if (spawn100(gen, l) != null) { + s++; + } + } + } else { + if (spawn100(gen, l) != null) { + s++; + } + } + } + } + } + + return s; + } + + public int spawn(Engine gen, IrisPosition c, RNG rng) { + int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns); + int s = 0; + + if (!BukkitWorldBinding.tryBind(gen.getWorld())) { + return 0; + } + + World world = BukkitWorldBinding.world(gen.getWorld()); + if (spawns > 0) { + + if (referenceMarker != null && referenceMarker.shouldExhaust()) { + if (J.isFolia()) { + J.a(() -> gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class)); + } else { + gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class); + } + } + + for (int id = 0; id < spawns; id++) { + Location l = BukkitPlatform.toLocation(c, world).add(0, 1, 0); + + if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { + if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { + if (spawn100(gen, l, true) != null) { + s++; + } + } + } else { + if (spawn100(gen, l, true) != null) { + s++; + } + } + } + } + + return s; + } + + public IrisEntity getRealEntity(Engine g) { + return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); + } + + public Entity spawn(Engine g, Location at) { + if (getRealEntity(g) == null) { + return null; + } + + if (LootResolver.oneIn(rng.aquire(() -> new RNG(g.getSeedManager().getEntity())), getRarity())) { + return spawn100(g, at); + } + + return null; + } + + static Location findCaveSpawnLocation(Engine engine, Chunk chunk, RNG rng) { + if (J.isFolia()) { + return null; + } + KList markers = engine.getMantle().findMarkers(chunk.getX(), chunk.getZ(), MarkerMatter.CAVE_FLOOR); + return selectCaveSpawnLocation(markers, chunk.getWorld(), rng); + } + + static Location selectCaveSpawnLocation(KList markers, World world, RNG rng) { + return markers.convert((marker) -> BukkitPlatform.toLocation(marker, world).add(0, 1, 0)).getRandom(rng); + } + + private Entity spawn100(Engine g, Location at) { + return spawn100(g, at, false); + } + + private Entity spawn100(Engine g, Location at, boolean ignoreSurfaces) { + try { + IrisEntity irisEntity = getRealEntity(g); + if (irisEntity == null) { // No entity + IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); + return null; + } + + if (!ignoreSurfaces && !irisEntity.getSurface().matches(at.clone().subtract(0, 1, 0).getBlock())) { + return null; + } + + Vector3d boundingBox = BukkitPlatform.entityBoundingBox(irisEntity.getBukkitType()); + if (!ignoreSurfaces && boundingBox != null) { + boolean isClearForSpawn = isAreaClearForSpawn(at, boundingBox); + if (!isClearForSpawn) { + return null; + } + } + + Entity e = irisEntity.spawn(g, at.add(0.5, 0.5, 0.5), rng.aquire(() -> new RNG(g.getSeedManager().getEntity()))); + if (e != null) { + IrisLogging.debug("Spawned " + C.DARK_AQUA + "Entity<" + getEntity() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ()); + } + + return e; + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.error(" Failed to retrieve real entity @ " + at + " (entity: " + getEntity() + ")"); + return null; + } + } + + private boolean isAreaClearForSpawn(Location center, Vector3d boundingBox) { + World world = center.getWorld(); + int startX = center.getBlockX() - (int) (boundingBox.x / 2); + int endX = center.getBlockX() + (int) (boundingBox.x / 2); + int startY = center.getBlockY(); + int endY = center.getBlockY() + (int) boundingBox.y; + int startZ = center.getBlockZ() - (int) (boundingBox.z / 2); + int endZ = center.getBlockZ() + (int) (boundingBox.z / 2); + + for (int x = startX; x <= endX; x++) { + for (int y = startY; y <= endY; y++) { + for (int z = startZ; z <= endZ; z++) { + if (world.getBlockAt(x, y, z).getType() != Material.AIR) { + return false; + } + } + } + } + return true; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java new file mode 100644 index 000000000..f837f5cfd --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java @@ -0,0 +1,102 @@ +/* + * 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.entity; + +import art.arcane.iris.engine.data.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.RegistryListPotionEffect; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.spi.IrisLogging; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor + +@Snippet("potion-effect") +@Desc("An iris potion effect") +@Data +public class IrisPotionEffect { + private final transient AtomicCache pt = new AtomicCache<>(); + @Required + @RegistryListPotionEffect + @Desc("The potion effect to apply in this area") + private String potionEffect = ""; + @Required + @MinNumber(-1) + @MaxNumber(1024) + @Desc("The Potion Strength or -1 to disable") + private int strength = -1; + @Required + @MinNumber(1) + @Desc("The time the potion will last for") + private int ticks = 200; + @Desc("Is the effect ambient") + private boolean ambient = false; + @Desc("Is the effect showing particles") + private boolean particles = true; + + public PotionEffectType getRealType() { + return pt.aquire(() -> + { + if (getPotionEffect() == null || getPotionEffect().isEmpty()) { + return PotionEffectType.LUCK; + } + + try { + PotionEffectType resolved = PotionEffectTypes.resolve(getPotionEffect()); + if (resolved != null) { + return resolved; + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + + if (PotionEffectTypes.shouldWarn(getPotionEffect())) { + IrisLogging.warn("Unknown Potion Effect Type: \"" + getPotionEffect() + "\". Valid types: " + PotionEffectTypes.knownTypesList()); + } + + return PotionEffectType.LUCK; + }); + } + + public void apply(LivingEntity p) { + if (strength > -1) { + if (p.hasPotionEffect(getRealType())) { + PotionEffect e = p.getPotionEffect(getRealType()); + if (e.getAmplifier() > strength) { + return; + } + + p.removePotionEffect(getRealType()); + } + + p.addPotionEffect(new PotionEffect(getRealType(), ticks, strength, ambient, particles, false)); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java b/src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java new file mode 100644 index 000000000..7d2a55222 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java @@ -0,0 +1,98 @@ +/* + * 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.entity; + +import art.arcane.iris.util.common.reflect.KeyedType; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.potion.PotionEffectType; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; + +public final class PotionEffectTypes { + private static final Map LEGACY_ALIASES; + private static final Set MISSING_WARNED = ConcurrentHashMap.newKeySet(); + + static { + Map m = new HashMap<>(); + m.put("SLOW", "SLOWNESS"); + m.put("FAST_DIGGING", "HASTE"); + m.put("SLOW_DIGGING", "MINING_FATIGUE"); + m.put("INCREASE_DAMAGE", "STRENGTH"); + m.put("HEAL", "INSTANT_HEALTH"); + m.put("HARM", "INSTANT_DAMAGE"); + m.put("JUMP", "JUMP_BOOST"); + m.put("CONFUSION", "NAUSEA"); + m.put("DAMAGE_RESISTANCE", "RESISTANCE"); + LEGACY_ALIASES = Collections.unmodifiableMap(m); + } + + private PotionEffectTypes() { + } + + public static String normalize(String input) { + if (input == null) { + return ""; + } + String upper = input.trim().toUpperCase(Locale.ROOT).replace(' ', '_'); + if (upper.contains(":")) { + upper = upper.substring(upper.indexOf(':') + 1); + } + return LEGACY_ALIASES.getOrDefault(upper, upper); + } + + public static PotionEffectType resolve(String rawName) { + if (rawName == null || rawName.trim().isEmpty()) { + return null; + } + String wanted = normalize(rawName); + for (PotionEffectType i : Registry.EFFECT) { + NamespacedKey key = KeyedType.getKey(i); + if (key == null) { + continue; + } + String candidate = key.getKey().toUpperCase(Locale.ROOT).replace(' ', '_'); + if (candidate.equals(wanted)) { + return i; + } + } + return null; + } + + public static String knownTypesList() { + TreeSet names = new TreeSet<>(); + for (PotionEffectType i : Registry.EFFECT) { + NamespacedKey key = KeyedType.getKey(i); + if (key != null) { + names.add(key.getKey().toUpperCase(Locale.ROOT).replace(' ', '_')); + } + } + return String.join(", ", names); + } + + public static boolean shouldWarn(String rawName) { + return MISSING_WARNED.add(normalize(rawName)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java new file mode 100644 index 000000000..2f1049b29 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java @@ -0,0 +1,38 @@ +/* + * 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.entity.spawn; + +import art.arcane.iris.engine.object.value.IrisRate; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.volmlib.util.math.M; +import lombok.Data; + +@Data +public class IrisEngineSpawnerCooldown { + private long lastSpawn = 0; + private String spawner; + + public void spawn(Engine engine) { + lastSpawn = M.ms(); + } + + public boolean canSpawn(IrisRate s) { + return M.ms() - lastSpawn > s.getInterval(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java new file mode 100644 index 000000000..20f8b65f1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java @@ -0,0 +1,36 @@ +/* + * 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.entity.spawn; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Terrain modes are used to decide the generator type currently used") +public enum IrisSpawnGroup { + @Desc("Spawns on the terrain surface") + NORMAL, + + @Desc("Spawns in cave-air and low light level areas") + CAVE, + + @Desc("Spawns underwater") + UNDERWATER, + + @Desc("Spawns in beaches") + BEACH +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java new file mode 100644 index 000000000..fdaad9401 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java @@ -0,0 +1,142 @@ +/* + * 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.entity.spawn; + +import art.arcane.iris.engine.object.entity.IrisEntitySpawn; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.engine.object.value.IrisRate; +import art.arcane.iris.engine.object.world.IrisTimeBlock; +import art.arcane.iris.engine.object.world.IrisWeather; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.core.loader.IrisRegistrant; +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.spi.PlatformWorld; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@EqualsAndHashCode(callSuper = true) +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents an entity spawn during initial chunk generation") +@Data +public class IrisSpawner extends IrisRegistrant { + + private transient IrisMarker referenceMarker; + + @ArrayType(min = 1, type = IrisEntitySpawn.class) + @Desc("The entity spawns to add") + private KList spawns = new KList<>(); + + @ArrayType(min = 1, type = IrisEntitySpawn.class) + @Desc("The entity spawns to add initially. EXECUTES PER CHUNK!") + private KList initialSpawns = new KList<>(); + + @Desc("This spawner will not spawn in a given chunk if that chunk has more than the defined amount of living entities.") + private int maxEntitiesPerChunk = 1; + + @Desc("The block of 24 hour time to contain this spawn in.") + private IrisTimeBlock timeBlock = new IrisTimeBlock(); + + @Desc("The weather condition required for this spawner to fire.") + private IrisWeather weather = IrisWeather.ANY; + + @Desc("The maximum rate this spawner can fire") + private IrisRate maximumRate = new IrisRate(); + + @Desc("The maximum rate this spawner can fire on a specific chunk") + private IrisRate maximumRatePerChunk = new IrisRate(); + + @Desc("The light levels this spawn is allowed to run in (0-15 inclusive)") + private IrisRange allowedLightLevels = new IrisRange(0, 15); + + @Desc("Where should these spawns be placed") + private IrisSpawnGroup group = IrisSpawnGroup.NORMAL; + + public boolean isValid(IrisBiome biome) { + return switch (group) { + case NORMAL -> switch (biome.getInferredType()) { + case SHORE, SEA, CAVE -> false; + case LAND -> true; + }; + case CAVE -> true; + case UNDERWATER -> switch (biome.getInferredType()) { + case SHORE, LAND, CAVE -> false; + case SEA -> true; + }; + case BEACH -> switch (biome.getInferredType()) { + case SHORE -> true; + case LAND, CAVE, SEA -> false; + }; + }; + } + + public boolean isValid(PlatformWorld world) { + return timeBlock.isWithin(world) && weather.is(world); + } + + public boolean canSpawn(Engine engine) { + PlatformWorld world = engine.getWorld().platformWorld(); + if (world == null || !isValid(world)) + return false; + + IrisRate rate = getMaximumRate(); + return rate.isInfinite() || engine.getEngineData().getCooldown(this).canSpawn(rate); + } + + public boolean canSpawn(Engine engine, int x, int z) { + if (!canSpawn(engine)) + return false; + + IrisRate rate = getMaximumRatePerChunk(); + return rate.isInfinite() || engine.getEngineData().getChunk(x, z).getCooldown(this).canSpawn(rate); + } + + public void spawn(Engine engine) { + if (getMaximumRate().isInfinite()) + return; + + engine.getEngineData().getCooldown(this).spawn(engine); + } + + public void spawn(Engine engine, int x, int z) { + spawn(engine); + if (getMaximumRatePerChunk().isInfinite()) + return; + + engine.getEngineData().getChunk(x, z).getCooldown(this).spawn(engine); + } + + @Override + public String getFolderName() { + return "spawners"; + } + + @Override + public String getTypeName() { + return "Spawner"; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java new file mode 100644 index 000000000..b53c9ee57 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java @@ -0,0 +1,34 @@ +package art.arcane.iris.engine.object.entity.spawn; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.volmlib.util.collection.KMap; +import lombok.EqualsAndHashCode; +import lombok.NonNull; + +@EqualsAndHashCode +public class IrisSpawnerCooldowns { + private final KMap cooldowns = new KMap<>(); + + public IrisEngineSpawnerCooldown getCooldown(@NonNull IrisSpawner spawner) { + return getCooldown(spawner.getLoadKey()); + } + + public IrisEngineSpawnerCooldown getCooldown(@NonNull String loadKey) { + return cooldowns.computeIfAbsent(loadKey, k -> { + IrisEngineSpawnerCooldown cd = new IrisEngineSpawnerCooldown(); + cd.setSpawner(loadKey); + return cd; + }); + } + + public void cleanup(Engine engine) { + cooldowns.values().removeIf(cd -> { + IrisSpawner sp = engine.getData().getSpawnerLoader().load(cd.getSpawner()); + return sp == null || cd.canSpawn(sp.getMaximumRate()); + }); + } + + public boolean isEmpty() { + return cooldowns.isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java new file mode 100644 index 000000000..5924802b6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java @@ -0,0 +1,68 @@ +/* + * 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.entity.spawn; + +import art.arcane.iris.engine.object.annotations.Desc; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.data.Waterlogged; + +@Desc("The type of surface entities should spawn on") +public enum IrisSurface { + + @Desc("Land surfaces") + LAND, + + @Desc("Any surfaces animals can spawn on, such as dirt, grass and podzol") + ANIMAL, + + @Desc("Within the water") + WATER, + + @Desc("On land or on water") + OVERWORLD, + + @Desc("Within lava") + LAVA; + + /** + * Check if this Iris surface matches the blockstate provided + * + * @param state The blockstate + * @return True if it matches + */ + public boolean matches(Block state) { + Material type = state.getType(); + if (type.isSolid()) { + return this == LAND || this == OVERWORLD || (this == ANIMAL + && (type == Material.GRASS_BLOCK || type == Material.DIRT + || type == Material.DIRT_PATH || type == Material.COARSE_DIRT + || type == Material.ROOTED_DIRT || type == Material.PODZOL + || type == Material.MYCELIUM || type == Material.SNOW_BLOCK)); + } + if (type == Material.LAVA) return this == LAVA; + if (type == Material.WATER || type == Material.SEAGRASS + || type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT + || type == Material.KELP || + (state instanceof Waterlogged && ((Waterlogged) state).isWaterlogged())) + return this == WATER || this == OVERWORLD; + + return false; + } +} 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 new file mode 100644 index 000000000..906f8d87b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImage.java @@ -0,0 +1,168 @@ +/* + * 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/IrisImageColorMode.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java new file mode 100644 index 000000000..0aecfc259 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java @@ -0,0 +1,9 @@ +package art.arcane.iris.engine.object.image; + +public enum IrisImageColorMode { + GRAYSCALE, + RGB, + RGBA, + INDEXED, + UNSUPPORTED +} 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 new file mode 100644 index 000000000..e28062058 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMap.java @@ -0,0 +1,120 @@ +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/IrisImageMapAlpha.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java new file mode 100644 index 000000000..338e2cd71 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java @@ -0,0 +1,11 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How alpha participates in decoded data") +public enum IrisImageMapAlpha { + IGNORE, + MASK, + TRANSPARENT_IS_FALLBACK, + ERROR +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java new file mode 100644 index 000000000..d7ad2e1f6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java @@ -0,0 +1,13 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The generation input controlled by an image map") +public enum IrisImageMapApplication { + TERRAIN_HEIGHT, + BIOME, + REGION, + SURFACE_BLOCK, + MASK, + CUSTOM +} 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 new file mode 100644 index 000000000..395ab2df1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapBinding.java @@ -0,0 +1,29 @@ +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/image/IrisImageMapMask.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java new file mode 100644 index 000000000..43ca5de04 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java @@ -0,0 +1,33 @@ +package art.arcane.iris.engine.object.image; + +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.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@Desc("A composable reference to a named MASK image map") +@Data +public class IrisImageMapMask { + @Desc("The key of a named imageMaps entry whose application is MASK") + private String map = ""; + + @Desc("How this mask combines with masks before it") + private IrisImageMapMaskOperation operation = IrisImageMapMaskOperation.MULTIPLY; + + @Desc("Invert this mask before combining it") + private boolean inverted = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Values below this threshold become zero") + private double threshold = 0D; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Soft transition width above threshold; zero is a hard edge") + private double falloff = 0D; +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java new file mode 100644 index 000000000..aa1708e83 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How a referenced mask combines with masks before it") +public enum IrisImageMapMaskOperation { + MULTIPLY, + MINIMUM, + MAXIMUM, + ADD, + SUBTRACT +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java new file mode 100644 index 000000000..fc2ee68a8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java @@ -0,0 +1,23 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@Desc("A two-dimensional image-map coordinate") +@Data +public class IrisImageMapOrigin { + @Desc("X coordinate in world blocks for origin, or source pixels for sourceOrigin") + private double x = 0D; + + @Desc("Z coordinate in world blocks for origin, or source image Y pixels for sourceOrigin") + private double z = 0D; + + public IrisImageMapOrigin(double x, double z) { + this.x = x; + this.z = z; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java new file mode 100644 index 000000000..a8bd749ae --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How coordinates outside an image are resolved") +public enum IrisImageMapOutOfBounds { + FALLBACK, + CLAMP, + REPEAT, + MIRROR, + ERROR +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java new file mode 100644 index 000000000..300c7c203 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java @@ -0,0 +1,11 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Clockwise image-map rotation around sourceOrigin") +public enum IrisImageMapRotation { + DEG_0, + DEG_90, + DEG_180, + DEG_270 +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java new file mode 100644 index 000000000..f215ab5f4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java @@ -0,0 +1,10 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The filter used between source pixels") +public enum IrisImageMapSampling { + NEAREST, + BILINEAR, + BICUBIC +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java new file mode 100644 index 000000000..64ad766f9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java @@ -0,0 +1,13 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How Iris decodes each source pixel") +public enum IrisImageMapType { + GRAYSCALE_HEIGHT, + RGB_HEIGHT, + COLOR_MAP, + BINARY_MASK, + GRAYSCALE_MASK, + ALPHA_MASK +} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java new file mode 100644 index 000000000..8d7e160b5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java @@ -0,0 +1,10 @@ +package art.arcane.iris.engine.object.image; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How a color absent from a color-map legend is handled") +public enum IrisImageMapUnknownColor { + ERROR, + FALLBACK, + IGNORE +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java new file mode 100644 index 000000000..07d0f6859 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java @@ -0,0 +1,14 @@ +package art.arcane.iris.engine.object.loot; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; + +public interface IObjectLoot { + KList getFilter(); + KList getFilter(IrisData manager); + boolean isExact(); + String getName(); + int getWeight(); +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java b/src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java new file mode 100644 index 000000000..574fc301f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java @@ -0,0 +1,38 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("An inventory slot type is used to represent a type of slot for items to fit into in any given inventory.") +public enum InventorySlotType { + @Desc("Typically the one you want to go with. Storage represnents most slots in inventories.") + STORAGE, + + @Desc("Used for the fuel slot in Furnaces, Blast furnaces, smokers etc.") + FUEL, + + @Desc("Used for the cook slot in furnaces") + FURNACE, + @Desc("Used for the cook slot in blast furnaces") + BLAST_FURNACE, + + @Desc("Used for the cook slot in smokers") + SMOKER, +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java new file mode 100644 index 000000000..fa2aa2f57 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java @@ -0,0 +1,92 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.LootResolver; +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.iris.engine.object.annotations.Snippet; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; +import org.bukkit.block.data.BlockData; +import org.bukkit.inventory.ItemStack; + +@Snippet("block-drops") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a block drop list") +@Data +public class IrisBlockDrops { + private final transient AtomicCache> data = new AtomicCache<>(); + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The blocks that drop loot") + private KList blocks = new KList<>(); + @Desc("If exact blocks is set to true, minecraft:barrel[axis=x] will only drop for that axis. When exact is false (default) any barrel will drop the defined drops.") + private boolean exactBlocks = false; + @Desc("Add in specific items to drop") + @ArrayType(min = 1, type = IrisLoot.class) + private KList drops = new KList<>(); + @Desc("If this is in a biome, setting skipParents to true will ignore the drops in the region and dimension for this block type. The default (false) will allow all three nodes to fire and add to a list of drops.") + private boolean skipParents = false; + @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") + private boolean replaceVanillaDrops = false; + + public boolean shouldDropFor(BlockData data, IrisData rdata) { + KList list = this.data.aquire(() -> { + KList b = new KList<>(); + + for (IrisBlockData i : getBlocks()) { + PlatformBlockState state = i.getBlockData(rdata); + + if (state != null) { + b.add((BlockData) state.nativeHandle()); + } + } + + return b.removeDuplicates(); + }); + + for (BlockData i : list) { + if (exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) { + return true; + } + } + + return false; + } + + public void fillDrops(boolean debug, KList d) { + for (IrisLoot i : getDrops()) { + if (LootResolver.oneIn(RNG.r, i.getRarity())) { + d.add(i.get(debug, RNG.r)); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java new file mode 100644 index 000000000..bd104ca0a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java @@ -0,0 +1,105 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.framework.LootResolver; +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.RegistryListEnchantment; +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.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.Locale; + + +@Snippet("enchantment") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents an enchantment & level") +@Data +public class IrisEnchantment { + @Required + @RegistryListEnchantment + @Desc("The enchantment") + private String enchantment; + + @MinNumber(1) + @Desc("Minimum amount of this loot") + private int minLevel = 1; + + @MinNumber(1) + @Desc("Maximum amount of this loot") + private int maxLevel = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance that this enchantment is applied (0 to 1)") + private double chance = 1; + + public void apply(RNG rng, ItemMeta meta) { + try { + Enchantment enchant = resolve(); + if (enchant == null) { + IrisLogging.warn("Unknown Enchantment: " + getEnchantment()); + return; + } + if (rng.nextDouble() < chance) { + if (meta instanceof EnchantmentStorageMeta) { + ((EnchantmentStorageMeta) meta).addStoredEnchant(enchant, getLevel(rng), true); + return; + } + meta.addEnchant(enchant, getLevel(rng), true); + } + } catch (Throwable e) { + IrisLogging.reportError(e); + + } + } + + /** + * Resolves the authored key against the live enchantment registry. Accepts a bare path + * ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}) - parity with the modded resolver. + */ + private Enchantment resolve() { + String raw = getEnchantment(); + if (raw == null || raw.isBlank()) { + return null; + } + String value = raw.trim().toLowerCase(Locale.ROOT).replace(' ', '_'); + NamespacedKey key = value.indexOf(':') >= 0 ? NamespacedKey.fromString(value) : NamespacedKey.minecraft(value); + return key == null ? null : Registry.ENCHANTMENT.get(key); + } + + public int getLevel(RNG rng) { + return LootResolver.inclusive(rng, getMinLevel(), getMaxLevel()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java new file mode 100644 index 000000000..8ad144f9c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java @@ -0,0 +1,297 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.object.entity.IrisAttributeModifier; +import art.arcane.iris.platform.bukkit.BukkitBlockResolution; + +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.core.link.Identifier; +import art.arcane.iris.core.service.ExternalDataSVC; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.LootResolver; +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.RegistryListItemType; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.iris.util.common.format.C; +import art.arcane.volmlib.util.format.Form; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.experimental.Accessors; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.components.CustomModelDataComponent; +import org.bukkit.material.Colorable; + +import java.awt.Color; +import java.util.List; +import java.util.Optional; + +@Snippet("loot") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a loot entry") +@Data +@EqualsAndHashCode(doNotUseGetters = true) +@ToString(doNotUseGetters = true) +public class IrisLoot { + public static final int MAX_AMOUNT = 64; + + private final transient AtomicCache dyeColorResolved = new AtomicCache<>(); + @Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.") + private InventorySlotType slotTypes = InventorySlotType.STORAGE; + @MinNumber(1) + @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") + private int rarity = 1; + @MinNumber(1) + @MaxNumber(MAX_AMOUNT) + @Desc("Minimum amount of this loot, from 1 to 64") + private int minAmount = 1; + @MinNumber(1) + @MaxNumber(MAX_AMOUNT) + @Desc("Maximum amount of this loot, from 1 to 64") + private int maxAmount = 1; + @MinNumber(1) + @Desc("The display name of this item") + private String displayName = null; + @MinNumber(0) + @MaxNumber(1) + @Desc("Minimum durability percent") + private double minDurability = 0; + @MinNumber(0) + @MaxNumber(1) + @Desc("Maximum durability percent") + private double maxDurability = 1; + @Desc("Define a custom model identifier 1.14+ only") + private Integer customModel = null; + @Desc("Set this to true to prevent it from being broken") + private boolean unbreakable = false; + @ArrayType(min = 1, type = String.class) + @Desc("The item flags to add") + private KList itemFlags = new KList<>(); + @Desc("Apply enchantments to this item") + @ArrayType(min = 1, type = IrisEnchantment.class) + private KList enchantments = new KList<>(); + @Desc("Apply attribute modifiers to this item") + @ArrayType(min = 1, type = IrisAttributeModifier.class) + private KList attributes = new KList<>(); + @ArrayType(min = 1, type = String.class) + @Desc("Add lore to this item") + private KList lore = new KList<>(); + @RegistryListItemType + @Required + @Desc("This is the item or block type. Does not accept minecraft:*, only materials such as DIAMOND_SWORD or DIRT. The exception are modded materials, as they require a namespace.") + private String type = ""; + @Desc("The dye color") + private String dyeColor = null; + @Desc("The leather armor color") + private String leatherColor = null; + @Desc("Defines a custom NBT Tag for the item.") + private KMap customNbt; + + public Material getType() { + return BukkitBlockResolution.getMaterial(type); + } + + /** + * The authored item key, exactly as written in the pack. Platform-neutral: {@link #getType()} resolves it against + * Bukkit, mod loaders resolve it against their own item registry. + */ + public String getTypeKey() { + return type; + } + + /** + * The authored dye colour name, or null when unset. Platform-neutral counterpart to {@link #getDyeColor()}. + */ + public String getDyeColorKey() { + return dyeColor; + } + + public DyeColor getDyeColor() { + if (dyeColor == null) { + return null; + } + return dyeColorResolved.aquire(() -> { + try { + return DyeColor.valueOf(dyeColor); + } catch (IllegalArgumentException e) { + return null; + } + }); + } + + private KList getResolvedItemFlags() { + KList resolved = new KList<>(); + for (String flag : itemFlags) { + if (flag == null) { + continue; + } + try { + resolved.add(ItemFlag.valueOf(flag)); + } catch (IllegalArgumentException ignored) { + } + } + return resolved; + } + + public ItemStack get(boolean debug, RNG rng) { + try { + ItemStack is = getItemStack(rng); + if (is == null) + return new ItemStack(Material.AIR); + is.setItemMeta(applyProperties(is, rng, debug, null)); + return BukkitPlatform.applyCustomNbt(is, customNbt); + } catch (Throwable e) { + IrisLogging.reportError(e); + return new ItemStack(Material.AIR); + } + } + + public ItemStack get(boolean debug, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, int x, int y, int z) { + long combinedRarity = LootResolver.combinedRarity(rarity, table.getRarity()); + if (!LootResolver.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { + return null; + } + + try { + ItemStack is = getItemStack(rng); + if (is == null) + return null; + is.setItemMeta(applyProperties(is, rng, debug, table)); + return BukkitPlatform.applyCustomNbt(is, customNbt); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + + return null; + } + + // TODO Better Third Party Item Acquisition + private ItemStack getItemStack(RNG rng) { + if (!type.startsWith("minecraft:") && type.contains(":")) { + Optional opt = IrisServices.get(ExternalDataSVC.class).getItemStack(Identifier.fromString(type), customNbt); + if (opt.isEmpty()) { + IrisLogging.warn("Unknown Material: " + type); + return new ItemStack(Material.AIR); + } + ItemStack is = opt.get(); + is.setAmount(Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount()))); + return is; + } + return new ItemStack(getType(), Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount()))); + } + + private ItemMeta applyProperties(ItemStack is, RNG rng, boolean debug, IrisLootTable table) { + ItemMeta m = is.getItemMeta(); + if (m == null) { + return null; + } + + for (IrisEnchantment i : getEnchantments()) { + i.apply(rng, m); + } + + for (IrisAttributeModifier i : getAttributes()) { + i.apply(rng, m); + } + + m.setUnbreakable(isUnbreakable()); + for (ItemFlag i : getResolvedItemFlags()) { + m.addItemFlags(i); + } + + if (getCustomModel() != null) { + CustomModelDataComponent customModelData = m.getCustomModelDataComponent(); + customModelData.setFloats(List.of(getCustomModel().floatValue())); + m.setCustomModelDataComponent(customModelData); + } + + if (is.getType().getMaxDurability() > 0 && m instanceof Damageable d) { + int max = is.getType().getMaxDurability(); + d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); + } + + if (getLeatherColor() != null && m instanceof LeatherArmorMeta leather) { + Color c = Color.decode(getLeatherColor()); + leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); + } + + if (getDyeColor() != null && m instanceof Colorable colorable) { + colorable.setColor(getDyeColor()); + } + + if (displayName != null) { + m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); + } + + KList lore = new KList<>(); + + getLore().forEach((i) -> + { + String mf = C.translateAlternateColorCodes('&', i); + + if (mf.length() > 24) { + for (String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { + lore.add(g.trim()); + } + } else { + lore.add(mf); + } + }); + + if (debug) { + if (table == null) { + if (lore.isNotEmpty()) { + lore.add(C.GRAY + "--------------------"); + } + lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")"); + } else { + if (lore.isNotEmpty()) { + lore.add(C.GRAY + "--------------------"); + } + + lore.add(C.GRAY + "From: " + table.getName() + " (" + Form.pc(1D / table.getRarity(), 5) + ")"); + lore.add(C.GRAY + "1 in " + (table.getRarity() * getRarity()) + " Chance (" + Form.pc(1D / (table.getRarity() * getRarity()), 5) + ")"); + } + } + + m.setLore(lore); + + return m; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java new file mode 100644 index 000000000..622d7f825 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java @@ -0,0 +1,33 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("A loot mode is used to describe what to do with the existing loot layers before adding this loot. ADD appends to the building list of tables (dimension tables, then region tables, then biome tables). REPLACE swaps the parent tables for this reference's tables. CLEAR suppresses loot entirely at this point.") +public enum IrisLootMode { + @Desc("Add to the existing parent loot tables") + ADD, + @Desc("Clear all parent loot tables and contribute nothing at this level. Any tables listed here are ignored.") + CLEAR, + @Desc("Replace all parent loot tables with this reference's tables") + REPLACE, + @Desc("Only use when there was no loot table defined by an object") + FALLBACK +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java new file mode 100644 index 000000000..c2e7b563f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java @@ -0,0 +1,68 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.data.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.Snippet; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.util.common.data.DataProvider; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("loot-registry") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a loot entry") +@Data +public class IrisLootReference { + public static final double MAX_MULTIPLIER = 16D; + + private final transient AtomicCache> tt = new AtomicCache<>(); + @Desc("ADD = add on top of parent tables. REPLACE = clear parent tables, then add these. CLEAR = clear parent tables and add nothing, even if tables are listed. FALLBACK = only used when nothing else defined a table.") + private IrisLootMode mode = IrisLootMode.ADD; + @RegistryListResource(IrisLootTable.class) + @ArrayType(min = 1, type = String.class) + @Desc("Add loot table registries here") + private KList tables = new KList<>(); + @MinNumber(0) + @MaxNumber(MAX_MULTIPLIER) + @Desc("Scale loot sources in this area from 0 to 16 times their normal count") + private double multiplier = 1D; + + public KList getLootTables(DataProvider g) { + return tt.aquire(() -> + { + KList t = new KList<>(); + + for (String i : tables) { + t.add(g.getData().getLootLoader().load(i)); + } + + return t; + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java new file mode 100644 index 000000000..ba9342ca5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java @@ -0,0 +1,115 @@ +/* + * 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.loot; + +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.engine.framework.LootResolver; +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.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.inventory.ItemStack; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a loot table. Biomes, Regions & Objects can add or replace the virtual table with these loot tables") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisLootTable extends IrisRegistrant { + public static final int MAX_PICKED = 64; + public static final int MAX_TRIES = 256; + + @Required + @Desc("The name of this loot table") + @MinNumber(2) + private String name = ""; + + @MinNumber(1) + @Desc("The rarity as in 1 in X chance") + private int rarity = 1; + + @MinNumber(1) + @MaxNumber(MAX_PICKED) + @Desc("The maximum amount of loot that can be picked in this table at a time, from 1 to 64") + private int maxPicked = 5; + + @MinNumber(0) + @MaxNumber(MAX_PICKED) + @Desc("The minimum amount of loot that can be picked in this table at a time, from 0 to 64") + private int minPicked = 1; + + @MinNumber(1) + @MaxNumber(MAX_TRIES) + @Desc("The maximum amount of tries to generate loot, from 1 to 256") + private int maxTries = 10; + + @Desc("The loot in this table") + @ArrayType(min = 1, type = IrisLoot.class) + private KList loot = new KList<>(); + + public KList getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) { + KList lootf = new KList<>(); + if (loot.isEmpty() || maxTries <= 0) { + return lootf; + } + + RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z); + int m = 0; + int c = 0; + int mx = Math.max(0, LootResolver.inclusive(rng, getMinPicked(), getMaxPicked())); + + while (m < mx && c++ < getMaxTries()) { + int num = rng.nextInt(loot.size()); + + IrisLoot l = loot.get(num); + + if (l != null && l.getSlotTypes() == slot) { + ItemStack item = l.get(debug, this, rng, lootSeed, num, x, y, z); + + if (item != null && item.getType() != Material.AIR) { + lootf.add(item); + m++; + } + } + } + + return lootf; + } + + @Override + public String getFolderName() { + return "loot"; + } + + @Override + public String getTypeName() { + return "Loot"; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java new file mode 100644 index 000000000..ec5b70e77 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java @@ -0,0 +1,82 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.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.B; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Snippet("object-loot") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents loot within this object") +@Data +public class IrisObjectLoot implements IObjectLoot { + private final transient AtomicCache> filterCache = new AtomicCache<>(); + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The list of blocks this loot table should apply to") + private KList filter = new KList<>(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The loot table name") + @Required + @RegistryListResource(IrisLootTable.class) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public KList getFilter(IrisData rdata) { + return filterCache.aquire(() -> + { + KList b = new KList<>(); + + for (IrisBlockData i : filter) { + PlatformBlockState bx = i.getBlockData(rdata); + + if (bx != null) { + b.add(bx); + } + } + + return b; + }); + } + + public boolean matchesFilter(IrisData manager, PlatformBlockState data) { + for (PlatformBlockState filterState : getFilter(manager)) { + if (B.matches(filterState, data)) return true; + } + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java new file mode 100644 index 000000000..3ca950d5a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java @@ -0,0 +1,57 @@ +package art.arcane.iris.engine.object.loot; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListFunction; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.annotations.functions.LootTableKeyFunction; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Snippet("object-vanilla-loot") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents vanilla loot within this object") +@Data +public class IrisObjectVanillaLoot implements IObjectLoot { + private final transient AtomicCache> filterCache = new AtomicCache<>(); + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The list of blocks this loot table should apply to") + private KList filter = new KList<>(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The vanilla loot table key") + @Required + @RegistryListFunction(LootTableKeyFunction.class) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public KList getFilter(IrisData rdata) { + return filterCache.aquire(() -> + { + KList b = new KList<>(); + + for (IrisBlockData i : filter) { + PlatformBlockState bx = i.getBlockData(rdata); + + if (bx != null) { + b.add(bx); + } + } + + return b; + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java new file mode 100644 index 000000000..c66c624f1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java @@ -0,0 +1,111 @@ +package art.arcane.iris.engine.object.loot; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.inventory.ItemStack; +import org.bukkit.loot.LootContext; +import org.bukkit.loot.LootTable; + +import java.io.File; + +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisVanillaLootTable extends IrisLootTable { + /** + * The vanilla loot table key ("minecraft:chests/simple_dungeon"), not the LootTable itself. A + * raw org.bukkit.loot.LootTable field - and the constructor lombok would generate for it - makes + * every reflective walk over the IrisLootTable hierarchy (Gson, schema generation, the purity + * gate) resolve a Bukkit class. The table is resolved lazily at pull time, which only ever + * happens on Bukkit. The key text is identical to what {@code LootTable.getKey().toString()} + * produced before, so {@code LootResolver.tableIdentity} (which falls back to + * {@link #getName()}) yields the same loot seed. + */ + private final String lootTableKey; + + /** + * The resolved table, looked up once. Every chest pull resolved it again - a NamespacedKey parse plus a registry + * lookup per container, and a dungeon room is a lot of containers. + *

+ * Transient for the same reason the field above is a String: it keeps the Bukkit type argument out of the Gson + * field walk and out of the pack purity gate, both of which resolve generic field types for the fields they visit. + */ + private final transient AtomicCache resolvedTable = new AtomicCache<>(); + + @Override + public String getName() { + return "Vanilla " + lootTableKey; + } + + @Override + public int getRarity() { + return 0; + } + + @Override + public int getMaxPicked() { + return 0; + } + + @Override + public int getMinPicked() { + return 0; + } + + @Override + public int getMaxTries() { + return 0; + } + + @Override + public KList getLoot() { + return new KList<>(); + } + + @Override + public KList getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) { + LootTable table = resolveTable(); + if (table == null) { + IrisLogging.warn("Unknown vanilla loot table " + lootTableKey); + return new KList<>(); + } + RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z); + return new KList<>(table.populateLoot(rng, new LootContext.Builder(new Location(world, x, y, z)).build())); + } + + private LootTable resolveTable() { + return resolvedTable.aquire(() -> { + NamespacedKey key = NamespacedKey.fromString(lootTableKey); + return key == null ? null : Bukkit.getLootTable(key); + }); + } + + @Override + public String getFolderName() { + throw new UnsupportedOperationException("VanillaLootTables do not have a folder name"); + } + + @Override + public String getTypeName() { + throw new UnsupportedOperationException("VanillaLootTables do not have a type name"); + } + + @Override + public File getLoadFile() { + throw new UnsupportedOperationException("VanillaLootTables do not have a load file"); + } + + @Override + public IrisData getLoader() { + throw new UnsupportedOperationException("VanillaLootTables do not have a loader"); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java new file mode 100644 index 000000000..f7e6cf5af --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java @@ -0,0 +1,86 @@ +/* + * 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.marker; + +import art.arcane.iris.engine.object.world.IrisTimeBlock; +import art.arcane.iris.engine.object.world.IrisWeather; +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.iris.engine.object.annotations.Snippet; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.collection.KList; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("command") +@Accessors(chain = true) +@NoArgsConstructor +@Desc("Represents a set of Iris commands") +@Data +public class IrisCommand { + + @Required + @ArrayType(min = 1, type = String.class) + @Desc("List of commands. Iris replaces {x} {y} and {z} with the location of the entity spawn") + private KList commands = new KList<>(); + + @Desc("The delay for running the command. Instant by default") + private long delay = 0; + + @Desc("If this should be repeated (indefinitely, cannot be cancelled). This does not persist with server-restarts, so it only repeats when the chunk is generated.") + private boolean repeat = false; + + @Desc("The delay between repeats, in server ticks (by default 100, so 5 seconds)") + private long repeatDelay = 100; + + @Desc("The block of 24 hour time in which the command should execute.") + private IrisTimeBlock timeBlock = new IrisTimeBlock(); + + @Desc("The weather that is required for the command to execute.") + private IrisWeather weather = IrisWeather.ANY; + + public boolean isValid(PlatformWorld world) { + return timeBlock.isWithin(world) && weather.is(world); + } + + public void run(PlatformWorld world, int x, int y, int z) { + if (!isValid(world)) { + return; + } + + for (String command : commands) { + command = (command.startsWith("/") ? command.replaceFirst("/", "") : command) + .replaceAll("\\Q{x}\\E", String.valueOf(x)) + .replaceAll("\\Q{y}\\E", String.valueOf(y)) + .replaceAll("\\Q{z}\\E", String.valueOf(z)); + final String finalCommand = command; + int safeDelay = (int) Math.max(0, Math.min(Integer.MAX_VALUE, delay)); + if (repeat) { + int safeRepeatDelay = (int) Math.max(1, Math.min(Integer.MAX_VALUE, repeatDelay)); + J.s(() -> J.sr(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeRepeatDelay), safeDelay); + } else { + J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeDelay); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java new file mode 100644 index 000000000..1d5ed6e25 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java @@ -0,0 +1,94 @@ +/* + * 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.marker; + +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.platform.bukkit.BukkitWorld; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +@Snippet("command-registry") +@Accessors(chain = true) +@NoArgsConstructor +@Desc("Represents a casting location for a command") +@Data +public class IrisCommandRegistry { + @Required + @ArrayType(min = 1, type = IrisCommand.class) + @Desc("Run commands, at the exact location of the player") + private KList rawCommands = new KList<>(); + @DependsOn({"rawCommands"}) + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetX = 0; + @DependsOn({"rawCommands"}) + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetY = 0; + @DependsOn({"rawCommands"}) + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetZ = 0; + @DependsOn({"rawCommands"}) + @Desc("Randomize the altX from -altX to altX") + private boolean commandRandomAltX = true; + @DependsOn({"rawCommands"}) + @Desc("Randomize the altY from -altY to altY") + private boolean commandRandomAltY = false; + @DependsOn({"rawCommands"}) + @Desc("Randomize the altZ from -altZ to altZ") + private boolean commandRandomAltZ = true; + @DependsOn({"rawCommands"}) + @Desc("Randomize location for all separate commands (true), or run all on the same location (false)") + private boolean commandAllRandomLocations = true; + + public void run(Player p) { + if (rawCommands.isNotEmpty()) { + PlatformWorld world = new BukkitWorld(p.getWorld()); + Location part = p.getLocation().clone().add( + commandRandomAltX ? RNG.r.d(-commandOffsetX, commandOffsetX) : commandOffsetX, + commandRandomAltY ? RNG.r.d(-commandOffsetY, commandOffsetY) : commandOffsetY, + commandRandomAltZ ? RNG.r.d(-commandOffsetZ, commandOffsetZ) : commandOffsetZ); + for (IrisCommand rawCommand : rawCommands) { + rawCommand.run(world, part.getBlockX(), part.getBlockY(), part.getBlockZ()); + if (commandAllRandomLocations) { + part = p.getLocation().clone().add( + commandRandomAltX ? RNG.r.d(-commandOffsetX, commandOffsetX) : commandOffsetX, + commandRandomAltY ? RNG.r.d(-commandOffsetY, commandOffsetY) : commandOffsetY, + commandRandomAltZ ? RNG.r.d(-commandOffsetZ, commandOffsetZ) : commandOffsetZ); + } + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java new file mode 100644 index 000000000..1cb419299 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java @@ -0,0 +1,68 @@ +/* + * 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.marker; + +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +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 art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@AllArgsConstructor +@NoArgsConstructor +@Desc("Represents a marker") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisMarker extends IrisRegistrant { + @Desc("A list of spawners to add to anywhere this marker is.") + @RegistryListResource(IrisSpawner.class) + @ArrayType(type = String.class, min = 1) + private KList spawners = new KList<>(); + + @Desc("Remove this marker when the block it's assigned to is changed.") + private boolean removeOnChange = true; + + @Desc("If true, markers will only be placed here if there is 2 air blocks above it.") + private boolean emptyAbove = true; + + @Desc("If this marker is used, what is the chance it removes itself. For example 25% (0.25) would mean that on average 4 uses will remove a specific marker. Set this below 0 (-1) to never exhaust & set this to 1 or higher to always exhaust on first use.") + private double exhaustionChance = 0; + + public boolean shouldExhaust() { + return exhaustionChance > RNG.r.nextDouble(); + } + + @Override + public String getFolderName() { + return "markers"; + } + + @Override + public String getTypeName() { + return "Marker"; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java new file mode 100644 index 000000000..580ce1212 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java @@ -0,0 +1,77 @@ +/* + * 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.marker; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.iris.engine.object.annotations.Snippet; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Snippet("object-marker") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Find blocks to mark") +@Data +public class IrisObjectMarker { + private final transient AtomicCache> findData = new AtomicCache<>(); + @ArrayType(min = 1, type = IrisBlockData.class) + @Required + @Desc("Find block types to mark") + private KList mark = new KList<>(); + @MinNumber(1) + @MaxNumber(16) + @Desc("The maximum amount of markers to place. Use these sparingly!") + private int maximumMarkers = 8; + @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") + private boolean exact = false; + @Required + @RegistryListResource(IrisMarker.class) + @Desc("The marker to add") + private String marker; + + public KList getMark(IrisData rdata) { + return findData.aquire(() -> + { + KList b = new KList<>(); + + for (IrisBlockData i : mark) { + PlatformBlockState bx = i.getBlockData(rdata); + + if (bx != null) { + b.add(bx); + } + } + + return b; + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java b/src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java new file mode 100644 index 000000000..44f27a422 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java @@ -0,0 +1,108 @@ +package art.arcane.iris.engine.object.marker; + +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.PlacementContext; +import art.arcane.iris.engine.object.placement.PlacementState; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.MatterMarker; + +import java.util.ArrayList; +import java.util.List; + +public class ObjectMarkerPlacement { + + private IrisObjectPlacement config; + private PlacementContext context; + private final IObjectPlacer placer; + private RNG markerRng; + List placements; + + public ObjectMarkerPlacement(PlacementContext context, PlacementState state) { + this.config = state.getConfig(); + this.placer = state.getPlacer(); + this.context = context; + this.markerRng = context.getRng().nextParallelRNG(((((long) context.getX()) << 32) | (context.getZ() & 0xFFFFFFFFL)) * 31L + context.getYv()); + this.placements = new ArrayList<>(); + } + + public void loadPossibleMarkers() { + // Marker selection persists into the mantle, so it must be seed-deterministic. + // Derive a side stream keyed on the placement position instead of consuming the + // caller's rng: consuming draws there would shift every later placement in the + // chunk and invalidate existing worlds/goldenhashes. + int index = 0; + for (IrisObjectMarker markerConfig : config.getMarkers()) { + IrisMarker marker = context.getSelf().getLoader().getMarkerLoader().load(markerConfig.getMarker()); + int markerSalt = index++; + if (marker != null) { + placements.add(new ObjectMarkerPlacement.MarkerPlacement(markerConfig, marker, + markerConfig.getMark(context.getRdata()), markerSalt)); + } + } + } + + public List matchMarkers(PlatformBlockState state) { + List matching = new ArrayList<>(); + for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : placements) { + if (markerPlacement.matches(state)) { + matching.add(markerPlacement); + } + } + return matching; + } + + public void placeMarkers() { + for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : placements) { + int max = markerPlacement.config.getMaximumMarkers(); + for (BlockPosition position : markerPlacement.candidates + .shuffleCopy(markerRng.nextParallelRNG(markerPlacement.salt))) { + if (max <= 0) { + break; + } + + boolean firstAboveAir = B.isAir(placer.get(position.getX(), position.getY() + 1, position.getZ())); + boolean secondAboveAir = B.isAir(placer.get(position.getX(), position.getY() + 2, position.getZ())); + if (!markerPlacement.marker.isEmptyAbove() || (firstAboveAir && secondAboveAir)) { + placer.setData(position.getX(), position.getY(), position.getZ(), + new MatterMarker(markerPlacement.config.getMarker())); + max--; + } + } + } + + } + + public static final class MarkerPlacement { + public final IrisObjectMarker config; + public final IrisMarker marker; + public final Iterable targets; + public final int salt; + public final KList candidates = new KList<>(); + + public MarkerPlacement(IrisObjectMarker config, IrisMarker marker, + Iterable targets, int salt) { + this.config = config; + this.marker = marker; + this.targets = targets; + this.salt = salt; + } + + public boolean matches(PlatformBlockState state) { + for (PlatformBlockState target : targets) { + if (config.isExact() + ? target.matches(state) + : IrisObjectShaping.materialKey(target).equals(IrisObjectShaping.materialKey(state))) { + return true; + } + } + return false; + } + } + +} 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 new file mode 100644 index 000000000..109117b0f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/material/BlockDataMergeSupport.java @@ -0,0 +1,75 @@ +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 new file mode 100644 index 000000000..472433247 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java @@ -0,0 +1,237 @@ +/* + * 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.iris.engine.data.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 new file mode 100644 index 000000000..1434f9d2d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java @@ -0,0 +1,203 @@ +/* + * 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.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.data.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 new file mode 100644 index 000000000..48968bcfc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java @@ -0,0 +1,120 @@ +/* + * 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.IrisObjectReplace; +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 = IrisObjectReplace.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 new file mode 100644 index 000000000..2488a6987 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeInjector.java @@ -0,0 +1,51 @@ +/* + * 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 new file mode 100644 index 000000000..3a1553c4a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeReplacer.java @@ -0,0 +1,50 @@ +/* + * 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 new file mode 100644 index 000000000..ec251a343 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModNoiseStyleReplacer.java @@ -0,0 +1,49 @@ +/* + * 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 new file mode 100644 index 000000000..aaa0c4fe2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementBiomeInjector.java @@ -0,0 +1,50 @@ +/* + * 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 new file mode 100644 index 000000000..0fe2601f2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementRegionInjector.java @@ -0,0 +1,50 @@ +/* + * 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 new file mode 100644 index 000000000..b4893f272 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectReplacer.java @@ -0,0 +1,50 @@ +/* + * 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 new file mode 100644 index 000000000..c8088ce8a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisModRegionReplacer.java @@ -0,0 +1,50 @@ +/* + * 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 new file mode 100644 index 000000000..a6245d290 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java @@ -0,0 +1,278 @@ +/* + * 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.iris.engine.data.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 new file mode 100644 index 000000000..deaf94468 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisInterpolator.java @@ -0,0 +1,84 @@ +/* + * 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 new file mode 100644 index 000000000..a65c2da3e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java @@ -0,0 +1,212 @@ +/* + * 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.data.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 new file mode 100644 index 000000000..ce23ad862 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisShapedGeneratorStyle.java @@ -0,0 +1,85 @@ +/* + * 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 new file mode 100644 index 000000000..4ac0beb53 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisStyledRange.java @@ -0,0 +1,72 @@ +/* + * 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 new file mode 100644 index 000000000..402bae799 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/NoiseStyle.java @@ -0,0 +1,566 @@ +/* + * 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 new file mode 100644 index 000000000..fdb76bad9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpression.java @@ -0,0 +1,138 @@ +/* + * 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.iris.engine.data.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 new file mode 100644 index 000000000..296d3b356 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionFunction.java @@ -0,0 +1,110 @@ +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 new file mode 100644 index 000000000..4e3af17eb --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionLoad.java @@ -0,0 +1,187 @@ +/* + * 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.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.data.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 new file mode 100644 index 000000000..5a6eb97ec --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/DecayControlPlacer.java @@ -0,0 +1,108 @@ +/* + * 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 new file mode 100644 index 000000000..6c9b80444 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/FloatingObjectFootprint.java @@ -0,0 +1,171 @@ +/* + * 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 new file mode 100644 index 000000000..5ba258d83 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java @@ -0,0 +1,63 @@ +/* + * 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 new file mode 100644 index 000000000..2993767c5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IPostBlockAccess.java @@ -0,0 +1,38 @@ +/* + * 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/IrisObjectLimit.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectLimit.java new file mode 100644 index 000000000..71bcaab65 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectLimit.java @@ -0,0 +1,50 @@ +/* + * 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.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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("object-limit") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Limits object placement by minimum and maximum world height") +@Data +public class IrisObjectLimit { + @MinNumber(-2048) + @MaxNumber(2048) + @Desc("The minimum height for placement (bottom of object)") + private int minimumHeight = -2048; + + @MinNumber(-2048) + @MaxNumber(2048) + @Desc("The maximum height for placement (top of object)") + private int maximumHeight = 2048; + + public boolean canPlace(int h, int l) { + return h <= maximumHeight && l >= minimumHeight; + } +} 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 new file mode 100644 index 000000000..3845ec97b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -0,0 +1,451 @@ +/* + * 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.loot.IObjectLoot; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.loot.IrisObjectLoot; +import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; +import art.arcane.iris.engine.object.loot.IrisVanillaLootTable; +import art.arcane.iris.engine.object.marker.IrisObjectMarker; +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.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveAnchorMode; +import art.arcane.iris.platform.bukkit.BukkitBlockResolution; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.data.cache.LazyBoundedCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +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.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.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.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.TreeType; +import org.bukkit.block.data.BlockData; +import org.jetbrains.annotations.Nullable; + +import java.util.Optional; +import java.util.function.Function; + +@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 IrisObjectLimit clamp = new IrisObjectLimit(); + @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 IrisSlopeClip slopeCondition = new IrisSlopeClip(); + @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 IrisStiltSettings stiltSettings; + @Desc("When a VACUUM place mode is used, this defines the deformation radius and falloff.") + private IrisVacuumSettings 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 = IrisObjectMarker.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 IrisCaveAnchorMode caveAnchorMode = IrisCaveAnchorMode.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 = IrisObjectReplace.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 = IrisObjectLoot.class) + @Desc("The loot tables to apply to these objects") + private KList loot = new KList<>(); + @ArrayType(min = 1, type = IrisObjectVanillaLoot.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 = IrisTree.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; + private transient AtomicCache cache = new AtomicCache<>(); + + 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); + 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()))); + } + + public boolean matches(IrisTreeSize size, TreeType type) { + for (IrisTree i : getTrees()) { + if (i.matches(size, type)) { + 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 TableCache getCache(IrisData manager) { + return cache.aquire(() -> { + TableCache cache = new TableCache(); + + cache.merge(getCache(manager, getVanillaLoot(), IrisObjectPlacement::getVanillaTable)); + cache.merge(getCache(manager, getLoot(), manager.getLootLoader()::load)); + + return cache; + }); + } + + private TableCache getCache(IrisData manager, KList list, Function loader) { + TableCache tc = new TableCache(); + + for (IObjectLoot loot : list) { + if (loot == null || loot.getWeight() <= 0) + continue; + IrisLootTable table = loader.apply(loot.getName()); + if (table == null) { + IrisLogging.warn("Couldn't find loot table " + loot.getName()); + continue; + } + + if (loot.getFilter().isEmpty()) //Table applies to all containers + { + tc.global.put(table, loot.getWeight()); + } else if (!loot.isExact()) //Table is meant to be by type + { + for (PlatformBlockState filterState : loot.getFilter(manager)) { + BlockData filterData = (BlockData) filterState.nativeHandle(); + if (!tc.basic.containsKey(filterData.getMaterial())) { + tc.basic.put(filterData.getMaterial(), new WeightedTables()); + } + + tc.basic.get(filterData.getMaterial()).put(table, loot.getWeight()); + } + } else //Filter is exact + { + for (PlatformBlockState filterState : loot.getFilter(manager)) { + BlockData filterData = (BlockData) filterState.nativeHandle(); + if (!tc.exact.containsKey(filterData.getMaterial())) { + tc.exact.put(filterData.getMaterial(), new KMap<>()); + } + + if (!tc.exact.get(filterData.getMaterial()).containsKey(filterData)) { + tc.exact.get(filterData.getMaterial()).put(filterData, new WeightedTables()); + } + + tc.exact.get(filterData.getMaterial()).get(filterData).put(table, loot.getWeight()); + } + } + } + return tc; + } + + @Nullable + private static IrisVanillaLootTable getVanillaTable(String name) { + return Optional.ofNullable(NamespacedKey.fromString(name)) + .map(Bukkit::getLootTable) + // Hand over the key, not the LootTable: IrisVanillaLootTable holds no Bukkit fields. + .map(table -> new IrisVanillaLootTable(String.valueOf(table.getKey()))) + .orElse(null); + } + + /** + * Gets the loot table that should be used for the block + * + * @param state The block state of the block + * @param dataManager Iris Data Manager + * @return The loot table it should use. + */ + public IrisLootTable getTable(PlatformBlockState state, IrisData dataManager, RNG rng) { + TableCache cache = getCache(dataManager); + BlockData data = (BlockData) state.nativeHandle(); + if (BukkitBlockResolution.isStorageChest(data)) { + IrisLootTable picked = null; + if (cache.exact.containsKey(data.getMaterial()) && cache.exact.get(data.getMaterial()).containsKey(data)) { + picked = cache.exact.get(data.getMaterial()).get(data).pullRandom(rng); + } else if (cache.basic.containsKey(data.getMaterial())) { + picked = cache.basic.get(data.getMaterial()).pullRandom(rng); + } else if (!cache.global.isEmpty()) { + picked = cache.global.pullRandom(rng); + } + + return picked; + } + + return null; + } + + 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); + } + } + + private static class TableCache { + final transient WeightedTables global = new WeightedTables(); + final transient KMap basic = new KMap<>(); + final transient KMap> exact = new KMap<>(); + + private void merge(TableCache other) { + global.merge(other.global); + basic.merge(other.basic, WeightedTables::merge); + exact.merge(other.exact, (a, b) -> a.merge(b, WeightedTables::merge)); + } + } + + private static final class WeightedTables { + private final KList tables = new KList<>(); + + private void put(IrisLootTable table, int weight) { + tables.add(new WeightedTable(table, weight)); + } + + private IrisLootTable pullRandom(RNG rng) { + WeightedTable picked = LootResolver.pickWeighted(tables, WeightedTable::weight, rng); + return picked == null ? null : picked.table(); + } + + private boolean isEmpty() { + return tables.isEmpty(); + } + + private WeightedTables merge(WeightedTables other) { + tables.addAll(other.tables); + return this; + } + } + + private record WeightedTable(IrisLootTable table, int weight) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java new file mode 100644 index 000000000..c9dae93a5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java @@ -0,0 +1,43 @@ +/* + * 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 art.arcane.iris.engine.object.terrain.carving.CarveResult; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.RNG; + +import java.util.function.BiConsumer; + +/** Entry point for executing an engine's resolved placement plan. */ +public final class IrisObjectPlacementRunner { + private final IrisObject self; + + public IrisObjectPlacementRunner(IrisObject self) { + this.self = self; + } + + public int place(int x, int yv, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, + BiConsumer listener, CarveResult cave, IrisData data) { + PlacementContext context = new PlacementContext(config, data, placer, cave, rng, self, x, z, yv, listener); + return PlacementLifecycles.forPlacer(placer).get(config.getMode()).execute(context).heightOrRejected(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java new file mode 100644 index 000000000..0ba26ca28 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java @@ -0,0 +1,84 @@ +/* + * 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.material.IrisBlockData; +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.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.noise.CNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Snippet("object-block-replacer") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Find and replace object materials") +@Data +public class IrisObjectReplace { + private final transient AtomicCache replaceGen = new AtomicCache<>(); + private final transient AtomicCache> findData = new AtomicCache<>(); + private final transient AtomicCache> replaceData = new AtomicCache<>(); + @ArrayType(min = 1, type = IrisBlockData.class) + @Required + @Desc("Find this block") + private KList find = new KList<>(); + @Required + @Desc("Replace it with this block palette") + private IrisMaterialPalette replace = new IrisMaterialPalette(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @MinNumber(0) + @MaxNumber(1) + @Desc("Modifies the chance the block is replaced") + private float chance = 1; + + public KList getFind(IrisData rdata) { + return findData.aquire(() -> + { + KList b = new KList<>(); + + for (IrisBlockData i : find) { + PlatformBlockState bx = i.getBlockData(rdata); + + if (bx != null) { + b.add(bx); + } + } + + return b; + }); + } + + public PlatformBlockState getReplace(RNG seed, double x, double y, double z, IrisData rdata) { + return getReplace().get(seed, x, y, z, rdata); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java new file mode 100644 index 000000000..57a0fb223 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -0,0 +1,137 @@ +/* + * 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; + +public final class IrisObjectVacuum { + private static final double DEFAULT_WAVE_AMPLITUDE = 3.0; + private static final double DEFAULT_WAVE_SCALE = 5.0; + + private IrisObjectVacuum() { + } + + public static boolean isVacuumMode(ObjectPlaceMode mode) { + return mode == ObjectPlaceMode.VACUUM + || mode == ObjectPlaceMode.VACUUM_HIGH + || mode == ObjectPlaceMode.VACUUM_FAST + || mode == ObjectPlaceMode.VACUUM_ORGANIC + || mode == ObjectPlaceMode.VACUUM_WAVY; + } + + public static int resolveRadius(ObjectPlaceMode mode, IrisVacuumSettings settings) { + int radius = switch (mode) { + case VACUUM_HIGH -> 20; + case VACUUM_FAST -> 8; + default -> 12; + }; + if (settings != null && settings.getRadius() > 0) { + radius = settings.getRadius(); + } + return Math.max(0, radius); + } + + public static int resolveStep(ObjectPlaceMode mode) { + return mode == ObjectPlaceMode.VACUUM_FAST ? 2 : 1; + } + + public static double resolveFalloff(IrisVacuumSettings settings) { + return settings != null ? Math.max(0.25, settings.getFalloff()) : 2.0; + } + + public static double resolveWaveAmplitude(IrisVacuumSettings settings) { + if (settings == null) { + return DEFAULT_WAVE_AMPLITUDE; + } + return Math.max(0, settings.getWaveAmplitude()); + } + + public static double resolveWaveScale(IrisVacuumSettings settings) { + if (settings == null) { + return DEFAULT_WAVE_SCALE; + } + double scale = settings.getWaveScale(); + return scale > 0 ? scale : DEFAULT_WAVE_SCALE; + } + + public static int footprintLow(int dimension) { + int size = Math.abs(dimension); + return -(size / 2); + } + + public static int footprintHigh(int dimension) { + int size = Math.abs(dimension); + if (size <= 0) { + return 0; + } + return size - (size / 2) - 1; + } + + public static int outset(int delta, int low, int high) { + if (delta < low) { + return low - delta; + } + if (delta > high) { + return delta - high; + } + return 0; + } + + public static int columnTargetY(int dx, int dz, int lowX, int highX, int lowZ, int highZ, + double effectiveRadius, double falloff, int originalY, int meetY) { + double factor = columnInfluence( + dx, dz, lowX, highX, lowZ, highZ, effectiveRadius, falloff); + return (int) Math.round(originalY + (((double) meetY - originalY) * factor)); + } + + public static double columnInfluence(int dx, int dz, int lowX, int highX, int lowZ, int highZ, + double effectiveRadius, double falloff) { + int outX = outset(dx, lowX, highX); + int outZ = outset(dz, lowZ, highZ); + double distance = Math.sqrt((double) outX * outX + (double) outZ * outZ); + if (effectiveRadius <= 0) { + return distance <= 0 ? 1.0 : 0.0; + } + if (distance >= effectiveRadius) { + return 0.0; + } + double t = 1.0 - (distance / effectiveRadius); + if (t <= 0) { + return 0.0; + } + return Math.pow(t, Math.max(0.25, falloff)); + } + + public static int waveOffset(double distance, double effectiveRadius, double signedNoise, double amplitude) { + if (amplitude <= 0 || effectiveRadius <= 0) { + return 0; + } + if (distance <= 0 || distance >= effectiveRadius) { + return 0; + } + double envelope = Math.sin(Math.PI * (distance / effectiveRadius)); + return (int) Math.round(signedNoise * amplitude * envelope); + } + + public static int carveFloorY(int targetY, int objectTopY, boolean insideFootprint) { + int floor = targetY + 1; + if (insideFootprint) { + floor = Math.max(floor, objectTopY + 1); + } + return floor; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java new file mode 100644 index 000000000..22c7860fa --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java @@ -0,0 +1,59 @@ +/* + * 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.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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("slope-clip") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Limits placement to a minimum and maximum terrain slope") +@Data +public class IrisSlopeClip { + @MinNumber(0) + @MaxNumber(1024) + @Desc("The minimum slope for placement") + private double minimumSlope = 0; + + @MinNumber(0) + @MaxNumber(1024) + @Desc("The maximum slope for placement") + private double maximumSlope = 10; + + public boolean isDefault() { + return minimumSlope <= 0 && maximumSlope >= 10; + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean isValid(double slope) { + if (isDefault()) { + return true; + } + + return !(minimumSlope > slope) && !(maximumSlope < slope); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java new file mode 100644 index 000000000..c9245aba8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java @@ -0,0 +1,47 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("stilt-settings") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Defines stilting behaviour.") +@Data +public class IrisStiltSettings { + @MinNumber(0) + @MaxNumber(64) + @Desc("Defines the maximum amount of blocks the object stilts verticially before overstilting and randomRange.") + private int yMax; + @MinNumber(0) + @MaxNumber(64) + @Desc("Defines the upper boundary for additional blocks after overstilting and/or maxStiltRange.") + private int yRand; + @MaxNumber(64) + @MinNumber(0) + @Desc("If the place mode is set to stilt, you can over-stilt it even further into the ground. Especially useful when using fast stilt due to inaccuracies.") + private int overStilt; + @Desc("If defined, stilting will be done using this block palette rather than the last layer of the object.") + private IrisMaterialPalette palette; + @MinNumber(1) + @MaxNumber(256) + @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks to scan toward the cave floor (or ceiling) looking for solid ground before giving up.") + private int organicMaxScan = 48; + @MinNumber(0) + @MaxNumber(32) + @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks each column's stilt is randomly shortened by, giving the underside a ragged organic edge instead of a flat disc.") + private int organicJitter = 3; + @MinNumber(0) + @MaxNumber(1) + @Desc("For ORGANIC_STILT / CEILING_HANG: in the deepest fraction of each stilt column, blocks are randomly skipped to break the tip up. Higher = more broken and scratchy. 0 disables.") + private double organicScratch = 0.55; + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java new file mode 100644 index 000000000..d8fce21f7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java @@ -0,0 +1,203 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.util.common.math.IrisBlockVector; + +import java.util.Arrays; +import java.util.List; + +/** + * Hard gate for surface-anchored object and tree placement: every column under the object's lowest solid + * layer, plus a buffer ring, must be solid un-carved ground for the required depth. Anything else floats + * over or bridges a carved hole, so the placement is skipped. + */ +public final class IrisSurfaceSupport { + private static final int MAX_STENCIL_CELLS = 1 << 22; + private static final ThreadLocal STENCIL = ThreadLocal.withInitial(Stencil::new); + + private IrisSurfaceSupport() { + } + + public static boolean isUnsupported(IObjectPlacer placer, IrisData data, int x, int z, + IrisObjectTranslate translate, IrisObjectRotation rotation, + int spinX, int spinY, int spinZ, + List supportOffsets, int buffer, int minSolidDepth) { + Stencil stencil = STENCIL.get(); + if (!stencil.build(supportOffsets, translate, rotation, spinX, spinY, spinZ, Math.max(0, buffer))) { + return true; + } + return stencil.anyColumnUnsupported(placer, data, x, z, Math.max(1, minSolidDepth)); + } + + private static IrisBlockVector transform(IrisBlockVector offset, IrisObjectTranslate translate, + IrisObjectRotation rotation, int spinX, int spinY, int spinZ) { + IrisBlockVector transformed = offset.clone(); + if (rotation != null) { + transformed = rotation.rotate(transformed, spinX, spinY, spinZ); + } + if (translate == null) { + return transformed; + } + return rotation == null + ? translate.translate(transformed) + : translate.translate(transformed, rotation, spinX, spinY, spinZ); + } + + /** + * Rasterized footprint reused per thread. Overlapping support offsets collapse into one cell here so + * each unique column is sampled once no matter how large the buffer is. + */ + private static final class Stencil { + private int[] offsetX = new int[64]; + private int[] offsetZ = new int[64]; + private boolean[] cells = new boolean[0]; + private boolean[] dilateScratch = new boolean[0]; + private int minX; + private int minZ; + private int width; + private int depth; + private int centerX; + private int centerZ; + + private boolean build(List supportOffsets, IrisObjectTranslate translate, + IrisObjectRotation rotation, int spinX, int spinY, int spinZ, int buffer) { + boolean originOnly = supportOffsets == null || supportOffsets.isEmpty(); + int count = originOnly ? 1 : supportOffsets.size(); + if (offsetX.length < count) { + offsetX = new int[count]; + offsetZ = new int[count]; + } + + int lowX = Integer.MAX_VALUE; + int highX = Integer.MIN_VALUE; + int lowZ = Integer.MAX_VALUE; + int highZ = Integer.MIN_VALUE; + for (int i = 0; i < count; i++) { + IrisBlockVector source = originOnly ? new IrisBlockVector(0, 0, 0) : supportOffsets.get(i); + IrisBlockVector transformed = transform(source, translate, rotation, spinX, spinY, spinZ); + int transformedX = transformed.getBlockX(); + int transformedZ = transformed.getBlockZ(); + offsetX[i] = transformedX; + offsetZ[i] = transformedZ; + lowX = Math.min(lowX, transformedX); + highX = Math.max(highX, transformedX); + lowZ = Math.min(lowZ, transformedZ); + highZ = Math.max(highZ, transformedZ); + } + + minX = lowX - buffer; + minZ = lowZ - buffer; + width = (highX - lowX + 1) + (buffer * 2); + depth = (highZ - lowZ + 1) + (buffer * 2); + long area = (long) width * (long) depth; + if (area <= 0L || area > MAX_STENCIL_CELLS) { + return false; + } + + int size = (int) area; + if (cells.length < size) { + cells = new boolean[size]; + dilateScratch = new boolean[size]; + } + Arrays.fill(cells, 0, size, false); + for (int i = 0; i < count; i++) { + cells[((offsetX[i] - minX) * depth) + (offsetZ[i] - minZ)] = true; + } + if (buffer > 0) { + dilate(buffer, size); + } + + int anchorX = -minX; + int anchorZ = -minZ; + centerX = anchorX >= 0 && anchorX < width ? anchorX : width / 2; + centerZ = anchorZ >= 0 && anchorZ < depth ? anchorZ : depth / 2; + return true; + } + + /** Chebyshev dilation, run as two separable passes so a wide buffer stays linear in footprint size. */ + private void dilate(int buffer, int size) { + Arrays.fill(dilateScratch, 0, size, false); + for (int sourceX = 0; sourceX < width; sourceX++) { + int base = sourceX * depth; + int fromX = Math.max(0, sourceX - buffer); + int toX = Math.min(width - 1, sourceX + buffer); + for (int sourceZ = 0; sourceZ < depth; sourceZ++) { + if (!cells[base + sourceZ]) { + continue; + } + for (int targetX = fromX; targetX <= toX; targetX++) { + dilateScratch[(targetX * depth) + sourceZ] = true; + } + } + } + + Arrays.fill(cells, 0, size, false); + for (int sourceX = 0; sourceX < width; sourceX++) { + int base = sourceX * depth; + for (int sourceZ = 0; sourceZ < depth; sourceZ++) { + if (!dilateScratch[base + sourceZ]) { + continue; + } + int fromZ = Math.max(0, sourceZ - buffer); + int toZ = Math.min(depth - 1, sourceZ + buffer); + for (int targetZ = fromZ; targetZ <= toZ; targetZ++) { + cells[base + targetZ] = true; + } + } + } + } + + /** Centre-outward so the common failure, a hole right under the anchor, costs one column. */ + private boolean anyColumnUnsupported(IObjectPlacer placer, IrisData data, int x, int z, int minSolidDepth) { + int maxRing = Math.max( + Math.max(centerX, width - 1 - centerX), + Math.max(centerZ, depth - 1 - centerZ)); + for (int ring = 0; ring <= maxRing; ring++) { + if (ring == 0) { + if (isColumnUnsupported(placer, data, x, z, centerX, centerZ, minSolidDepth)) { + return true; + } + continue; + } + + int lowX = centerX - ring; + int highX = centerX + ring; + int lowZ = centerZ - ring; + int highZ = centerZ + ring; + for (int sx = lowX; sx <= highX; sx++) { + if (isColumnUnsupported(placer, data, x, z, sx, lowZ, minSolidDepth) + || isColumnUnsupported(placer, data, x, z, sx, highZ, minSolidDepth)) { + return true; + } + } + for (int sz = lowZ + 1; sz < highZ; sz++) { + if (isColumnUnsupported(placer, data, x, z, lowX, sz, minSolidDepth) + || isColumnUnsupported(placer, data, x, z, highX, sz, minSolidDepth)) { + return true; + } + } + } + return false; + } + + private boolean isColumnUnsupported(IObjectPlacer placer, IrisData data, int x, int z, + int stencilX, int stencilZ, int minSolidDepth) { + if (stencilX < 0 || stencilX >= width || stencilZ < 0 || stencilZ >= depth + || !cells[(stencilX * depth) + stencilZ]) { + return false; + } + + int columnX = x + minX + stencilX; + int columnZ = z + minZ + stencilZ; + int surfaceY = placer.getHighest(columnX, columnZ, data, true); + for (int below = 0; below < minSolidDepth; below++) { + if (placer.isCarved(columnX, surfaceY - below, columnZ)) { + return true; + } + } + return !placer.isSurfaceSolid(columnX, surfaceY, columnZ); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java new file mode 100644 index 000000000..5f99d7bb5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java @@ -0,0 +1,83 @@ +/* + * 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.annotations.ArrayType; +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.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; +import org.bukkit.TreeType; + +@Snippet("tree") +@Accessors(chain = true) +@AllArgsConstructor +@NoArgsConstructor +@Desc("Tree replace options for this object placer") +@Data +public class IrisTree { + @Required + @Desc("The types of trees overwritten by this object") + @ArrayType(min = 1, type = String.class) + private KList treeTypes = new KList<>(); + + + @Required + @Desc("The size of the square of saplings this applies to (2 means a 2 * 2 sapling area)") + @ArrayType(min = 1, type = IrisTreeSize.class) + private KList sizes = new KList<>(); + + + public boolean matches(IrisTreeSize size, TreeType type) { + if (!matchesSize(size)) { + return false; + } + + return matchesType(type); + } + + private boolean matchesSize(IrisTreeSize size) { + for (IrisTreeSize i : getSizes()) { + if ((i.getDepth() == size.getDepth() && i.getWidth() == size.getWidth()) || (i.getDepth() == size.getWidth() && i.getWidth() == size.getDepth())) { + return true; + } + } + + return false; + } + + private boolean matchesType(TreeType type) { + if (type == null) { + return false; + } + + String name = type.name(); + for (String i : getTreeTypes()) { + if (i != null && i.equalsIgnoreCase(name)) { + return true; + } + } + + return false; + } +} \ No newline at end of file diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java new file mode 100644 index 000000000..31d9c026c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java @@ -0,0 +1,54 @@ +/* + * 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.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("tree-size") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Sapling override object picking options") +@Data +public class IrisTreeSize { + + @Required + @Desc("The width of the sapling area") + int width = 1; + + @Required + @Desc("The depth of the sapling area") + int depth = 1; + + /** + * Does the size match + * + * @param size the size to check match + * @return true if it matches (fits within width and depth) + */ + public boolean doesMatch(IrisTreeSize size) { + return (width == size.getWidth() && depth == size.getDepth()) || (depth == size.getWidth() && width == size.getDepth()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java new file mode 100644 index 000000000..12eb59fc4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java @@ -0,0 +1,39 @@ +package art.arcane.iris.engine.object.placement; + +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("vacuum-settings") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Defines how a VACUUM place mode bends terrain to meet an object's base.") +@Data +public class IrisVacuumSettings { + @MinNumber(0) + @MaxNumber(128) + @Desc("The horizontal radius (in blocks) the terrain deformation extends beyond the object footprint before it blends back to the natural surface. 0 = derive automatically from the place mode (VACUUM, VACUUM_HIGH larger, VACUUM_FAST smaller).") + private int radius = 0; + @MinNumber(0.25) + @MaxNumber(8) + @Desc("The falloff exponent controlling how the deformation eases out across the radius. 1 = linear (cone), 2 = parabolic (default, gentle bowl), higher = flatter near the object with a sharper drop at the edge.") + private double falloff = 2.0; + @MinNumber(0) + @MaxNumber(64) + @Desc("For VACUUM_ORGANIC: the maximum number of blocks the effective radius is randomly perturbed per column, giving the meeting edge an irregular organic outline instead of a clean circle.") + private int organicJitter = 4; + @MinNumber(0) + @MaxNumber(64) + @Desc("For VACUUM_WAVY: the vertical amplitude (in blocks) of the rolling simplex wave applied across the terrain bend. The wave fades to zero under the object (so it stays flush) and at the outer radius (so it blends back to the surface), peaking across the mid-slope. 0 disables the wave.") + private int waveAmplitude = 3; + @MinNumber(0.1) + @MaxNumber(64) + @Desc("For VACUUM_WAVY: the frequency of the simplex wave. Higher values make tighter, choppier ripples; lower values make broad, gentle swells. The wavelength in blocks is roughly 100 / waveScale.") + private double waveScale = 5.0; +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java new file mode 100644 index 000000000..0bca2e368 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java @@ -0,0 +1,259 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.marker.ObjectMarkerPlacement; +import art.arcane.iris.engine.object.material.BlockDataMergeSupport; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.nms.container.Pair; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.math.BlockPosition; + +import java.util.List; +import java.util.Optional; +import java.util.function.BiConsumer; + +final class ObjectBlockPass { + + private List matchingMarkers; + private final BiConsumer listener; + + private final PlacementContext context; + private final PlacementState state; + private final VectorMap blocks; + private final VectorMap states; + private final ObjectMarkerPlacement markerPlacer; + private final PlacementLifecycle lifecycle; + + ObjectBlockPass( + PlacementContext context, + PlacementState state, + PlacementLifecycle lifecycle, + BiConsumer listener + ) { + this.context = context; + this.state = state; + this.lifecycle = lifecycle; + this.listener = listener; + this.blocks = context.self.blocks; + this.states = context.self.states; + + if (state.config.getMarkers().isNotEmpty() && state.placer.getEngine() != null) { + markerPlacer = new ObjectMarkerPlacement(context, state); + markerPlacer.loadPossibleMarkers(); + } else { + markerPlacer = null; + } + } + + void process() { + VectorMap.Cursor cursor = blocks.cursor(); + IrisObjectTranslate translate = state.config.getTranslate(); + CNG surfaceWarp = !state.config.getWarp().isFlat() ? state.config.getSurfaceWarp(context.rng, context.self.getLoader()) : null; + boolean preventingDecay = state.placer.isPreventingDecay(); + boolean waterlogCandidate = state.config.isWaterloggable() || state.config.isUnderwater(); + boolean hasStates = !states.isEmpty(); + int xx, zz; + + double warpHalf = !state.config.getWarp().isFlat() ? state.config.getWarp().getMultiplier() / 2D : 0D; + + while (cursor.next()) { + var read = readStateFrom(cursor, hasStates); + + PlatformBlockState data = read.getA(); + TileData tile = read.getB(); + IrisBlockVector vector = cursor.key().clone(); + + state.spin.rotate(vector); + PlacementBlock block = new PlacementBlock(data, tile, vector); + lifecycle.run(PlacementStage.TRANSFORM_BLOCK, context, state, block); + if (state.isRejected()) { + return; + } + + if (translate.canTranslate()) { + vector.add(state.translateOffset); + } + + lifecycle.run(PlacementStage.COLLECT_BLOCK, context, state, block); + if (state.isRejected()) { + return; + } + if (preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance") && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))) { + data = data.withProperty("persistent", "true"); + } + + if (!state.config.getEdit().isEmpty()) { + var result = applyEdits(vector, data, tile); + data = result.data(); + tile = result.tile(); + } + + matchingMarkers = markerPlacer != null ? markerPlacer.matchMarkers(data) : null; + + data = state.spin.rotate(data); + xx = context.x + (int) Math.round(vector.getX()); + int yy = state.y + (int) Math.round(vector.getY()); + zz = context.z + (int) Math.round(vector.getZ()); + + if (!state.config.getWarp().isFlat()) { + xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, vector.getX() + context.x, vector.getY() + state.y, vector.getZ() + context.z); + zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, vector.getZ() + context.z, vector.getY() + state.y, vector.getX() + context.x); + } + + if (context.yv < 0 && (is(ObjectPlaceMode.PAINT)) && !B.isVineBlock(data)) { + yy = (int) Math.round(vector.getY()) + Math.floorDiv(context.self.h, 2) + state.placer.getHighest(xx, zz, context.self.getLoader(), state.config.isUnderwater()); + } + + if (state.config.isMeld() && !is(ObjectPlaceMode.STRUCTURE_PIECE) && !state.placer.isSolid(xx, yy, zz)) { + continue; + } + + if (waterlogCandidate && IrisProceduralBlocks.hasProperty(data, "waterlogged") && shouldAutoWaterlogBlock(context, state, xx, yy, zz)) { + data = data.withProperty("waterlogged", "true"); + } + + if (B.isVineBlock(data)) { + data = attachVineFaces(state.placer, data, xx, yy, zz); + } + + if (handleCustomData(data, tile, xx, yy, zz)) { + lifecycle.run(PlacementStage.BLOCK_WRITTEN, context, state, new PlacementBlockWrite(xx, yy, zz, data)); + if (state.isRejected()) { + return; + } + } + } + + if (markerPlacer != null) { + markerPlacer.placeMarkers(); + } + + + } + + private boolean is(ObjectPlaceMode mode) { + return state.config.getMode() == mode; + } + + static boolean shouldPlaceObjectBlock(boolean rawStructurePiece, boolean air, boolean wouldReplace) { + return !wouldReplace && (rawStructurePiece || !air); + } + + private boolean handleCustomData(PlatformBlockState data, TileData tile, int xx, int yy, int zz) { + // Short-circuit order matters for cost only: the mantle read is paid solely + // for vine blocks. Both operands are pure, so the value is unchanged. + boolean wouldReplace = B.isVineBlock(data) && B.isSolid(state.placer.get(xx, yy, zz)); + String material = IrisObjectShaping.materialKey(data); + boolean air = material.equals("minecraft:air") || material.equals("minecraft:cave_air"); + boolean place = shouldPlaceObjectBlock(is(ObjectPlaceMode.STRUCTURE_PIECE), air, wouldReplace); + if (data.isCustom() || place) { + state.placer.set(xx, yy, zz, data); + if (tile != null) { + state.placer.setTile(xx, yy, zz, tile); + } + if (matchingMarkers != null) { + BlockPosition markerPosition = new BlockPosition(xx, yy, zz); + for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : matchingMarkers) { + markerPlacement.candidates.add(markerPosition); + } + } + if (listener != null) { + listener.accept(new BlockPosition(xx, yy, zz), data); + } + return true; + } + return false; + } + + private EditResult applyEdits(IrisBlockVector vector, PlatformBlockState data, TileData tile) { + for (IrisObjectReplace j : state.config.getEdit()) { + if (context.rng.chance(j.getChance())) { + for (PlatformBlockState k : j.getFind(context.rdata)) { + if (j.isExact() ? k.matches(data) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(data))) { + PlatformBlockState newData = j.getReplace(context.rng, vector.getX() + context.x, vector.getY() + state.y, vector.getZ() + context.z, context.rdata); + + if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(data)) && !(newData.isCustom() || data.isCustom())) + data = BlockDataMergeSupport.merge(data, newData); + else + data = newData; + + Optional t = j.getReplace().getTile(context.rng, context.x, state.y, context.z, context.rdata); + if (t.isPresent()) { + tile = t.get(); + } + } + } + } + } + return new EditResult(data, tile); + } + + static boolean shouldAutoWaterlogBlock(PlacementContext context, PlacementState state, int x, int y, int z) { + if (!(state.config.isWaterloggable() || state.config.isUnderwater())) { + return false; + } + + if (context.yv >= 0 && state.config.getCarvingSupport().equals(CarvingMode.CARVING_ONLY)) { + return false; + } + + PlatformBlockState existing = state.placer.get(x, y, z); + if (existing == null) { + return false; + } + + return B.isWater(existing) || B.isWaterLogged(existing); + } + + static PlatformBlockState attachVineFaces(IObjectPlacer placer, PlatformBlockState data, int x, int y, int z) { + PlatformBlockState result = data; + for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { + if (!IrisProceduralBlocks.hasProperty(data, face)) { + continue; + } + int[] mod = IrisProceduralBlocks.faceOffset(face); + PlatformBlockState facing = placer.get(x + mod[0], y + mod[1], z + mod[2]); + if (B.isSolid(facing) && !B.isVineBlock(facing)) { + result = result.withProperty(face, "true"); + } + } + return result; + } + + + private Pair readStateFrom(VectorMap.Cursor cursor, boolean hasStates) { + PlatformBlockState block; + TileData tile = null; + IrisBlockVector vector = cursor.key(); + try { + block = cursor.value(); + if (hasStates) { + tile = states.get(vector); + } + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.warn("Failed to read block node " + vector.getBlockX() + "," + vector.getBlockY() + "," + vector.getBlockZ() + " in object " + context.self.getLoadKey() + " (cme)"); + block = IrisObject.States.AIR; + } + + if (block == null) { + IrisLogging.warn("Failed to read block node " + vector.getBlockX() + "," + vector.getBlockY() + "," + vector.getBlockZ() + " in object " + context.self.getLoadKey() + " (null)"); + block = IrisObject.States.AIR; + } + if (state.placer.isDebugSmartBore() && IrisObject.States.VAIR.equals(block)) { + block = IrisObject.States.VAIR_DEBUG; + } + return new Pair<>(block, tile); + } + + private record EditResult(PlatformBlockState data, TileData tile) {} +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java new file mode 100644 index 000000000..4260e704c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java @@ -0,0 +1,11 @@ +package art.arcane.iris.engine.object.placement; + +public final class ObjectModuleCeilingHang implements PlacementModule { + static final PlacementLifecycleDependency FLIP = new PlacementLifecycleDependency("ceiling.flip"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(FLIP, PlacementStage.TRANSFORM_BLOCK, + (context, state, block) -> block.vector().setY(-block.vector().getBlockY())); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java new file mode 100644 index 000000000..7e7392c70 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java @@ -0,0 +1,149 @@ +/* + * 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.annotations.Desc; + +import java.util.function.Supplier; + +@Desc("Object Place modes are useful for positioning objects just right. The default value is CENTER_HEIGHT.") +public enum ObjectPlaceMode { + @Desc("The default place mode. This mode picks a center point (where the center of the object will be) and takes the height. That height is used for the whole object.") + + CENTER_HEIGHT(PlacementModuleCenterHeight::new), + + @Desc("Samples a lot of points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.") + + MAX_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, false)), + + @Desc("Samples only 4 points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.\"") + + FAST_MAX_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, true)), + + @Desc("Samples a lot of points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") + MIN_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, false)), + + @Desc("Samples only 4 points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") + + FAST_MIN_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, true)), + + @Desc("Stilting is MAX_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") + + STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.DEFAULT, false)), + + @Desc("Just like stilting but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") + + FAST_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.DEFAULT, true)), + + @Desc("Stilting is MIN_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") + + MIN_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.MIN, false)), + + @Desc("Just like MIN_STILT but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") + + FAST_MIN_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.MIN, true)), + + @Desc("Stilting is CENTER_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") + + CENTER_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.CENTER, false)), + + @Desc("Erode stilting tapers columns downward like an ice cream cone. Blocks near the center extend deepest while edge blocks drop off first. Blocks are randomly skipped in the lower portion for a rough organic eroded texture.") + + ERODE_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.ERODE, false)), + + @Desc("Organic stilting scans straight down from the bottom of the object to the first solid block (the cave floor, or terrain) and fills the gap with the object's own bottom block. Each column stops at a slightly different, noise-varied depth and the lower portion is randomly broken up, so the underside reads as rough organic roots rather than a flat disc. Designed for objects placed inside caves so they connect to the floor instead of floating. Tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") + + ORGANIC_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.ORGANIC, false)), + + @Desc("Hangs the object upside-down from a cave ceiling. The object is flipped vertically (its tip points down like a stalactite) and its top is anchored to the ceiling, while an organic, noise-varied stilt grows up into the ceiling so it never floats below the roof. Use inside caves; tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") + + CEILING_HANG(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.CEILING, false)), + + @Desc("Anchors the object at the terrain surface (plus translate.y) like CENTER_HEIGHT, then bends the surrounding terrain to be flush with the object's base. Columns inside the object footprint are raised (or lowered) to meet the base, and the deformation falls off parabolically out to a radius so the terrain smoothly blends back to its natural height. Use this to seat a floating/translated object on the ground without a flat stilt disc, e.g. a cube translated up 10 on a mountain pulls the terrain up to meet it. Tune with vacuum-settings (radius, falloff).") + + VACUUM(PlacementModuleCenterHeight::new), + + @Desc("VACUUM with a larger radius and finer per-column sampling for the smoothest terrain blend. More expensive.") + + VACUUM_HIGH(PlacementModuleCenterHeight::new), + + @Desc("VACUUM with a smaller radius and coarser sampling for performance. Use when seating many objects.") + + VACUUM_FAST(PlacementModuleCenterHeight::new), + + @Desc("VACUUM whose falloff radius is perturbed by noise per column, so the terrain meets the object with an irregular organic edge rather than a clean parabolic bowl.") + + VACUUM_ORGANIC(PlacementModuleCenterHeight::new), + + @Desc("VACUUM whose terrain bend is bent by smooth coherent simplex noise so the surface meets the object with a gently rolling, wavy slope instead of the ragged white-noise edge of VACUUM_ORGANIC or a clean parabolic bowl. The object itself still seats flush; the waves fade to zero under the object and at the outer rim, peaking across the mid-slope. Tune with vacuum-settings (waveAmplitude, waveScale).") + + VACUUM_WAVY(PlacementModuleCenterHeight::new), + + @Desc("Samples the height of the terrain at every x,z position of your object and pushes it down to the surface. It's pretty much like a melt function over the terrain.") + + PAINT(PlacementModulePaint::new), + + @Desc("Places the object in pure air at an absolute Y driven entirely by translate.y (plus optional translate.yRandom). Terrain height, underwater, and carving anchor checks are skipped. Use this for floating islands, sky structures, clouds, or blimps where the object must not be translated to the ground.") + + FLOATING(PlacementModuleFloating::new), + + @Desc("Raw stamp at the caller-supplied (x, y, z). No terrain sampling, no stilting, no Y recomputation, no underwater or carving anchor guards. Used internally to route native Minecraft structure pieces (villages etc.) through the Iris object placer.") + + STRUCTURE_PIECE(() -> lifecycle -> PlacementModuleAnchor.install(lifecycle, + (context, state, ignored) -> state.y = context.yv)); + + + private final Supplier factory; + + ObjectPlaceMode(Supplier factory) { + this.factory = factory; + } + + PlacementLifecycle createLifecycle() { + PlacementLifecycleBuilder lifecycle = new PlacementLifecycleBuilder(); + install(lifecycle); + return lifecycle.build(); + } + + void install(PlacementLifecycleBuilder lifecycle) { + new PlacementModulePreparation().install(lifecycle); + new PlacementModuleSlope().install(lifecycle); + factory.get().install(lifecycle); + new PlacementModuleAnchor().install(lifecycle); + new PlacementModuleSurfaceSupport().install(lifecycle); + new PlacementModuleLimits().install(lifecycle); + new PlacementModuleNativeStructureProtection().install(lifecycle); + new PlacementModuleBounds().install(lifecycle); + new PlacementModuleCollision().install(lifecycle); + new PlacementModuleBore().install(lifecycle); + new PlacementModuleBlocks().install(lifecycle); + PlacementLifecycleDependency finish = switch (this) { + case STILT, FAST_STILT, MIN_STILT, FAST_MIN_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT, CEILING_HANG -> + PlacementModuleStilt.FILL; + case VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC, VACUUM_WAVY -> { + new PlacementModuleVacuum().install(lifecycle); + yield PlacementModuleVacuum.FINISH; + } + default -> PlacementModuleBlocks.COMPLETE; + }; + new PlacementModuleSnow(finish).install(lifecycle); + } + + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java new file mode 100644 index 000000000..3947fdc35 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java @@ -0,0 +1,165 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.IrisBlockVector; + +/** + * Precomputed vector rotation for a single placement. + *

+ * This mirrors {@link IrisObjectRotation#rotate(IrisBlockVector, int, int, int)} branch for branch, with two + * differences: it mutates the vector handed to it instead of cloning, and the per-axis angle plus its cosine + * and sine are resolved once instead of once per block. The angle is a pure function of the axis clamp and the + * spin, both fixed for the placement, and Math.cos/Math.sin are pure, so every produced double is identical to + * the value the per-call form would have produced. + */ + final class ObjectSpinKernel { + private static final int MODE_NONE = 0; + private static final int MODE_FLIP = 1; + private static final int MODE_QUARTER = 2; + private static final int MODE_THREE_QUARTER = 3; + private static final int MODE_ANGLE = 4; + + IrisObjectRotation rotation; + + private final int spinX ; + private final int spinY; + private final int spinZ; + private final int xMode; + private final int yMode; + private final int zMode; + private final double xCos; + private final double xSin; + private final double yCos; + private final double ySin; + private final double zCos; + private final double zSin; + + ObjectSpinKernel(IrisObjectRotation rotation, int spinX, int spinY, int spinZ) { + this.rotation = rotation; + xMode = rotation.canRotateX() ? modeOf(rotation.getXAxis()) : MODE_NONE; + zMode = rotation.canRotateZ() ? modeOf(rotation.getZAxis()) : MODE_NONE; + yMode = rotation.canRotateY() ? modeOf(rotation.getYAxis()) : MODE_NONE; + this.spinX = spinX; + this.spinY = spinY; + this.spinZ = spinZ; + double xAngle = xMode == MODE_ANGLE ? rotation.getXRotation(spinX) : 0; + double zAngle = zMode == MODE_ANGLE ? rotation.getZRotation(spinZ) : 0; + double yAngle = yMode == MODE_ANGLE ? rotation.getYRotation(spinY) : 0; + xCos = Math.cos(xAngle); + xSin = Math.sin(xAngle); + zCos = Math.cos(zAngle); + zSin = Math.sin(zAngle); + yCos = Math.cos(yAngle); + ySin = Math.sin(yAngle); + } + + private static int modeOf(IrisAxisRotationClamp clamp) { + if (!clamp.isLocked()) { + return MODE_ANGLE; + } + + if (Math.abs(clamp.getMax()) % 360D == 180D) { + return MODE_FLIP; + } + + if (clamp.getMax() % 360D == 90D || clamp.getMax() % 360D == -270D) { + return MODE_QUARTER; + } + + if (clamp.getMax() == -90D || clamp.getMax() % 360D == 270D) { + return MODE_THREE_QUARTER; + } + + return MODE_ANGLE; + } + + PlatformBlockState rotate(PlatformBlockState state) { + return rotation.rotate(state, spinX, spinY, spinZ); + } + + /** + * Rotates in place. Axis order (X, then Z, then Y) is load bearing. + */ + void rotate(IrisBlockVector v) { + if (!rotation.canRotate()) { + return; + } + + switch (xMode) { + case MODE_FLIP -> { + v.setZ(-v.getZ()); + v.setY(-v.getY()); + } + case MODE_QUARTER -> { + double z = v.getZ(); + v.setZ(v.getY()); + v.setY(-z); + } + case MODE_THREE_QUARTER -> { + double z = v.getZ(); + v.setZ(-v.getY()); + v.setY(z); + } + case MODE_ANGLE -> { + double y = xCos * v.getY() - xSin * v.getZ(); + double z = xSin * v.getY() + xCos * v.getZ(); + v.setY(y); + v.setZ(z); + } + default -> { + } + } + + switch (zMode) { + case MODE_FLIP -> { + v.setY(-v.getY()); + v.setX(-v.getX()); + } + case MODE_QUARTER -> { + double y = v.getY(); + v.setY(v.getX()); + v.setX(-y); + } + case MODE_THREE_QUARTER -> { + double y = v.getY(); + v.setY(-v.getX()); + v.setX(y); + } + case MODE_ANGLE -> { + double x = zCos * v.getX() - zSin * v.getY(); + double y = zSin * v.getX() + zCos * v.getY(); + v.setX(x); + v.setY(y); + } + default -> { + } + } + + switch (yMode) { + case MODE_FLIP -> { + v.setX(-v.getX()); + v.setZ(-v.getZ()); + } + case MODE_QUARTER -> { + double x = v.getX(); + v.setX(v.getZ()); + v.setZ(-x); + } + case MODE_THREE_QUARTER -> { + double x = v.getX(); + v.setX(-v.getZ()); + v.setZ(x); + } + case MODE_ANGLE -> { + double x = yCos * v.getX() + ySin * v.getZ(); + double z = -ySin * v.getX() + yCos * v.getZ(); + v.setX(x); + v.setZ(z); + } + default -> { + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java new file mode 100644 index 000000000..0107574e8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java @@ -0,0 +1,9 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.IrisBlockVector; + +/** Source data and a placement-owned vector; changing the vector does not change the cached object. */ +public record PlacementBlock(PlatformBlockState data, TileData tile, IrisBlockVector vector) { +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java new file mode 100644 index 000000000..38a03f78c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java @@ -0,0 +1,6 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.spi.PlatformBlockState; + +/** A completed object write, after its tile data and listener have been handled. */ +public record PlacementBlockWrite(int x, int y, int z, PlatformBlockState data) {} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java new file mode 100644 index 000000000..a3f30eccc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java @@ -0,0 +1,45 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.terrain.carving.CarveResult; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.RNG; +import lombok.Getter; + +import java.util.Objects; +import java.util.function.BiConsumer; + +/** Caller inputs for one placement. Modules keep derived values in PlacementState. */ +@Getter +public final class PlacementContext { + public record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {} + public record WorldBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {} + + final IrisObjectPlacement config; + final IrisData rdata; + final IObjectPlacer placer; + final CarveResult caveResult; + final RNG rng; + final IrisObject self; + final int x; + final int z; + final int yv; + final BiConsumer listener; + + public PlacementContext(IrisObjectPlacement config, IrisData rdata, IObjectPlacer placer, + CarveResult caveResult, RNG rng, IrisObject self, int x, int z, int yv, + BiConsumer listener) { + this.placer = Objects.requireNonNull(placer, "Object placer is required."); + this.config = Objects.requireNonNull(config, "Object placement config is required."); + this.rng = Objects.requireNonNull(rng, "Object placement RNG is required."); + this.rdata = Objects.requireNonNull(rdata, "Object placement data is required."); + this.self = Objects.requireNonNull(self, "Object is required."); + this.caveResult = caveResult; + this.x = x; + this.z = z; + this.yv = yv; + this.listener = listener; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java new file mode 100644 index 000000000..15326a3cc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java @@ -0,0 +1,6 @@ +package art.arcane.iris.engine.object.placement; + +@FunctionalInterface +public interface PlacementFunction { + void execute(PlacementContext context, PlacementState state, C input); +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java new file mode 100644 index 000000000..378b59ee7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java @@ -0,0 +1,35 @@ +package art.arcane.iris.engine.object.placement; + +import java.util.List; + +/** Immutable plan. Placement performs no registration, graph traversal, or sorting. */ +public final class PlacementLifecycle { + private final List>> stages; + + PlacementLifecycle(List> ordered) { + stages = PlacementStage.ALL.stream() + .map(stage -> ordered.stream().filter(step -> step.stage() == stage).toList()).toList(); + } + + public PlacementState execute(PlacementContext context) { + PlacementState state = new PlacementState(context); + for (PlacementStage stage : PlacementStage.BEFORE_PASS) { + run(stage, context, state, null); + } + run(PlacementStage.BLOCKS, context, state, this); + run(PlacementStage.AFTER_BLOCKS, context, state, null); + return state; + } + + public void run(PlacementStage stage, PlacementContext context, PlacementState state, C input) { + for (PlacementLifecycleBuilder.Step step : stages.get(stage.order)) { + if (state.isRejected()) { + return; + } + // Registration pairs each function with its typed stage. + @SuppressWarnings("unchecked") + PlacementFunction function = (PlacementFunction) step.function(); + function.execute(context, state, input); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java new file mode 100644 index 000000000..9454cfe8c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java @@ -0,0 +1,84 @@ +package art.arcane.iris.engine.object.placement; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.PriorityQueue; + +/** + * Registers steps and resolves their graph before an engine runtime is published. + * A dependency names a required step, not a Java class: two instances of the same module can + * register distinct work. Declaring a dependency does not install its prerequisite. + * The module composition must register it, in any order, before calling {@link #build()}. + * + *

{@code
+ * lifecycle.add(FILL, PlacementStage.AFTER_BLOCKS, this::fill, HEIGHT, BOUNDS);
+ * }
+ * + * Independent steps retain registration order within their stage. Invalid graphs fail construction; + * the builder never executes functions. Functions must not capture mutable placement state. + */ +public final class PlacementLifecycleBuilder { + private final Map> steps = new LinkedHashMap<>(); + + public void add(PlacementLifecycleDependency id, PlacementStage stage, + PlacementFunction function, PlacementLifecycleDependency... after) { + Objects.requireNonNull(id, "Step id"); + Objects.requireNonNull(stage, "Stage"); + Objects.requireNonNull(function, "Function"); + Step step = new Step<>(id, stage, function, List.of(after), steps.size()); + if (steps.putIfAbsent(id, step) != null) { + throw new IllegalArgumentException("Duplicate placement step '" + id.name() + "'"); + } + } + + /** Stable topological sort; stage barriers do not need all-to-all edges. */ + public PlacementLifecycle build() { + Map remaining = new HashMap<>(); + Map>> dependents = new HashMap<>(); + PriorityQueue> ready = new PriorityQueue<>(Comparator.>comparingInt(step -> step.stage.order).thenComparingInt(Step::index)); + for (Step step : steps.values()) { + var prerequisites = step.after.stream().distinct().toList(); + remaining.put(step.id, prerequisites.size()); + for (PlacementLifecycleDependency id : prerequisites) { + Step prerequisite = steps.get(id); + if (prerequisite == null) { + throw new IllegalArgumentException("Placement step '" + step.id.name() + + "' requires missing step '" + id.name() + "'"); + } + if (prerequisite.stage.order > step.stage.order) { + throw new IllegalArgumentException("Placement step '" + step.id.name() + "' in " + step.stage + + " cannot depend on later step '" + id.name() + "' in " + prerequisite.stage); + } + dependents.computeIfAbsent(id, ignored -> new ArrayList<>()).add(step); + } + if (prerequisites.isEmpty()) { + ready.add(step); + } + } + List> ordered = new ArrayList<>(steps.size()); + while (!ready.isEmpty()) { + Step step = ready.remove(); + ordered.add(step); + for (Step dependent : dependents.getOrDefault(step.id, List.of())) { + if (remaining.compute(dependent.id, (ignored, count) -> count - 1) == 0) { + ready.add(dependent); + } + } + } + if (ordered.size() != steps.size()) { + throw new IllegalArgumentException("Placement dependency cycle; unresolved steps: " + + steps.keySet().stream().filter(id -> remaining.get(id) > 0) + .map(PlacementLifecycleDependency::name).toList()); + } + return new PlacementLifecycle(ordered); + } + + record Step(PlacementLifecycleDependency id, PlacementStage stage, PlacementFunction function, + List after, int index) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java new file mode 100644 index 000000000..399e7c0de --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java @@ -0,0 +1,13 @@ +package art.arcane.iris.engine.object.placement; + +import java.util.Objects; + +/** A named prerequisite, scoped to one placement plan. */ +public record PlacementLifecycleDependency(String name) { + public PlacementLifecycleDependency { + Objects.requireNonNull(name, "Dependency name"); + if (name.isBlank()) { + throw new IllegalArgumentException("Placement dependency name cannot be blank"); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java new file mode 100644 index 000000000..d59d5eae8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java @@ -0,0 +1,43 @@ +package art.arcane.iris.engine.object.placement; + +import java.util.EnumMap; +import java.util.Map; + +/** One resolved plan per mode in an engine runtime. Engine-less tools share a separate default set. */ +public final class PlacementLifecycles { + private final Map plans; + + private PlacementLifecycles(Map plans) { + this.plans = Map.copyOf(plans); + } + + public static PlacementLifecycles resolve() { + Map plans = new EnumMap<>(ObjectPlaceMode.class); + for (ObjectPlaceMode mode : ObjectPlaceMode.values()) { + try { + plans.put(mode, mode.createLifecycle()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("Invalid placement lifecycle for " + mode + ": " + e.getMessage(), e); + } + } + return new PlacementLifecycles(plans); + } + + public static PlacementLifecycles defaults() { + return Defaults.INSTANCE; + } + + static PlacementLifecycles forPlacer(IObjectPlacer placer) { + var engine = placer.getEngine(); + PlacementLifecycles plans = engine == null ? null : engine.getPlacementLifecycles(); + return plans == null ? defaults() : plans; + } + + public PlacementLifecycle get(ObjectPlaceMode mode) { + return plans.get(java.util.Objects.requireNonNull(mode, "Placement mode")); + } + + private static final class Defaults { + private static final PlacementLifecycles INSTANCE = resolve(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java new file mode 100644 index 000000000..e9e0eb433 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java @@ -0,0 +1,9 @@ +package art.arcane.iris.engine.object.placement; + +/** + * Registers work during runtime construction. Functions are shared by concurrent placements: + * implementations must receive placement state at execution time, never capture it at installation. + */ +public interface PlacementModule { + void install(PlacementLifecycleBuilder lifecycle); +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java new file mode 100644 index 000000000..f9a60c738 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java @@ -0,0 +1,43 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +/** Common caller-supplied and from-bottom anchors wrap each mode's sampled height. */ +final class PlacementModuleAnchor implements PlacementModule { + static final PlacementLifecycleDependency HEIGHT = new PlacementLifecycleDependency("anchor.height"); + static final PlacementLifecycleDependency POSITIONED = new PlacementLifecycleDependency("anchor.positioned"); + static final PlacementLifecycleDependency FINAL_HEIGHT = new PlacementLifecycleDependency("anchor.final"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(POSITIONED, PlacementStage.HEIGHT, (context, state, ignored) -> { + if (context.yv >= 0 && state.config.isBottom() + && state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE) { + state.y += Math.floorDiv(context.self.h, 2); + if (!state.config.isForcePlace() && state.config.getCarvingSupport() != CarvingMode.CARVING_ONLY + && PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); + } + } + }, HEIGHT); + lifecycle.add(FINAL_HEIGHT, PlacementStage.BEFORE_BLOCKS, + (context, state, ignored) -> state.y += state.yrand, POSITIONED, PlacementModuleCollision.CHECK); + } + + static void install(PlacementLifecycleBuilder lifecycle, PlacementFunction sampledHeight) { + lifecycle.add(HEIGHT, PlacementStage.HEIGHT, (context, state, ignored) -> { + if (state.config.isFromBottom()) { + state.y = context.self.getH() + 1 + state.rty; + } else if (context.yv < 0) { + sampledHeight.execute(context, state, null); + return; + } else { + state.y = context.yv; + } + if (!state.config.isForcePlace() + && state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE + && PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); + } + }, PlacementModulePreparation.TRANSFORMS); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java new file mode 100644 index 000000000..5231eb414 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java @@ -0,0 +1,18 @@ +package art.arcane.iris.engine.object.placement; + +/** Owns block-pass execution and the object read lock. */ +final class PlacementModuleBlocks implements PlacementModule { + static final PlacementLifecycleDependency COMPLETE = new PlacementLifecycleDependency("blocks.complete"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(COMPLETE, PlacementStage.BLOCKS, (context, state, plan) -> { + context.self.readLock.lock(); + try { + new ObjectBlockPass(context, state, plan, context.listener).process(); + } finally { + context.self.readLock.unlock(); + } + }, PlacementModuleBore.BORE); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java new file mode 100644 index 000000000..3971388ef --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java @@ -0,0 +1,25 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +/** The first world-writing step; all placement guards must have completed. */ +final class PlacementModuleBore implements PlacementModule { + static final PlacementLifecycleDependency BORE = new PlacementLifecycleDependency("bore"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(BORE, PlacementStage.BEFORE_BLOCKS, (context, state, ignored) -> { + if (!state.config.isBore()) { + return; + } + var bounds = state.worldBounds; + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { + for (int y = bounds.minY() - state.config.getBoreExtendMinY(); + y <= bounds.maxY() + state.config.getBoreExtendMaxY(); y++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { + state.placer.set(x, y, z, IrisObject.States.AIR); + } + } + } + }, PlacementModuleBounds.WORLD, PlacementModuleCollision.CHECK, PlacementModuleAnchor.FINAL_HEIGHT); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java new file mode 100644 index 000000000..50fc4674e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java @@ -0,0 +1,43 @@ +package art.arcane.iris.engine.object.placement; + +/** Computes the shared world volume for collision checks and boring, only when needed. */ +final class PlacementModuleBounds implements PlacementModule { + static final PlacementLifecycleDependency WORLD = new PlacementLifecycleDependency("bounds.world"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(WORLD, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + if (config.isBore() || (!config.isForcePlace() && config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE + && (!config.getAllowedCollisions().isEmpty() || !config.getForbiddenCollisions().isEmpty()))) { + state.worldBounds = resolve(context, state, context.yv < 0 && config.getMode() == ObjectPlaceMode.PAINT); + } + }, PlacementModuleNativeStructureProtection.CHECK); + } + + private static PlacementContext.WorldBounds resolve(PlacementContext context, PlacementState state, boolean paint) { + int x = context.x; + int z = context.z; + int y = state.y + state.yrand; + int minX = x + state.bounds.minX(); + int maxX = x + state.bounds.maxX(); + int minZ = z + state.bounds.minZ(); + int maxZ = z + state.bounds.maxZ(); + if (!paint) { + return new PlacementContext.WorldBounds(minX, maxX, y + state.bounds.minY(), y + state.bounds.maxY(), minZ, maxZ); + } + + int minimumSurface = Integer.MAX_VALUE; + int maximumSurface = Integer.MIN_VALUE; + for (int worldX = minX; worldX <= maxX; worldX++) { + for (int worldZ = minZ; worldZ <= maxZ; worldZ++) { + int surface = state.placer.getHighest(worldX, worldZ, context.self.getLoader(), state.config.isUnderwater()); + minimumSurface = Math.min(minimumSurface, surface); + maximumSurface = Math.max(maximumSurface, surface); + } + } + int paintOffset = Math.floorDiv(context.self.h, 2); + return new PlacementContext.WorldBounds(minX, maxX, minimumSurface + state.bounds.minY() + paintOffset, + maximumSurface + state.bounds.maxY() + paintOffset, minZ, maxZ); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java new file mode 100644 index 000000000..fe9cb93a2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java @@ -0,0 +1,18 @@ +package art.arcane.iris.engine.object.placement; + +public final class PlacementModuleCenterHeight implements PlacementModule { + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, PlacementModuleCenterHeight::sample); + } + + private static void sample(PlacementContext context, PlacementState state, Void ignored) { + state.y = (context.caveResult != null ? context.caveResult.getSurface() : state.placer.getHighest(context.x, context.z, context.self.getLoader(), state.config.isUnderwater())) + state.rty; + if (!state.config.isForcePlace()) { + if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java new file mode 100644 index 000000000..db589dd06 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java @@ -0,0 +1,41 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.PlacedObject; + +/** Owns object collision policy and its data-engine requirement. */ +final class PlacementModuleCollision implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.collisions"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + if (config.isForcePlace() || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE + || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { + return; + } + Engine engine = context.rdata.getEngine(); + if (engine == null) { + throw new IllegalStateException("Object placement requires active Iris data for collision settings."); + } + var bounds = state.worldBounds; + for (int x = bounds.minX(); x <= bounds.maxX(); x++) { + for (int y = bounds.minY(); y <= bounds.maxY(); y++) { + for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { + PlacedObject placed = engine.getObjectPlacement(x, y, z); + if (placed == null || placed.getObject() == null) { + continue; + } + String key = placed.getObject().getLoadKey(); + if (key != null && config.getForbiddenCollisions().contains(key) + && !config.getAllowedCollisions().contains(key)) { + state.reject("object-collision"); + return; + } + } + } + } + }, PlacementModuleBounds.WORLD); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java new file mode 100644 index 000000000..f407192ce --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java @@ -0,0 +1,10 @@ +package art.arcane.iris.engine.object.placement; + +public final class PlacementModuleFloating implements PlacementModule { + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, (context, state, ignored) -> state.y = state.rty); + } + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java new file mode 100644 index 000000000..8ddb2ee9c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java @@ -0,0 +1,57 @@ +package art.arcane.iris.engine.object.placement; + +public final class PlacementModuleHeight implements PlacementModule { + private final boolean fast; + private final Mode mode; + + public enum Mode { + MIN, + MAX + } + + public PlacementModuleHeight(Mode mode, boolean fast) { + this.fast = fast; + this.mode = mode; + } + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, this::sample); + } + + private void sample(PlacementContext context, PlacementState state, Void ignored) { + int minX = context.x + state.bounds.minX(); + int maxX = context.x + state.bounds.maxX(); + int minZ = context.z + state.bounds.minZ(); + int maxZ = context.z + state.bounds.maxZ(); + if (Mode.MIN == mode) { + state.y = Integer.MAX_VALUE; + } + int xStep = fast ? Math.max(0, (maxX - minX) / 2) + 1 : 1; + int zStep = fast ? Math.max(0, (maxZ - minZ) / 2) + 1 : 1; + for (int i = minX; i <= maxX; i += xStep) { + for (int ii = minZ; ii <= maxZ; ii += zStep) { + columnHeight(context, state, i, ii); + if (state.isRejected()) { + return; + } + } + } + } + + private void columnHeight(PlacementContext context, PlacementState state, int i, int ii) { + int h = state.placer.getHighest(i, ii, context.self.getLoader(), state.config.isUnderwater()) + state.rty; + if (!state.config.isForcePlace()) { + if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, i, h, ii)) { + state.reject("carving-anchor"); + } + } + + if (Mode.MIN == mode && h < state.y) { + state.y = h; + } + if (Mode.MAX == mode && h > state.y) { + state.y = h; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java new file mode 100644 index 000000000..f2ec8852d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java @@ -0,0 +1,34 @@ +package art.arcane.iris.engine.object.placement; + +/** Water, cave clearance and height-clamp eligibility. */ +final class PlacementModuleLimits implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.limits"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + if (config.isForcePlace() || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE) { + return; + } + if (context.yv < 0 && config.getMode() != ObjectPlaceMode.FLOATING + && !config.isUnderwater() && !config.isOnwater() + && state.placer.isUnderwater(context.x, context.z)) { + state.reject("underwater-anchor"); + return; + } + if (context.caveResult != null + && Math.max(0, context.self.h + state.yrand + state.ty) + 1 >= context.caveResult.getHeight()) { + state.reject("cave-clearance"); + return; + } + if (config.isUnderwater() && state.y + state.rty + state.ty >= state.placer.getFluidHeight()) { + state.reject("fluid-height"); + return; + } + if (!config.getClamp().canPlace(state.y + state.rty + state.ty, state.y - state.rty + state.ty)) { + state.reject("height-clamp"); + } + }, PlacementModuleSurfaceSupport.CHECK); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java new file mode 100644 index 000000000..d535586ae --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java @@ -0,0 +1,113 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStructureVolume; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.collection.KList; + +/** Native structures remain protected even when forcePlace bypasses optional placement checks. */ +final class PlacementModuleNativeStructureProtection implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.native-structures"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + if (state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE && vetoes(context, state)) { + state.reject("native-structure"); + } + }, PlacementModuleLimits.CHECK); + } + + private static boolean vetoes(PlacementContext context, PlacementState state) { + IrisObject self = context.self; + IObjectPlacer placer = state.placer; + IrisObjectPlacement config = state.config; + ObjectSpinKernel spin = state.spin; + IrisBlockVector translateOffset = state.translateOffset; + boolean translating = translateOffset != null; + boolean ceilingHang = config.getMode() == ObjectPlaceMode.CEILING_HANG; + boolean paint = context.yv < 0 && config.getMode() == ObjectPlaceMode.PAINT; + int warpMargin = state.warpMargin; + int x = context.x; + int y = state.y + state.yrand; + int z = context.z; + Engine engine = placer.getEngine(); + if (engine == null) { + return false; + } + + int margin = (Math.max(self.getW(), Math.max(self.getH(), self.getD())) / 2) + 1 + warpMargin; + if (translating) { + margin += Math.max(Math.abs(translateOffset.getBlockX()), + Math.max(Math.abs(translateOffset.getBlockY()), Math.abs(translateOffset.getBlockZ()))); + } + + KList volumes = engine.getNativeStructureVolumes(x - margin, z - margin, x + margin, z + margin); + if (volumes == null || volumes.isEmpty()) { + return false; + } + + int worldY = y + engine.getMinHeight(); + int envelopeMinY = paint ? Integer.MIN_VALUE : worldY - margin; + int envelopeMaxY = paint ? Integer.MAX_VALUE : worldY + margin; + boolean envelopeMeetsPiece = false; + for (NativeStructureVolume volume : volumes) { + if (volume.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { + envelopeMeetsPiece = true; + break; + } + } + + if (!envelopeMeetsPiece) { + return false; + } + + self.readLock.lock(); + try { + VectorMap.Cursor cursor = self.blocks.cursor(); + while (cursor.next()) { + PlatformBlockState source = cursor.value(); + if (source == null || isAirBlock(source)) { + continue; + } + + IrisBlockVector i = cursor.key().clone(); + spin.rotate(i); + if (ceilingHang) { + i.setY(-i.getBlockY()); + } + if (translating) { + i.add(translateOffset); + } + + int xx = x + (int) Math.round(i.getX()); + int zz = z + (int) Math.round(i.getZ()); + int yy = paint + ? (int) Math.round(i.getY()) + Math.floorDiv(self.h, 2) + + placer.getHighest(xx, zz, self.getLoader(), config.isUnderwater()) + : y + (int) Math.round(i.getY()); + int worldBlockY = yy + engine.getMinHeight(); + + for (NativeStructureVolume volume : volumes) { + if (volume.containsWithin(xx, worldBlockY, zz, warpMargin)) { + return true; + } + } + } + } finally { + self.readLock.unlock(); + } + + return false; + } + + private static boolean isAirBlock(PlatformBlockState state) { + String material = IrisObjectShaping.materialKey(state); + return material.equals("minecraft:air") || material.equals("minecraft:cave_air"); + } + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java new file mode 100644 index 000000000..4f1404e2a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java @@ -0,0 +1,18 @@ +package art.arcane.iris.engine.object.placement; + +public final class PlacementModulePaint implements PlacementModule { + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModuleAnchor.install(lifecycle, PlacementModulePaint::sample); + } + + private static void sample(PlacementContext context, PlacementState state, Void ignored) { + state.y = state.placer.getHighest(context.x, context.z, context.self.getLoader(), state.config.isUnderwater()) + state.rty; + if (!state.config.isForcePlace()) { + if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { + state.reject("carving-anchor"); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java new file mode 100644 index 000000000..a3593ccad --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java @@ -0,0 +1,98 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; +import art.arcane.iris.util.common.math.IrisBlockVector; + +/** Resolves the placer and transforms once, preserving the caller's RNG draw order. */ +final class PlacementModulePreparation implements PlacementModule { + static final PlacementLifecycleDependency PLACER = new PlacementLifecycleDependency("prepare.placer"); + static final PlacementLifecycleDependency TRANSFORMS = new PlacementLifecycleDependency("prepare.transforms"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(PLACER, PlacementStage.PREPARE, (context, state, ignored) -> { + if (state.config.getHeightmap() != null) { + state.placer = new HeightmapObjectPlacer(context.rng, context.x, context.yv, context.z, + state.config, context.placer); + } + }); + lifecycle.add(TRANSFORMS, PlacementStage.PREPARE, PlacementModulePreparation::prepare, + PlacementModuleSlope.SLOPE); + } + + private static void prepare(PlacementContext context, PlacementState state, Void ignored) { + IrisObjectPlacement config = state.config; + IrisObject self = context.self; + if (config.isSmartBore()) { + IrisObjectShaping.ensureSmartBored(self); + } + int spinx = context.rng.imax() / 1000; + int spiny = context.rng.imax() / 1000; + int spinz = context.rng.imax() / 1000; + state.spinX = spinx; + state.spinY = spiny; + state.spinZ = spinz; + state.rty = config.getRotation().rotate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); + state.ty = config.getTranslate().translate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); + state.spin = new ObjectSpinKernel(config.getRotation(), spinx, spiny, spinz); + IrisObjectTranslate translate = config.getTranslate(); + if (translate.canTranslate()) { + state.translateOffset = config.getRotation().rotate( + new IrisBlockVector(translate.getX(), translate.getY(), translate.getZ()), spinx, spiny, spinz); + } + int yrand = translate.getYRandom(); + state.yrand = yrand > 0 ? context.rng.i(0, yrand) : yrand < 0 ? context.rng.i(yrand, 0) : yrand; + state.warpMargin = !config.getWarp().isFlat() ? (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D) : 0; + state.bounds = transformedBounds(self, state.spin, state.translateOffset != null, state.translateOffset, + config.getMode() == ObjectPlaceMode.CEILING_HANG, state.warpMargin); + } + + private static PlacementContext.TransformedBounds transformedBounds(IrisObject self, ObjectSpinKernel spin, boolean translating, IrisBlockVector translateOffset, + boolean ceilingHang, int margin) { + int sourceMinX = -self.getCenter().getBlockX(); + int sourceMaxX = self.getW() - self.getCenter().getBlockX() - 1; + int sourceMinY = -self.getCenter().getBlockY(); + int sourceMaxY = self.getH() - self.getCenter().getBlockY() - 1; + int sourceMinZ = -self.getCenter().getBlockZ(); + int sourceMaxZ = self.getD() - self.getCenter().getBlockZ() - 1; + int minX = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int minY = Integer.MAX_VALUE; + int maxY = Integer.MIN_VALUE; + int minZ = Integer.MAX_VALUE; + int maxZ = Integer.MIN_VALUE; + + for (int xCorner = 0; xCorner < 2; xCorner++) { + int sourceX = xCorner == 0 ? sourceMinX : sourceMaxX; + for (int yCorner = 0; yCorner < 2; yCorner++) { + int sourceY = yCorner == 0 ? sourceMinY : sourceMaxY; + for (int zCorner = 0; zCorner < 2; zCorner++) { + int sourceZ = zCorner == 0 ? sourceMinZ : sourceMaxZ; + IrisBlockVector corner = new IrisBlockVector(sourceX, sourceY, sourceZ); + spin.rotate(corner); + if (ceilingHang) { + corner.setY(-corner.getBlockY()); + } + if (translating) { + corner.add(translateOffset); + } + int transformedX = (int) Math.round(corner.getX()); + int transformedY = (int) Math.round(corner.getY()); + int transformedZ = (int) Math.round(corner.getZ()); + minX = Math.min(minX, transformedX); + maxX = Math.max(maxX, transformedX); + minY = Math.min(minY, transformedY); + maxY = Math.max(maxY, transformedY); + minZ = Math.min(minZ, transformedZ); + maxZ = Math.max(maxZ, transformedZ); + } + } + } + + return new PlacementContext.TransformedBounds(minX - margin, maxX + margin, minY, maxY, minZ - margin, maxZ + margin); + } + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java new file mode 100644 index 000000000..bd8618767 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java @@ -0,0 +1,72 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.util.project.stream.ProceduralStream; + +/** Slope checks precede random rotation and leave the caller's configuration intact. */ +final class PlacementModuleSlope implements PlacementModule { + static final PlacementLifecycleDependency SLOPE = new PlacementLifecycleDependency("prepare.slope"); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(SLOPE, PlacementStage.PREPARE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + boolean evaluate = !config.isForcePlace() && !config.getSlopeCondition().isDefault(); + if (!evaluate && !config.isRotateTowardsSlope()) { + return; + } + Engine engine = state.placer.getEngine(); + if (engine == null) { + throw new IllegalStateException("Object placement requires an active Iris engine for slope settings."); + } + if (evaluate && !config.getSlopeCondition().isValid( + engine.getComplex().getSlopeStream().get(context.x, context.z))) { + state.reject("slope"); + return; + } + if (config.isRotateTowardsSlope()) { + state.config = rotate(context.self, config, engine, context.x, context.z); + } + }, PlacementModulePreparation.PLACER); + } + + private static IrisObjectPlacement rotate(IrisObject self, IrisObjectPlacement config, Engine engine, int x, int z) { + int slopeRotationY = 0; + ProceduralStream heightStream = engine.getComplex().getHeightStream(); + // Whichever side of the rectangle that bounds the object is lowest is the 'direction' of the slope (simply said). + double hNorth = heightStream.get(x, z + ((float) self.d) / 2); + double hEast = heightStream.get(x + ((float) self.w) / 2, z); + double hSouth = heightStream.get(x, z - ((float) self.d) / 2); + double hWest = heightStream.get(x - ((float) self.w) / 2, z); + double min = Math.min(Math.min(hNorth, hEast), Math.min(hSouth, hWest)); + if (min == hNorth) { + slopeRotationY = 0; + } else if (min == hEast) { + slopeRotationY = 90; + } else if (min == hSouth) { + slopeRotationY = 180; + } else if (min == hWest) { + slopeRotationY = 270; + } + + double newRotation = config.getRotation().getYAxis().getMin() + slopeRotationY; + IrisObjectRotation originalRotation = config.getRotation(); + IrisObjectRotation slopeRotation = new IrisObjectRotation(); + slopeRotation.setXAxis(originalRotation.getXAxis()); + slopeRotation.setZAxis(originalRotation.getZAxis()); + if (newRotation == 0) { + slopeRotation.setYAxis(new IrisAxisRotationClamp(false, false, 0, 0, 90)); + slopeRotation.setEnabled(originalRotation.canRotateX() || originalRotation.canRotateZ()); + } else { + slopeRotation.setYAxis(new IrisAxisRotationClamp(true, false, newRotation, newRotation, 90)); + slopeRotation.setEnabled(true); + } + config = config.toPlacement(config.getPlace().toArray(new String[0])); + config.setRotation(slopeRotation); + return config; + } + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java new file mode 100644 index 000000000..0a452c6c9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java @@ -0,0 +1,45 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.math.Position2; +import art.arcane.volmlib.util.math.RNG; + +/** Snow uses only successful object writes, and follows stilt or vacuum work. */ +final class PlacementModuleSnow implements PlacementModule { + static final PlacementLifecycleDependency COLLECT = new PlacementLifecycleDependency("snow.collect"); + static final PlacementLifecycleDependency FINISH = new PlacementLifecycleDependency("snow.finish"); + private final PlacementLifecycleDependency after; + + PlacementModuleSnow(PlacementLifecycleDependency after) { + this.after = after; + } + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(COLLECT, PlacementStage.BLOCK_WRITTEN, (context, state, block) -> { + if (!(state.config.getSnow() > 0)) { + return; + } + if (state.snowHeights == null) { + state.snowHeights = new KMap<>(); + } + Position2 position = new Position2(block.x(), block.z()); + Integer current = state.snowHeights.get(position); + if (current == null || current < block.y()) { + state.snowHeights.put(position, block.y()); + } + }); + lifecycle.add(FINISH, PlacementStage.AFTER_BLOCKS, (context, state, ignored) -> { + if (state.snowHeights == null) { + return; + } + RNG rng = context.rng.nextParallelRNG(3468854); + for (Position2 position : state.snowHeights.k()) { + int height = rng.i(0, (int) (state.config.getSnow() * 7)); + state.placer.set(position.getX(), state.snowHeights.get(position) + 1, position.getZ(), + IrisObject.States.SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); + } + }, COLLECT, after); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java new file mode 100644 index 000000000..67fd1b62b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java @@ -0,0 +1,317 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.material.BlockDataMergeSupport; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.math.RNG; + +/** Stilt preparation observes all transformed blocks before the fill step runs. */ +public final class PlacementModuleStilt implements PlacementModule { + static final PlacementLifecycleDependency BOUNDS = new PlacementLifecycleDependency("stilt.bounds"); + static final PlacementLifecycleDependency FILL = new PlacementLifecycleDependency("stilt.fill"); + + private final boolean fast; + private final Mode mode; + + public enum Mode { + DEFAULT, CENTER, MIN, ERODE, ORGANIC, CEILING + } + + public PlacementModuleStilt(Mode mode, boolean fast) { + this.mode = mode; + this.fast = fast; + } + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + PlacementModule height = switch (mode) { + case CENTER, ORGANIC, CEILING -> new PlacementModuleCenterHeight(); + case MIN -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, fast); + case DEFAULT, ERODE -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, fast); + }; + height.install(lifecycle); + if (mode == Mode.CEILING) { + new ObjectModuleCeilingHang().install(lifecycle); + } + PlacementLifecycleDependency[] prerequisites = mode == Mode.CEILING + ? new PlacementLifecycleDependency[]{PlacementModuleAnchor.HEIGHT, ObjectModuleCeilingHang.FLIP} + : new PlacementLifecycleDependency[]{PlacementModuleAnchor.HEIGHT}; + lifecycle.add(BOUNDS, PlacementStage.COLLECT_BLOCK, (context, state, block) -> { + if (IrisObjectShaping.shouldStilt(block.data())) { + state.stiltLowest = Math.min(state.stiltLowest, block.vector().getBlockY()); + state.stiltHighest = Math.max(state.stiltHighest, block.vector().getBlockY()); + } + }, prerequisites); + lifecycle.add(FILL, PlacementStage.AFTER_BLOCKS, this::fill, PlacementModuleAnchor.HEIGHT, BOUNDS, PlacementModuleBlocks.COMPLETE); + } + + private void fill(PlacementContext context, PlacementState state, Void ignored) { + if (state.stiltLowest == Integer.MAX_VALUE) { + return; + } + IrisObject self = context.self; + IrisObjectPlacement config = state.config; + IObjectPlacer placer = state.placer; + IrisData rdata = context.rdata; + RNG rng = context.rng; + ObjectSpinKernel spin = state.spin; + IrisBlockVector translateOffset = state.translateOffset; + boolean translating = translateOffset != null; + boolean ceilingHang = mode == Mode.CEILING; + boolean organic = mode == Mode.ORGANIC || ceilingHang; + boolean eroding = mode == Mode.ERODE; + boolean hasEdits = !config.getEdit().isEmpty(); + boolean warped = !config.getWarp().isFlat(); + CNG surfaceWarp = warped ? config.getSurfaceWarp(rng, self.getLoader()) : null; + double warpHalf = warped ? config.getWarp().getMultiplier() / 2D : 0D; + int x = context.x; + int z = context.z; + int y = state.y; + int lowest = state.stiltLowest; + int topLayer = state.stiltHighest; + int xx, zz; + self.readLock.lock(); + try { + VectorMap blocks = self.blocks; + IrisStiltSettings settings = config.getStiltSettings(); + + double erodeCentroidX = 0; + double erodeCentroidZ = 0; + double erodeMaxDist = 1; + if (eroding) { + int centroidCount = 0; + VectorMap.Cursor centroidCursor = blocks.cursor(); + while (centroidCursor.next()) { + IrisBlockVector rot = centroidCursor.key().clone(); + spin.rotate(rot); + if (translating) { + rot.add(translateOffset); + } + if (rot.getBlockY() == lowest) { + PlatformBlockState bd = centroidCursor.value(); + if (bd != null && IrisObjectShaping.shouldStilt(bd)) { + erodeCentroidX += rot.getX(); + erodeCentroidZ += rot.getZ(); + centroidCount++; + } + } + } + if (centroidCount > 0) { + erodeCentroidX /= centroidCount; + erodeCentroidZ /= centroidCount; + } + VectorMap.Cursor spreadCursor = blocks.cursor(); + while (spreadCursor.next()) { + IrisBlockVector rot = spreadCursor.key().clone(); + spin.rotate(rot); + if (translating) { + rot.add(translateOffset); + } + if (rot.getBlockY() == lowest) { + PlatformBlockState bd = spreadCursor.value(); + if (bd != null && IrisObjectShaping.shouldStilt(bd)) { + double dx = rot.getX() - erodeCentroidX; + double dz = rot.getZ() - erodeCentroidZ; + double dist = Math.sqrt(dx * dx + dz * dz); + if (dist > erodeMaxDist) { + erodeMaxDist = dist; + } + } + } + } + } + + VectorMap.Cursor stiltCursor = blocks.cursor(); + while (stiltCursor.next()) { + IrisBlockVector g = stiltCursor.key(); + PlatformBlockState sourceData; + try { + sourceData = stiltCursor.value(); + } catch (Throwable e) { + IrisLogging.reportError(e); + IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (stilt cme)"); + sourceData = IrisObject.States.AIR; + } + + if (sourceData == null) { + IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (stilt null)"); + sourceData = IrisObject.States.AIR; + } + + if (!IrisObjectShaping.shouldStilt(sourceData)) { + continue; + } + + PlatformBlockState d = sourceData; + if (settings != null && settings.getPalette() != null) { + d = config.getStiltSettings().getPalette().get(rng, x, y, z, rdata); + } else { + String mat = IrisObjectShaping.materialKey(d); + if (mat.equals("minecraft:grass_block") || mat.equals("minecraft:mycelium") || mat.equals("minecraft:podzol") || mat.equals("minecraft:dirt_path")) { + d = B.getState("minecraft:dirt"); + } + } + + IrisBlockVector i = g.clone(); + spin.rotate(i); + if (ceilingHang) { + i.setY(-i.getBlockY()); + } + if (translating) { + i.add(translateOffset); + } + d = spin.rotate(d); + + int targetLayer = ceilingHang ? topLayer : lowest; + if (i.getBlockY() != targetLayer) + continue; + + if (hasEdits) { + for (IrisObjectReplace j : config.getEdit()) { + if (rng.chance(j.getChance())) { + for (PlatformBlockState k : j.getFind(rdata)) { + if (d == null) { + continue; + } + if (j.isExact() ? k.matches(d) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(d))) { + PlatformBlockState newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata); + + if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(d))) { + d = BlockDataMergeSupport.merge(d, newData); + } else { + d = newData; + } + } + } + } + } + } + + if (d == null || !d.isOccluding()) + continue; + + xx = x + (int) Math.round(i.getX()); + zz = z + (int) Math.round(i.getZ()); + + if (warped) { + xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getX() + x, i.getY() + y, i.getZ() + z); + zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getZ() + z, i.getY() + y, i.getX() + x); + } + + if (organic) { + int startY = targetLayer + y; + int maxScan = settings != null ? Math.max(1, settings.getOrganicMaxScan()) : 48; + int jitterMax = settings != null ? Math.max(0, settings.getOrganicJitter()) : 3; + double scratch = settings != null ? Math.max(0, Math.min(1, settings.getOrganicScratch())) : 0.55; + long colHash = ((long) xx * 341873128712L) ^ ((long) zz * 132897987541L); + int jitter = jitterMax > 0 ? (int) (Math.abs(colHash) % (jitterMax + 1)) : 0; + + if (ceilingHang) { + int scan = 0; + int solidY = startY + 1; + while (scan < maxScan && !placer.isSolid(xx, solidY, zz)) { + solidY++; + scan++; + } + int topBound = (scan < maxScan ? solidY - 1 : startY + Math.min(maxScan, 8)) - jitter; + int total = topBound - startY; + for (int j = startY; j <= topBound; j++) { + if (scratch > 0 && total > 0) { + double ratio = (double) (j - startY) / total; + if (ratio > (1.0 - scratch)) { + long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); + double skipChance = (ratio - (1.0 - scratch)) / scratch; + if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { + continue; + } + } + } + placer.set(xx, j, zz, d); + } + } else { + int scan = 0; + int solidY = startY - 1; + while (scan < maxScan && !placer.isSolid(xx, solidY, zz)) { + solidY--; + scan++; + } + int bottomBound = (scan < maxScan ? solidY + 1 : startY - Math.min(maxScan, 8)) + jitter; + int total = startY - bottomBound; + for (int j = startY; j >= bottomBound; j--) { + if (scratch > 0 && total > 0) { + double ratio = (double) (startY - j) / total; + if (ratio > (1.0 - scratch)) { + long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); + double skipChance = (ratio - (1.0 - scratch)) / scratch; + if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { + continue; + } + } + } + placer.set(xx, j, zz, d); + } + } + continue; + } + + int highest = placer.getHighest(xx, zz, self.getLoader(), true); + + if (IrisProceduralBlocks.hasProperty(d, "waterlogged") && ObjectBlockPass.shouldAutoWaterlogBlock(context, state, xx, highest, zz)) { + d = d.withProperty("waterlogged", "true"); + } + + int lowerBound = highest - 1; + if (settings != null) { + lowerBound -= config.getStiltSettings().getOverStilt() - rng.i(0, config.getStiltSettings().getYRand()); + if (settings.getYMax() != 0) + lowerBound -= Math.min(config.getStiltSettings().getYMax() - (lowest + y - highest), 0); + } + + if (eroding) { + double dx = i.getX() - erodeCentroidX; + double dz = i.getZ() - erodeCentroidZ; + double normalizedDist = Math.sqrt(dx * dx + dz * dz) / erodeMaxDist; + normalizedDist = Math.min(normalizedDist, 1.0); + int totalDepth = (lowest + y) - lowerBound; + int erodeDepth = (int) (totalDepth * Math.pow(1.0 - normalizedDist, 1.5)); + lowerBound = (lowest + y) - erodeDepth; + } + + for (int j = lowest + y; j > lowerBound; j--) { + PlatformBlockState fluidState = placer.get(xx, j, zz); + if (B.isFluid(fluidState)) { + break; + } + if (eroding) { + int depth = (lowest + y) - j; + int totalDepth = (lowest + y) - lowerBound; + double depthRatio = totalDepth > 0 ? (double) depth / totalDepth : 0; + if (depthRatio > 0.4) { + long hash = ((long) (xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L)); + double skipChance = (depthRatio - 0.4) / 0.6; + if ((Math.abs(hash) % 1000) / 1000.0 < skipChance * 0.7) { + continue; + } + } + } + + if (B.isVineBlock(d)) { + d = ObjectBlockPass.attachVineFaces(placer, d, xx, j, zz); + } + placer.set(xx, j, zz, d); + } + + } + } finally { + self.readLock.unlock(); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java new file mode 100644 index 000000000..1bfaf8e91 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java @@ -0,0 +1,67 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.spi.IrisLogging; +import java.util.concurrent.ConcurrentHashMap; + +/** Carving and surface support rules, including the bedrock diagnostic. */ +final class PlacementModuleSurfaceSupport implements PlacementModule { + static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.surface"); + private static final long IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS = 5000L; + private static final ConcurrentHashMap IMPLAUSIBLE_BEDROCK_WARNS = new ConcurrentHashMap<>(); + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { + IrisObjectPlacement config = state.config; + boolean rawStructurePiece = config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE; + if (context.yv < 0 && !config.isForcePlace() && !config.isFromBottom() + && config.getMode() != ObjectPlaceMode.FLOATING && !rawStructurePiece + && config.getCarvingSupport().supportsSurface() && state.placer.getEngine() != null + && state.placer.getEngine().getDimension().isBedrock() && state.y <= 1) { + warnImplausibleBedrockPlacement(context.self, state.placer, config, context.x, state.y, context.z); + state.reject("bedrock-anchor"); + return; + } + boolean surfaceAnchored = context.yv < 0 ? config.getCarvingSupport().supportsSurface() + : config.getCarvingSupport() == CarvingMode.SURFACE_ONLY; + if (surfaceAnchored && !config.isForcePlace() && !config.isFromBottom() + && config.getMode() != ObjectPlaceMode.FLOATING && !rawStructurePiece + && !config.isUnderwater() && !config.isOnwater() && config.isRequireSurfaceSupport() + && IrisSurfaceSupport.isUnsupported(context.placer, context.self.getLoader(), context.x, context.z, + config.getTranslate(), config.getRotation(), state.spinX, state.spinY, state.spinZ, + context.self.getSurfaceSupportOffsets(), config.getSurfaceSupportBuffer(), config.getSurfaceSupportDepth())) { + state.reject("surface-support"); + } + }, PlacementModuleAnchor.POSITIONED); + } + + static boolean rejectsAnchor(PlacementContext context, PlacementState state, int x, int y, int z) { + return switch (state.config.getCarvingSupport()) { + case SURFACE_ONLY -> state.placer.isCarved(x, y, z); + case CARVING_ONLY -> !(state.placer.isCarved(x, y, z) || state.placer.isCarved(x, y - 1, z) + || state.placer.isCarved(x, y - 2, z) || state.placer.isCarved(x, y - 3, z)); + case ANYWHERE -> false; + }; + } + + private static void warnImplausibleBedrockPlacement(IrisObject self, IObjectPlacer placer, IrisObjectPlacement config, int x, int y, int z) { + String key = self.getLoadKey(); + String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); + long now = System.currentTimeMillis(); + Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); + if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { + return; + } + IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); + IrisLogging.warn("Implausible object placement rejected: " + + (key == null ? "" : key) + + " resolved anchorY=" + y + " at (" + x + "," + z + ") mode=" + config.getMode() + + " carving=" + config.getCarvingSupport() + + ". Surface-anchored placement should never land on the bedrock row. " + + "Height sampling returned a bogus value — not configured for floor placement " + + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); + } + +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java new file mode 100644 index 000000000..564cc2fe9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java @@ -0,0 +1,90 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.noise.SimplexNoise; + +/** Collects written object bounds, then bends terrain to meet them. Installed for vacuum modes. */ +final class PlacementModuleVacuum implements PlacementModule { + static final PlacementLifecycleDependency COLLECT = new PlacementLifecycleDependency("vacuum.collect"); + static final PlacementLifecycleDependency FINISH = new PlacementLifecycleDependency("vacuum.finish"); + private static final long VACUUM_WAVE_SEED = 7392113L; + + @Override + public void install(PlacementLifecycleBuilder lifecycle) { + lifecycle.add(COLLECT, PlacementStage.BLOCK_WRITTEN, (context, state, block) -> { + state.vacuumLowest = Math.min(state.vacuumLowest, block.y()); + state.vacuumHighest = Math.max(state.vacuumHighest, block.y()); + }); + lifecycle.add(FINISH, PlacementStage.AFTER_BLOCKS, (context, state, ignored) -> { + if (state.vacuumLowest == Integer.MAX_VALUE || state.placer.getEngine() == null) { + return; + } + vacuumTerrain(context.self, state.placer, state.config, context.x, context.z, + state.bounds.minX(), state.bounds.maxX(), state.bounds.minZ(), state.bounds.maxZ(), + state.vacuumLowest, state.vacuumHighest); + }, COLLECT, PlacementModuleBlocks.COMPLETE); + } + + private static void vacuumTerrain(IrisObject self, IObjectPlacer placer, IrisObjectPlacement config, int centerX, int centerZ, int lowX, int highX, int lowZ, int highZ, int baseY, int topY) { + ObjectPlaceMode mode = config.getMode(); + IrisVacuumSettings settings = config.getVacuumSettings(); + int radius = IrisObjectVacuum.resolveRadius(mode, settings); + int step = IrisObjectVacuum.resolveStep(mode); + double falloff = IrisObjectVacuum.resolveFalloff(settings); + int jitter = settings != null ? Math.max(0, settings.getOrganicJitter()) : 4; + boolean organicEdge = mode == ObjectPlaceMode.VACUUM_ORGANIC; + boolean wavyEdge = mode == ObjectPlaceMode.VACUUM_WAVY; + double waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); + double waveScale = IrisObjectVacuum.resolveWaveScale(settings); + SimplexNoise waveNoise = (wavyEdge && waveAmplitude > 0) ? new SimplexNoise(VACUUM_WAVE_SEED) : null; + int meetY = baseY - 1; + + IrisComplex complex = placer.getEngine().getComplex(); + int worldMin = placer.getEngine().getMinHeight(); + int worldMax = worldMin + placer.getEngine().getHeight() - 1; + + for (int dx = lowX - radius; dx <= highX + radius; dx += step) { + for (int dz = lowZ - radius; dz <= highZ + radius; dz += step) { + int cx = centerX + dx; + int cz = centerZ + dz; + double effRadius = radius; + if (organicEdge && jitter > 0) { + long h = ((long) cx * 341873128712L) ^ ((long) cz * 132897987541L); + double n = ((Math.abs(h) % 1000) / 1000.0) - 0.5; + effRadius = Math.max(1.0, radius + (n * 2.0 * jitter)); + } + int origY = placer.getHighest(cx, cz, self.getLoader(), true); + int targetY = IrisObjectVacuum.columnTargetY(dx, dz, lowX, highX, lowZ, highZ, effRadius, falloff, origY, meetY); + if (waveNoise != null) { + int outX = IrisObjectVacuum.outset(dx, lowX, highX); + int outZ = IrisObjectVacuum.outset(dz, lowZ, highZ); + double waveDistance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); + double sample = waveNoise.noiseSigned(cx * waveScale, cz * waveScale); + targetY += IrisObjectVacuum.waveOffset(waveDistance, effRadius, sample, waveAmplitude); + } + if (targetY == origY) { + continue; + } + targetY = Math.max(worldMin + 1, Math.min(worldMax, targetY)); + if (targetY > origY) { + PlatformBlockState fill = complex != null ? complex.getRockStream().get(cx, cz) : null; + if (B.isAir(fill)) { + fill = IrisObject.States.STONE; + } + for (int yy = origY + 1; yy <= targetY; yy++) { + placer.set(cx, yy, cz, fill); + } + } else if (targetY < origY) { + boolean inside = IrisObjectVacuum.outset(dx, lowX, highX) == 0 && IrisObjectVacuum.outset(dz, lowZ, highZ) == 0; + int carveFloor = IrisObjectVacuum.carveFloorY(targetY, topY, inside); + for (int yy = origY; yy >= carveFloor; yy--) { + placer.set(cx, yy, cz, IrisObject.States.AIR); + } + } + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java new file mode 100644 index 000000000..342918a9b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java @@ -0,0 +1,38 @@ +package art.arcane.iris.engine.object.placement; + +import java.util.List; + +/** + * Whole-placement phases surround a nested block pass. TRANSFORM_BLOCK runs after rotation and + * before translation; COLLECT_BLOCK runs before edits; BLOCK_WRITTEN runs only for successful + * object writes. Block prerequisites refer to the current block. AFTER_BLOCKS waits for the + * entire block pass, including markers. All whole-placement validation precedes world writes. + */ +public final class PlacementStage { + public static final PlacementStage PREPARE = new PlacementStage<>("prepare", 0); + public static final PlacementStage HEIGHT = new PlacementStage<>("height", 1); + public static final PlacementStage VALIDATE = new PlacementStage<>("validate", 2); + public static final PlacementStage BEFORE_BLOCKS = new PlacementStage<>("before-blocks", 3); + public static final PlacementStage TRANSFORM_BLOCK = new PlacementStage<>("transform-block", 4); + public static final PlacementStage COLLECT_BLOCK = new PlacementStage<>("collect-block", 5); + public static final PlacementStage BLOCK_WRITTEN = new PlacementStage<>("block-written", 6); + // BLOCKS denotes completion of the whole pass, so later steps can depend on all block work. + public static final PlacementStage BLOCKS = new PlacementStage<>("blocks", 7); + public static final PlacementStage AFTER_BLOCKS = new PlacementStage<>("after-blocks", 8); + static final List> ALL = List.of(PREPARE, HEIGHT, VALIDATE, BEFORE_BLOCKS, + TRANSFORM_BLOCK, COLLECT_BLOCK, BLOCK_WRITTEN, BLOCKS, AFTER_BLOCKS); + static final List> BEFORE_PASS = List.of(PREPARE, HEIGHT, VALIDATE, BEFORE_BLOCKS); + + private final String name; + final int order; + + private PlacementStage(String name, int order) { + this.name = name; + this.order = order; + } + + @Override + public String toString() { + return name; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java new file mode 100644 index 000000000..c5def6945 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java @@ -0,0 +1,67 @@ +package art.arcane.iris.engine.object.placement; + +import art.arcane.iris.engine.object.placement.PlacementContext.TransformedBounds; +import art.arcane.iris.engine.object.placement.PlacementContext.WorldBounds; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.math.Position2; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; + +import java.util.Objects; + +/** Results and accumulators owned by one placement, never by a shared module or plan. */ +@Getter +@Setter +public final class PlacementState { + IrisObjectPlacement config; + IObjectPlacer placer; + ObjectSpinKernel spin; + int spinX; + int spinY; + int spinZ; + IrisBlockVector translateOffset; + int rty; + int ty; + int yrand; + int warpMargin; + int y; + TransformedBounds bounds; + WorldBounds worldBounds; + int stiltLowest = Integer.MAX_VALUE; + int stiltHighest = Integer.MIN_VALUE; + int vacuumLowest = Integer.MAX_VALUE; + int vacuumHighest = Integer.MIN_VALUE; + KMap snowHeights; + + @Setter(AccessLevel.NONE) + private String rejection; + + PlacementState(PlacementContext context) { + this(-1, null); + config = context.config; + placer = context.placer; + } + + PlacementState(int y, TransformedBounds bounds) { + this.y = y; + this.bounds = bounds; + } + + /** The first rejection is terminal. Each guard decides whether forcePlace exempts its rule. */ + public void reject(String reason) { + Objects.requireNonNull(reason, "Rejection reason"); + if (rejection == null) { + rejection = reason; + } + } + + public boolean isRejected() { + return rejection != null; + } + + public int heightOrRejected() { + return isRejected() ? -1 : y; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java new file mode 100644 index 000000000..dc55cdd01 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java @@ -0,0 +1,96 @@ +/* + * 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.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.volmlib.util.math.M; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("axis-rotation") +@Accessors(chain = true) +@AllArgsConstructor +@NoArgsConstructor +@Desc("Represents a rotation axis with intervals and maxes. The x and z axis values are defaulted to disabled. The Y axis defaults to on, rotating by 90 degree increments.") +@Data +public class IrisAxisRotationClamp { + @Desc("Should this axis be rotated at all?") + private boolean enabled = false; + + private transient boolean forceLock = false; + + @Required + @DependsOn({"max"}) + @MinNumber(-360) + @MaxNumber(360) + @Desc("The minimum angle (from) or set this and max to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") + private double min = 0; + + @Required + @DependsOn({"min"}) + @MinNumber(-360) + @MaxNumber(360) + @Desc("The maximum angle (to) or set this and min to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") + private double max = 0; + + @Required + @DependsOn({"min", "max"}) + @MinNumber(0) + @MaxNumber(360) + @Desc("Iris spins the axis but not freely. For example an interval of 90 would mean 4 possible angles (right angles) degrees. \nSetting this to 0 means totally free rotation.\n\nNote that a lot of structures can have issues with non 90 degree intervals because the minecraft block resolution is so low.") + private double interval = 0; + + public void minMax(double fd) { + min = fd; + max = fd; + forceLock = true; + } + + public boolean isUnlimited() { + return min == max && min == 0; + } + + public boolean isLocked() { + return min == max && !isUnlimited(); + } + + public double getRadians(int rng) { + if (forceLock) { + return Math.toRadians(Math.ceil(Math.abs((max % 360D)))); + } + + if (isUnlimited()) { + double resolvedInterval = interval < 1 ? 1 : interval; + return Math.toRadians((resolvedInterval * (Math.ceil(Math.abs((rng % 360D) / resolvedInterval)))) % 360D); + } + + if (min == max && min != 0) { + return Math.toRadians(max); + } + + return Math.toRadians(M.clip((interval * (Math.ceil(Math.abs((rng % 360D) / interval)))) % 360D, Math.min(min, max), Math.max(min, max))); + } +} 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 new file mode 100644 index 000000000..a4c6102b4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -0,0 +1,372 @@ +/* + * 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.placement.FloatingObjectFootprint; +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisObjectPlacementRunner; +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.loader.IrisRegistrant; +import art.arcane.iris.engine.data.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.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.AxisAlignedBB; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.math.IrisVector; +import art.arcane.iris.util.common.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 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 IrisObjectPlacementRunner} + * (world placement). + */ +@Accessors(chain = true) +@EqualsAndHashCode(callSuper = false) +public class IrisObject extends IrisRegistrant { + 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<>(); + @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); + } + + surfaceSupportOffsets.reset(); + floatingFootprint.reset(); + } + + 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); + } + } + + 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); + } + } + + surfaceSupportOffsets.reset(); + floatingFootprint.reset(); + } + + 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); + } + + public int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, BiConsumer listener, CarveResult c, IrisData rdata) { + return new IrisObjectPlacementRunner(this).place(x, yv, z, oplacer, config, rng, listener, c, rdata); + } + + 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(); + } + } + + 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 new file mode 100644 index 000000000..338fcc6c1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java @@ -0,0 +1,396 @@ +/* + * 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.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.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.surfaceSupportOffsets.reset(); + self.floatingFootprint.reset(); + 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.surfaceSupportOffsets.reset(); + self.floatingFootprint.reset(); + 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/IrisObjectPlacementScaleInterpolator.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java new file mode 100644 index 000000000..4df6edd8a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java @@ -0,0 +1,33 @@ +/* + * 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; + +@Desc("Use 3D Interpolation on scaled objects if they are larger than the origin.") +public enum IrisObjectPlacementScaleInterpolator { + @Desc("Don't interpolate, big cubes") + NONE, + @Desc("Uses linear interpolation in 3 dimensions, generally pretty good, but slow") + TRILINEAR, + @Desc("Uses cubic spline interpolation in 3 dimensions, even better, but extreme slowdowns") + TRICUBIC, + @Desc("Uses hermite spline interpolation in 3 dimensions, even better, but extreme slowdowns") + TRIHERMITE +} 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 new file mode 100644 index 000000000..330fcbe75 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java @@ -0,0 +1,540 @@ +/* + * 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.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.iris.util.common.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 IrisAxisRotationClamp xAxis = new IrisAxisRotationClamp(); + + @Desc("The y axis rotation") + private IrisAxisRotationClamp yAxis = new IrisAxisRotationClamp(true, false, 0, 0, 90); + + @Desc("The z axis rotation") + private IrisAxisRotationClamp zAxis = new IrisAxisRotationClamp(); + + public static IrisObjectRotation xFlip180() { + IrisObjectRotation rt = new IrisObjectRotation(); + IrisAxisRotationClamp rtx = new IrisAxisRotationClamp(); + IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); + IrisAxisRotationClamp rtz = new IrisAxisRotationClamp(); + rt.setEnabled(true); + rt.setXAxis(rtx); + rt.setYAxis(rty); + rt.setZAxis(rtz); + rtx.setEnabled(true); + rtx.minMax(180); + rty.setEnabled(false); + rtz.setEnabled(false); + return rt; + } + + public static IrisObjectRotation xFlip180RandomY() { + IrisObjectRotation rt = xFlip180(); + rt.setYAxis(new IrisAxisRotationClamp(true, false, 0, 0, 90)); + return rt; + } + + public static IrisObjectRotation xFlip180WithY(double y) { + IrisObjectRotation rt = xFlip180(); + IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); + rty.setEnabled(true); + rty.setInterval(90); + rty.minMax(y); + rt.setYAxis(rty); + return rt; + } + + public static IrisObjectRotation of(double x, double y, double z) { + IrisObjectRotation rt = new IrisObjectRotation(); + IrisAxisRotationClamp rtx = new IrisAxisRotationClamp(); + IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); + IrisAxisRotationClamp rtz = new IrisAxisRotationClamp(); + rt.setEnabled(x != 0 || y != 0 || z != 0); + rt.setXAxis(rtx); + rt.setYAxis(rty); + rt.setZAxis(rtz); + rtx.setEnabled(x != 0); + rty.setEnabled(y != 0); + rtz.setEnabled(z != 0); + rtx.setInterval(90); + rty.setInterval(90); + rtz.setInterval(90); + rtx.minMax(x); + rty.minMax(y); + rtz.minMax(z); + + 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, IrisAxisRotationClamp clamp) { + if (!enabled) { + return 0; + } + + if (!clamp.isEnabled()) { + 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().getMax()) % 360D == 180D) { + v.setZ(-v.getZ()); + v.setY(-v.getY()); + } else if (getXAxis().getMax() % 360D == 90D || getXAxis().getMax() % 360D == -270D) { + double z = v.getZ(); + v.setZ(v.getY()); + v.setY(-z); + } else if (getXAxis().getMax() == -90D || getXAxis().getMax() % 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().getMax()) % 360D == 180D) { + v.setY(-v.getY()); + v.setX(-v.getX()); + } else if (getZAxis().getMax() % 360D == 90D || getZAxis().getMax() % 360D == -270D) { + double y = v.getY(); + v.setY(v.getX()); + v.setX(-y); + } else if (getZAxis().getMax() == -90D || getZAxis().getMax() % 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().getMax()) % 360D == 180D) { + v.setX(-v.getX()); + v.setZ(-v.getZ()); + } else if (getYAxis().getMax() % 360D == 90D || getYAxis().getMax() % 360D == -270D) { + double x = v.getX(); + v.setX(v.getZ()); + v.setZ(-x); + } else if (getYAxis().getMax() == -90D || getYAxis().getMax() % 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.isEnabled(); + } + + public boolean canRotateY() { + return enabled && yAxis.isEnabled(); + } + + public boolean canRotateZ() { + return enabled && zAxis.isEnabled(); + } + + @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 new file mode 100644 index 000000000..b49d6de06 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java @@ -0,0 +1,417 @@ +/* + * 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.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.Snippet; +import art.arcane.iris.util.common.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; + private static final ScaleCache CACHE = new ScaleCache(resolveCacheMaximumEstimatedBytes()); + + public static void invalidate(IrisData owner) { + CACHE.invalidate(owner); + } + + @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); + } + + public IrisObject get(RNG rng, IrisObject origin) { + if (origin == null) { + return null; + } + + ScaleRequest request = snapshotRequest(); + if (!request.shouldScale()) { + return origin; + } + + int variantIndex = request.selectVariant(rng); + CacheKey key = CACHE.key(origin, request, variantIndex); + CacheLookup lookup = CACHE.lookup(key); + if (lookup.variant() != null) { + return lookup.variant(); + } + + synchronized (CACHE.loadLock(key)) { + CacheLookup afterWait = CACHE.lookup(key); + if (afterWait.variant() != null) { + return afterWait.variant(); + } + + IrisObject variant = origin.scaled(request.scaleAt(variantIndex), request.interpolation()); + long estimatedBytes = estimateVariant(variant); + return CACHE.putIfCurrent(key, variant, estimatedBytes, lookup.generation()); + } + } + + public boolean canScaleBeyond() { + return shouldScale() && getMaxScale() > 1; + } + + static int cacheEntryCount() { + return CACHE.size(); + } + + static long cacheEstimatedBytes() { + return CACHE.estimatedBytes(); + } + + static boolean isOriginCached(IrisObject origin) { + return CACHE.containsOrigin(origin); + } + + 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 IrisData owner; + 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.owner = origin.getLoader(); + this.request = request; + this.variantIndex = variantIndex; + this.originRevision = originRevision(origin); + int result = System.identityHashCode(origin); + result = (31 * result) + System.identityHashCode(owner); + result = (31 * result) + originRevision; + result = (31 * result) + request.hashCode(); + this.loadHashCode = result; + this.hashCode = (31 * result) + variantIndex; + } + + boolean belongsTo(IrisData candidate) { + return owner == candidate; + } + + 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() + && owner == other.owner + && 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(); + } + } + } + + record CacheLookup(IrisObject variant, long generation) { + } + + static final class ScaleCache { + private final long maximumEstimatedBytes; + private final LinkedHashMap entries; + private final Object[] loadLocks; + private final ReferenceQueue collectedOrigins; + private long estimatedBytes; + private long generation; + + 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 CacheLookup lookup(CacheKey key) { + drainCollectedOrigins(); + CacheValue value = entries.get(key); + return new CacheLookup(value == null ? null : value.variant(), generation); + } + + synchronized IrisObject putIfCurrent(CacheKey key, IrisObject variant, + long entryEstimatedBytes, long expectedGeneration) { + drainCollectedOrigins(); + CacheValue present = entries.get(key); + if (present != null) { + return present.variant(); + } + if (generation != expectedGeneration || entryEstimatedBytes > maximumEstimatedBytes) { + return variant; + } + + entries.put(key, new CacheValue(variant, entryEstimatedBytes)); + estimatedBytes += entryEstimatedBytes; + evictToBudget(); + return variant; + } + + synchronized void invalidate(IrisData owner) { + drainCollectedOrigins(); + generation++; + Iterator> iterator = entries.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + if (entry.getKey().belongsTo(owner)) { + estimatedBytes -= entry.getValue().estimatedBytes(); + iterator.remove(); + } + } + } + + 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 new file mode 100644 index 000000000..822a54801 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java @@ -0,0 +1,312 @@ +/* + * 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.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.math.IrisVector; +import art.arcane.iris.util.common.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.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.surfaceSupportOffsets.reset(); + self.floatingFootprint.reset(); + } + + 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.surfaceSupportOffsets.reset(); + self.floatingFootprint.reset(); + } + + 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) { + return IrisProceduralBlocks.materialKey(state); + } + + 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 new file mode 100644 index 000000000..abd547264 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java @@ -0,0 +1,370 @@ +/* + * 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.iris.util.common.data.VectorMap; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.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 new file mode 100644 index 000000000..ff57eb6da --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java @@ -0,0 +1,79 @@ +/* + * 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.iris.util.common.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 new file mode 100644 index 000000000..70ed81541 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java @@ -0,0 +1,476 @@ +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.iris.engine.data.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 new file mode 100644 index 000000000..44e7c82c7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/TileData.java @@ -0,0 +1,278 @@ +/* + * 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 new file mode 100644 index 000000000..bc50c7d52 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/prefab/matter/IrisMatterObject.java @@ -0,0 +1,59 @@ +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/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java new file mode 100644 index 000000000..de4ab0c45 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java @@ -0,0 +1,168 @@ +/* + * 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.procedural; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.Map; + +/** + * Shared low-level helpers for building procedural objects in memory: resolving a + * single block id or a noise palette into a platform block state, and assembling a + * raw block map into a centered IrisObject anchored so its y=0 layer sits one block + * above the terrain surface (same convention the tree generator uses). + */ +public final class IrisProceduralBlocks { + public static final String[] FACE_PROPERTIES = {"north", "east", "south", "west", "up", "down"}; + + private IrisProceduralBlocks() { + } + + public static int[] faceOffset(String face) { + return switch (face) { + case "north" -> new int[]{0, 0, -1}; + case "south" -> new int[]{0, 0, 1}; + case "east" -> new int[]{1, 0, 0}; + case "west" -> new int[]{-1, 0, 0}; + case "up" -> new int[]{0, 1, 0}; + default -> new int[]{0, -1, 0}; + }; + } + + public static boolean paletteSet(IrisMaterialPalette palette) { + return palette != null && palette.getPalette() != null && !palette.getPalette().isEmpty(); + } + + public static PlatformBlockState resolve(String block, IrisMaterialPalette palette, IrisData data, int x, int y, int z, RNG paletteRng) { + if (paletteSet(palette)) { + return palette.get(paletteRng, x, y, z, data); + } + if (block != null && !block.isEmpty()) { + return B.getStateOrNull(block, false); + } + return null; + } + + public static boolean hasProperty(PlatformBlockState state, String property) { + String key = state.key(); + int start = propertyStart(key, property); + if (start < 0) { + return false; + } + int valueStart = start + property.length() + 2; + return key.indexOf(',', valueStart) >= 0 || key.indexOf(']', valueStart) >= 0; + } + + 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 String propertyValue(PlatformBlockState state, String property) { + String key = state.key(); + int start = propertyStart(key, property); + if (start < 0) { + return null; + } + int valueStart = start + property.length() + 2; + int end = key.indexOf(',', valueStart); + if (end < 0) { + end = key.indexOf(']', valueStart); + } + if (end < 0) { + return null; + } + return key.substring(valueStart, end); + } + + /** + * Index of the delimiter opening "[property=" or ",property=" within the key, or -1. Scans in place + * rather than building the search needles, and prefers a "[" match over a "," match. + */ + private static int propertyStart(String key, String property) { + int bracket = key.indexOf('['); + if (bracket < 0) { + return -1; + } + int start = delimitedPropertyIndex(key, property, bracket, '['); + return start < 0 ? delimitedPropertyIndex(key, property, bracket, ',') : start; + } + + private static int delimitedPropertyIndex(String key, String property, int from, char delimiter) { + int length = property.length(); + int limit = key.length() - length - 2; + for (int i = key.indexOf(delimiter, from); i >= 0 && i <= limit; i = key.indexOf(delimiter, i + 1)) { + if (key.regionMatches(i + 1, property, 0, length) && key.charAt(i + 1 + length) == '=') { + return i; + } + } + return -1; + } + + public static IrisObject assemble(Map blocks) { + if (blocks == null || blocks.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 (Vector3i v : blocks.keySet()) { + minX = Math.min(minX, v.getBlockX()); + minY = Math.min(minY, v.getBlockY()); + minZ = Math.min(minZ, v.getBlockZ()); + maxX = Math.max(maxX, v.getBlockX()); + maxY = Math.max(maxY, v.getBlockY()); + maxZ = Math.max(maxZ, v.getBlockZ()); + } + + int w = maxX - minX + 1; + int h = maxY - minY + 1; + int d = maxZ - minZ + 1; + int cx = w / 2; + int cy = h / 2; + int cz = d / 2; + + IrisObject object = new IrisObject(w, h, d); + for (Map.Entry entry : blocks.entrySet()) { + Vector3i v = entry.getKey(); + int nx = v.getBlockX() - minX - cx; + int ny = v.getBlockY() - cy + 1; + int nz = v.getBlockZ() - minZ - cz; + object.getBlocks().put(new IrisBlockVector(nx, ny, nz), entry.getValue()); + } + + return object; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java new file mode 100644 index 000000000..1f4201ce8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java @@ -0,0 +1,93 @@ +/* + * 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.procedural; + +import art.arcane.iris.engine.object.procedural.coral.IrisCoral; +import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; +import art.arcane.iris.engine.object.procedural.formation.IrisFormation; +import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.engine.object.procedural.ruin.IrisRuin; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.annotations.ArrayType; +import art.arcane.iris.engine.object.annotations.Desc; +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("procedural-objects") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") +@Data +public class IrisProceduralObjects { + @ArrayType(min = 1, type = IrisProceduralTree.class) + @Desc("Procedurally generated trees.") + private KList trees = new KList<>(); + + @ArrayType(min = 1, type = IrisRuin.class) + @Desc("Procedurally generated ruins (crumbling pillars, walls, arches, rubble).") + private KList ruins = new KList<>(); + + @ArrayType(min = 1, type = IrisFormation.class) + @Desc("Procedurally generated natural rock formations (spires, hoodoos, arches, sea stacks, boulders, basalt columns).") + private KList formations = new KList<>(); + + @ArrayType(min = 1, type = IrisCoral.class) + @Desc("Procedurally generated underwater coral structures.") + private KList coral = new KList<>(); + + @ArrayType(min = 1, type = IrisFungus.class) + @Desc("Procedurally generated mushrooms and shelf fungi.") + private KList fungi = new KList<>(); + + @ArrayType(min = 1, type = IrisCrystal.class) + @Desc("Procedurally generated crystal clusters (usually placed in caves).") + private KList crystals = new KList<>(); + + public KList getAllPlacements() { + KList all = new KList<>(); + if (trees != null) { + all.addAll(trees); + } + if (ruins != null) { + all.addAll(ruins); + } + if (formations != null) { + all.addAll(formations); + } + if (coral != null) { + all.addAll(coral); + } + if (fungi != null) { + all.addAll(fungi); + } + if (crystals != null) { + all.addAll(crystals); + } + return all; + } + + public boolean isEmpty() { + return getAllPlacements().isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java new file mode 100644 index 000000000..b877a2624 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java @@ -0,0 +1,48 @@ +/* + * 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.procedural; + +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +/** + * A procedurally generated, placeable thing in a biome or region (trees, ruins, + * formations, coral, fungi, crystals). Implementations bake a deterministic pool + * of in-memory IrisObject variants and expose the placement controls the engine + * needs to scatter them, exactly like an object placement but generated from + * scratch instead of loaded from an iob file. + */ +public interface IrisProceduralPlacement { + String getName(); + + double getChance(); + + int getDensity(); + + boolean isPlausible(); + + IrisObjectPlacement asPlacement(); + + IrisObject getVariantObject(IrisData data, RNG rng); + + KList getVariantObjects(IrisData data); +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java new file mode 100644 index 000000000..b0ee7a1c5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java @@ -0,0 +1,64 @@ +/* + * 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.procedural.coral; + +import java.util.HashMap; +import java.util.Map; + +public final class CoralCanvas { + public enum Role { + STRUCTURE, + TIP + } + + private static final long BIAS = 1L << 20; + private static final long MASK = (1L << 21) - 1L; + + private final Map cells = new HashMap<>(); + + public void set(int x, int y, int z, Role role) { + if (y < 0) { + return; + } + long key = encode(x, y, z); + Role existing = cells.get(key); + if (existing == Role.TIP && role == Role.STRUCTURE) { + return; + } + cells.put(key, role); + } + + public Map getCells() { + return cells; + } + + public static long encode(int x, int y, int z) { + long ex = (x + BIAS) & MASK; + long ey = (y + BIAS) & MASK; + long ez = (z + BIAS) & MASK; + return (ex << 42) | (ey << 21) | ez; + } + + public static int[] decode(long key) { + int ez = (int) ((key & MASK) - BIAS); + int ey = (int) (((key >> 21) & MASK) - BIAS); + int ex = (int) (((key >> 42) & MASK) - BIAS); + return new int[]{ex, ey, ez}; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java new file mode 100644 index 000000000..17c4a4980 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java @@ -0,0 +1,263 @@ +/* + * 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.procedural.coral; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.procedural.coral.IrisCoral; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.HashMap; +import java.util.Map; + +public final class CoralGenerator { + private static final double GOLDEN_ANGLE = 137.50776405003785; + + private CoralGenerator() { + } + + public static IrisObject generate(IrisCoral coral, int variantIndex, RNG rng, IrisData data) { + int lo = Math.min(coral.getHeightMin(), coral.getHeightMax()); + int hi = Math.max(coral.getHeightMin(), coral.getHeightMax()); + int height = Math.max(2, rng.i(lo, hi + 1)); + long shapeSeed = rng.getSeed() + variantIndex * 31L; + + CoralCanvas canvas = new CoralCanvas(); + switch (coral.getForm()) { + case BRANCHING -> buildBranching(canvas, coral, height, shapeSeed, rng); + case FAN -> buildFan(canvas, coral, height, shapeSeed); + case BRAIN -> buildBrain(canvas, coral, height, shapeSeed); + case PILLAR -> buildPillar(canvas, coral, height, shapeSeed); + case TENDRIL -> buildTendril(canvas, coral, height, shapeSeed, rng); + } + + Map resolved = resolve(canvas, coral, data); + return IrisProceduralBlocks.assemble(resolved); + } + + private static void buildBranching(CoralCanvas canvas, IrisCoral coral, int height, long seed, RNG rng) { + int stalkTop = Math.max(1, (int) Math.round(height * 0.5)); + for (int y = 0; y < stalkTop; y++) { + placeWavy(canvas, coral, 0, y, 0, y, seed, CoralCanvas.Role.STRUCTURE); + } + + int count = Math.max(1, coral.getBranchCount()); + for (int b = 0; b < count; b++) { + double az = branchAzimuth(coral, b, count, rng); + int startY = stalkTop - 1 + (int) Math.round((b % 2) * 1.0); + double[] tip = rasterizeArm(canvas, coral, 0, startY, 0, az, + coral.getBranchElevation(), coral.getBranchLength(), seed + b * 131L); + + placeTipCluster(canvas, coral, (int) Math.round(tip[0]), (int) Math.round(tip[1]), (int) Math.round(tip[2]), + coral.getTipClusterRadius(), seed + b * 977L); + + if (coral.isSubBranches()) { + int subCount = Math.max(1, coral.getSubBranchCount()); + for (int s = 0; s < subCount; s++) { + double subAz = az + (s - (subCount - 1) / 2.0) * 35.0; + double subLen = coral.getBranchLength() * coral.getSubBranchScale(); + double[] subTip = rasterizeArm(canvas, coral, + (int) Math.round(tip[0]), (int) Math.round(tip[1]), (int) Math.round(tip[2]), + subAz, coral.getBranchElevation() + 10.0, subLen, seed + b * 131L + s * 17L + 5000L); + placeTipCluster(canvas, coral, (int) Math.round(subTip[0]), (int) Math.round(subTip[1]), (int) Math.round(subTip[2]), + Math.max(0, coral.getTipClusterRadius() - 1), seed + b * 977L + s * 53L); + } + } + } + } + + private static void buildFan(CoralCanvas canvas, IrisCoral coral, int height, long seed) { + int half = Math.max(1, coral.getFanWidth()); + for (int y = 0; y < height; y++) { + double t = y / (double) Math.max(1, height - 1); + double profile = Math.sin(Math.PI * t); + int w = (int) Math.round(half * profile); + for (int dx = -w; dx <= w; dx++) { + canvas.set(dx, y, 0, CoralCanvas.Role.STRUCTURE); + } + } + for (int dx = -half; dx <= half; dx++) { + placeTip(canvas, coral, dx, height - 1, 0, seed + dx); + } + } + + private static void buildBrain(CoralCanvas canvas, IrisCoral coral, int height, long seed) { + int r = Math.max(1, coral.getBrainRadius()); + int ry = Math.max(1, Math.min(r, (int) Math.round(height * 0.6))); + double rough = coral.getBrainRoughness(); + for (int dx = -r; dx <= r; dx++) { + for (int dz = -r; dz <= r; dz++) { + for (int dy = 0; dy <= ry * 2; dy++) { + double nx = dx / (double) r; + double ny = (dy - ry) / (double) ry; + double nz = dz / (double) r; + double d = nx * nx + ny * ny + nz * nz; + double wobble = (TreeFunctions.valueNoise3D(dx, dy, dz, seed) - 0.5) * 2.0 * rough; + if (d <= 1.0 + wobble) { + canvas.set(dx, dy, dz, CoralCanvas.Role.STRUCTURE); + } + } + } + } + } + + private static void buildPillar(CoralCanvas canvas, IrisCoral coral, int height, long seed) { + int r = Math.max(1, coral.getPillarRadius()); + for (int y = 0; y < height; y++) { + for (int dx = -r; dx <= r; dx++) { + for (int dz = -r; dz <= r; dz++) { + if (dx * dx + dz * dz <= r * r) { + canvas.set(dx, y, dz, CoralCanvas.Role.STRUCTURE); + } + } + } + } + placeTipCluster(canvas, coral, 0, height - 1, 0, coral.getTipClusterRadius(), seed); + } + + private static void buildTendril(CoralCanvas canvas, IrisCoral coral, int height, long seed, RNG rng) { + int count = Math.max(1, coral.getTendrilCount()); + double radius = Math.max(0.0, coral.getSpread()); + for (int c = 0; c < count; c++) { + double az = Math.toRadians(c * (360.0 / count)); + double bx = Math.cos(az) * radius * 0.5; + double bz = Math.sin(az) * radius * 0.5; + int tx = (int) Math.round(bx); + int tz = (int) Math.round(bz); + int top = 0; + for (int y = 0; y < height; y++) { + placeWavy(canvas, coral, tx, y, tz, y * (c + 1), seed + c * 311L, CoralCanvas.Role.STRUCTURE); + top = y; + } + placeTip(canvas, coral, tx, top, tz, seed + c * 311L); + } + } + + private static double[] rasterizeArm(CoralCanvas canvas, IrisCoral coral, int ox, int oy, int oz, + double azimuthDeg, double elevationDeg, double length, long seed) { + double azRad = Math.toRadians(azimuthDeg); + double elRad = Math.toRadians(elevationDeg); + double dx = length * Math.cos(elRad) * Math.sin(azRad); + double dy = length * Math.sin(elRad); + double dz = length * Math.cos(elRad) * Math.cos(azRad); + int steps = Math.max(1, (int) Math.round(Math.max(Math.abs(dy), Math.max(Math.abs(dx), Math.abs(dz))))); + + double[] tip = new double[]{ox, oy, oz}; + for (int i = 0; i <= steps; i++) { + double t = i / (double) steps; + double sway = swayOffset(coral, t * length, seed); + int x = (int) Math.round(ox + dx * t + sway); + int y = (int) Math.round(oy + dy * t); + int z = (int) Math.round(oz + dz * t - sway); + canvas.set(x, y, z, CoralCanvas.Role.STRUCTURE); + tip = new double[]{x, y, z}; + } + return tip; + } + + private static void placeWavy(CoralCanvas canvas, IrisCoral coral, int x, int y, int z, double phase, long seed, CoralCanvas.Role role) { + double sway = swayOffset(coral, phase, seed); + int sx = (int) Math.round(sway); + int sz = (int) Math.round(swayOffset(coral, phase + 53.0, seed + 7L)); + canvas.set(x + sx, y, z + sz, role); + } + + private static double swayOffset(IrisCoral coral, double phase, long seed) { + double amount = Math.max(0.0, Math.min(1.0, coral.getSway())); + if (amount <= 0.0) { + return 0.0; + } + double n = TreeFunctions.valueNoise1D(phase * 0.35, seed) - 0.5; + return n * 2.0 * amount * (1.0 + coral.getSpread() * 0.25); + } + + private static void placeTipCluster(CoralCanvas canvas, IrisCoral coral, int cx, int cy, int cz, int radius, long seed) { + if (radius <= 0) { + placeTip(canvas, coral, cx, cy, cz, seed); + return; + } + for (int dx = -radius; dx <= radius; dx++) { + for (int dy = -radius; dy <= radius; dy++) { + for (int dz = -radius; dz <= radius; dz++) { + if (dx * dx + dy * dy + dz * dz <= radius * radius) { + canvas.set(cx + dx, cy + dy, cz + dz, CoralCanvas.Role.STRUCTURE); + } + } + } + } + placeTip(canvas, coral, cx, cy + radius + 1, cz, seed); + } + + private static void placeTip(CoralCanvas canvas, IrisCoral coral, int x, int y, int z, long seed) { + if (!hasTip(coral)) { + return; + } + if (TreeFunctions.valueNoise1D(x * 31.0 + y * 17.0 + z * 13.0, seed) <= coral.getTipChance()) { + canvas.set(x, y, z, CoralCanvas.Role.TIP); + } + } + + private static boolean hasTip(IrisCoral coral) { + return IrisProceduralBlocks.paletteSet(coral.getTipPalette()) + || (coral.getTipBlock() != null && !coral.getTipBlock().isEmpty()); + } + + private static double branchAzimuth(IrisCoral coral, int index, int count, RNG rng) { + return switch (coral.getBranchAzimuth()) { + case GOLDEN_ANGLE -> index * GOLDEN_ANGLE; + case EVEN -> index * (360.0 / count); + case RANDOM -> rng.d(0.0, 360.0); + }; + } + + private static Map resolve(CoralCanvas canvas, IrisCoral coral, IrisData data) { + Map out = new HashMap<>(); + RNG paletteRng = new RNG(coral.getSeed()); + for (Map.Entry entry : canvas.getCells().entrySet()) { + int[] xyz = CoralCanvas.decode(entry.getKey()); + int x = xyz[0]; + int y = xyz[1]; + int z = xyz[2]; + PlatformBlockState state; + if (entry.getValue() == CoralCanvas.Role.TIP) { + state = IrisProceduralBlocks.resolve(coral.getTipBlock(), coral.getTipPalette(), data, x, y, z, paletteRng); + if (state == null) { + state = IrisProceduralBlocks.resolve(coral.getBlock(), coral.getBlockPalette(), data, x, y, z, paletteRng); + } + } else { + state = IrisProceduralBlocks.resolve(coral.getBlock(), coral.getBlockPalette(), data, x, y, z, paletteRng); + } + if (state == null) { + continue; + } + if (coral.isWaterlogged() && IrisProceduralBlocks.hasProperty(state, "waterlogged")) { + try { + state = state.withProperty("waterlogged", "true"); + } catch (IllegalArgumentException ignored) { + } + } + out.put(new Vector3i(x, y, z), state); + } + return out; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java new file mode 100644 index 000000000..8a1ab5fb2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java @@ -0,0 +1,249 @@ +/* + * 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.procedural.coral; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.placement.IrisObjectLimit; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisStiltSettings; +import art.arcane.iris.engine.object.placement.IrisVacuumSettings; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.procedural.coral.CoralGenerator; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("coral") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A single procedurally generated coral reef structure. Iris bakes a pool of deterministic variants from these settings and scatters them across the seafloor at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Mirrors the procedural tree system but tuned for underwater reefs: structural blocks are waterlogged so the coral stays alive, and placement defaults to anchoring on the terrain beneath the water surface.") +@Data +public class IrisCoral implements IrisProceduralPlacement { + private final transient AtomicCache> variantCache = new AtomicCache<>(); + + @Desc("A human readable name used in logs and as the variant load key.") + private String name = "coral"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per chunk for this coral to attempt placement. Use density for multiple per chunk.") + private double chance = 0.4; + + @MinNumber(1) + @Desc("If the chance check passes, attempt this many placements in the chunk.") + private int density = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("How many distinct variants to pre-bake for this coral. Higher means more variety at a small memory cost.") + private int variants = 6; + + @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") + private long seed = 1337; + + @Desc("The placement mode used to anchor the coral to the seafloor.") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + + @Desc("Rotate this coral's placement.") + private IrisObjectRotation rotation = new IrisObjectRotation(); + + @Desc("Limit the max or min height of placement.") + private IrisObjectLimit clamp = new IrisObjectLimit(); + + @Desc("Whether this coral may place on the terrain surface, under carvings, or both.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + + @Desc("If true (default for coral), the coral anchors on the terrain height beneath the water, so it grows up from the seafloor rather than floating at the water surface.") + private boolean underwater = true; + + @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the seafloor.") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + + @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") + private IrisStiltSettings stiltSettings; + + @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") + private IrisVacuumSettings vacuumSettings; + + @Desc("If true (default), every resolved coral block that is waterloggable is forced waterlogged so the coral does not die in water (coral fans, sea pickles and kelp also waterlog). Set false to place dead/dry coral.") + private boolean waterlogged = true; + + @Desc("The overall silhouette this coral grows into (branching, fan, brain, pillar, tendril). Each form runs a different generation routine.") + private IrisCoralForm form = IrisCoralForm.BRANCHING; + + @Required + @Desc("The structural coral block (the living wood of the reef), e.g. minecraft:tube_coral_block. Ignored when blockPalette is set.") + @RegistryListBlockType + private String block = "minecraft:tube_coral_block"; + + @Desc("A noise-driven palette for the structural coral block. When set this overrides the single block, letting the reef mix tube/brain/bubble/fire/horn coral_block tones across its body.") + private IrisMaterialPalette blockPalette = null; + + @Desc("Optional tip block placed at branch tips and at the very top of the structure, e.g. coral fans or minecraft:sea_pickle. Ignored when tipPalette is set. Null disables tips.") + @RegistryListBlockType + private String tipBlock = null; + + @Desc("A noise-driven palette for the tip block. When set this overrides the single tipBlock, letting tips mix fan / pickle decorations.") + private IrisMaterialPalette tipPalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per eligible tip position to place a tip block (coral fan / sea pickle).") + private double tipChance = 0.6; + + @MinNumber(1) + @Desc("Minimum overall height of the coral in blocks.") + private int heightMin = 4; + + @MinNumber(1) + @Desc("Maximum overall height of the coral in blocks.") + private int heightMax = 8; + + @MinNumber(0) + @Desc("Horizontal spread of the structure in blocks. For BRANCHING this is how far arms reach out, for BRAIN/PILLAR/FAN it widens the base footprint.") + private double spread = 3; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Lateral noise wobble (0-1) applied to branches and tendrils so they are not ruler-straight. 0 is perfectly straight, 1 is heavily wandering.") + private double sway = 0.5; + + @MinNumber(1) + @MaxNumber(12) + @Desc("BRANCHING only: how many arms sprout from the central stalk.") + private int branchCount = 4; + + @MinNumber(1) + @Desc("BRANCHING only: the length of each arm in blocks before reaching its tip.") + private double branchLength = 3; + + @MinNumber(0) + @MaxNumber(90) + @Desc("BRANCHING only: the upward elevation in degrees of each arm from horizontal. 90 is straight up, 0 is flat out.") + private double branchElevation = 55; + + @Desc("BRANCHING only: how the arms are distributed around the stalk by azimuth.") + private IrisCoralBranchAzimuth branchAzimuth = IrisCoralBranchAzimuth.GOLDEN_ANGLE; + + @Desc("BRANCHING only: if true, each arm splits once into a small fan of sub-arms for a bushier reef.") + private boolean subBranches = true; + + @MinNumber(1) + @MaxNumber(5) + @Desc("BRANCHING only: how many sub-arms each arm splits into when subBranches is true.") + private int subBranchCount = 2; + + @MinNumber(0) + @MaxNumber(1) + @Desc("BRANCHING only: the length of each sub-arm as a fraction of its parent arm.") + private double subBranchScale = 0.5; + + @MinNumber(0) + @MaxNumber(4) + @Desc("BRANCHING and PILLAR only: the radius of the small coral tip cluster grown at each tip.") + private int tipClusterRadius = 1; + + @MinNumber(1) + @MaxNumber(8) + @Desc("BRAIN only: the horizontal radius of the brain-coral blob in blocks.") + private int brainRadius = 3; + + @MinNumber(0) + @MaxNumber(1) + @Desc("BRAIN only: how strongly 3D value noise perturbs the ellipsoid surface, for a wrinkled organic blob. 0 is a smooth dome.") + private double brainRoughness = 0.35; + + @MinNumber(1) + @MaxNumber(12) + @Desc("PILLAR only: the radius of the stout vertical column in blocks.") + private int pillarRadius = 1; + + @MinNumber(1) + @MaxNumber(8) + @Desc("FAN only: the half-width of the upright fan plane in blocks (the disc widens toward its mid-height).") + private int fanWidth = 3; + + @MinNumber(1) + @MaxNumber(12) + @Desc("TENDRIL only: how many thin wavy stalks rise from the base.") + private int tendrilCount = 4; + + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> { + KList baked = new KList<>(); + int count = Math.max(1, variants); + + for (int i = 0; i < count; i++) { + IrisObject object = CoralGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + name + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + }); + } + + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(mode); + placement.setRotation(rotation); + placement.setClamp(clamp); + placement.setCarvingSupport(carvingSupport); + placement.setUnderwater(underwater); + placement.setTranslate(translate); + placement.setStiltSettings(stiltSettings); + placement.setVacuumSettings(vacuumSettings); + placement.setChance(chance); + placement.setDensity(density); + return placement; + } + + public boolean isPlausible() { + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java new file mode 100644 index 000000000..657457102 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java @@ -0,0 +1,33 @@ +/* + * 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.procedural.coral; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How the arms of a BRANCHING coral are distributed around the central stalk by compass azimuth.") +public enum IrisCoralBranchAzimuth { + @Desc("Distribute arms by the golden angle (about 137.5 degrees per arm) for a natural phyllotactic spiral where no two arms overlap.") + GOLDEN_ANGLE, + + @Desc("Distribute arms in evenly spaced spokes, dividing 360 degrees equally between them like a radial whorl.") + EVEN, + + @Desc("Place each arm at a fully random azimuth using the deterministic per-variant RNG, for an irregular wild reef.") + RANDOM +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java new file mode 100644 index 000000000..2d4f00038 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java @@ -0,0 +1,39 @@ +/* + * 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.procedural.coral; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The overall silhouette a procedural coral grows into. Each form drives a completely different generation routine in the coral generator, from tree-like branching arms to rounded brain blobs and thin wavy tendrils.") +public enum IrisCoralForm { + @Desc("A tree-like coral built from a stout central stalk that sprouts several upward-leaning arms (distributed by golden angle or randomly), each optionally splitting once into sub-arms, with small coral tip clusters (fans / sea pickles) at the ends. The most structurally complex form and the closest analogue to a procedural tree.") + BRANCHING, + + @Desc("A thin, single-block-thick vertical fan plane that rises and widens with height like a sheet of fire or horn coral. Reads as a flat decorative blade rather than a volume.") + FAN, + + @Desc("A rounded, noise-perturbed ellipsoid blob of brain coral that bulges out of the seafloor like a boulder, with an irregular wrinkled surface driven by 3D value noise.") + BRAIN, + + @Desc("A stout, thick vertical column of coral block topped with a dense tip cluster. Wider and blunter than a tendril, reading as a solid coral pillar or stack.") + PILLAR, + + @Desc("Several very thin (one block wide) wavy stalks that rise upward and wander laterally using value noise, like a clump of swaying coral whips or kelp-thin growths.") + TENDRIL +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java new file mode 100644 index 000000000..18a2b80a6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java @@ -0,0 +1,49 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; + +public final class CrystalBaseBuilder { + private CrystalBaseBuilder() { + } + + public static void build(CrystalCanvas canvas, IrisCrystal crystal, long seed) { + double radius = crystal.getBaseRadius(); + if (radius <= 0.0) { + canvas.set(0, 0, 0, CrystalRole.BASE); + return; + } + + double noiseStrength = crystal.getBaseNoise(); + int reach = (int) Math.ceil(radius + 1.0); + for (int x = -reach; x <= reach; x++) { + for (int y = -reach; y <= reach; y++) { + for (int z = -reach; z <= reach; z++) { + double distance = Math.sqrt((double) x * x + (double) y * y + (double) z * z); + double wobble = (TreeFunctions.valueNoise3D(x, y, z, seed) - 0.5) * 2.0 * noiseStrength * radius; + if (distance <= radius + wobble) { + canvas.set(x, y, z, CrystalRole.BASE); + } + } + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java new file mode 100644 index 000000000..2a7946f43 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java @@ -0,0 +1,52 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.util.common.math.Vector3i; + +import java.util.HashMap; +import java.util.Map; + +public final class CrystalCanvas { + private final Map cells = new HashMap<>(); + + public void set(int x, int y, int z, CrystalRole role) { + Vector3i key = new Vector3i(x, y, z); + CrystalRole existing = cells.get(key); + if (existing == null || rank(role) > rank(existing)) { + cells.put(key, role); + } + } + + public boolean has(int x, int y, int z) { + return cells.containsKey(new Vector3i(x, y, z)); + } + + public Map getCells() { + return cells; + } + + private static int rank(CrystalRole role) { + return switch (role) { + case BASE -> 0; + case SHARD -> 1; + case TIP -> 2; + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java new file mode 100644 index 000000000..e6ed58df2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java @@ -0,0 +1,111 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.HashMap; +import java.util.Map; + +public final class CrystalGenerator { + private CrystalGenerator() { + } + + public static IrisObject generate(IrisCrystal crystal, int variantIndex, RNG rng, IrisData data) { + CrystalCanvas canvas = new CrystalCanvas(); + long structureSeed = rng.getSeed(); + + CrystalBaseBuilder.build(canvas, crystal, structureSeed + 977L); + CrystalShardBuilder.build(canvas, crystal, rng); + + Map resolved = new HashMap<>(); + RNG paletteRng = new RNG(crystal.getSeed()); + RNG tipRng = new RNG(crystal.getSeed() + (variantIndex * 31337L) + 4099L); + + for (Map.Entry entry : canvas.getCells().entrySet()) { + Vector3i position = entry.getKey(); + int x = position.getBlockX(); + int y = position.getBlockY(); + int z = position.getBlockZ(); + PlatformBlockState blockData = resolveRole(crystal, entry.getValue(), data, x, y, z, paletteRng, tipRng); + if (blockData == null) { + continue; + } + resolved.put(position, blockData); + } + + return IrisProceduralBlocks.assemble(resolved); + } + + private static PlatformBlockState resolveRole(IrisCrystal crystal, CrystalRole role, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { + return switch (role) { + case BASE -> resolveBase(crystal, data, x, y, z, paletteRng); + case SHARD -> resolveShard(crystal, data, x, y, z, paletteRng); + case TIP -> resolveTip(crystal, data, x, y, z, paletteRng, tipRng); + }; + } + + private static PlatformBlockState resolveBase(IrisCrystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { + boolean hasBase = IrisProceduralBlocks.paletteSet(crystal.getBasePalette()) + || (crystal.getBaseBlock() != null && !crystal.getBaseBlock().isEmpty()); + if (hasBase) { + PlatformBlockState base = IrisProceduralBlocks.resolve(crystal.getBaseBlock(), crystal.getBasePalette(), data, x, y, z, paletteRng); + if (base != null) { + return base; + } + } + return resolveShard(crystal, data, x, y, z, paletteRng); + } + + private static PlatformBlockState resolveShard(IrisCrystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { + return IrisProceduralBlocks.resolve(crystal.getBlock(), crystal.getBlockPalette(), data, x, y, z, paletteRng); + } + + private static PlatformBlockState resolveTip(IrisCrystal crystal, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { + boolean hasTip = IrisProceduralBlocks.paletteSet(crystal.getTipPalette()) + || (crystal.getTipBlock() != null && !crystal.getTipBlock().isEmpty()); + + if (hasTip) { + if (tipRng.chance(crystal.getTipChance())) { + PlatformBlockState tip = IrisProceduralBlocks.resolve(crystal.getTipBlock(), crystal.getTipPalette(), data, x, y, z, paletteRng); + if (tip != null) { + return tip; + } + } + return resolveShard(crystal, data, x, y, z, paletteRng); + } + + if (crystal.isGlow() && crystal.getGlowBlock() != null && !crystal.getGlowBlock().isEmpty()) { + if (tipRng.chance(crystal.getTipChance())) { + PlatformBlockState glow = IrisProceduralBlocks.resolve(crystal.getGlowBlock(), null, data, x, y, z, paletteRng); + if (glow != null) { + return glow; + } + } + } + + return resolveShard(crystal, data, x, y, z, paletteRng); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java new file mode 100644 index 000000000..aa63d4619 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java @@ -0,0 +1,84 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.engine.object.procedural.crystal.IrisCrystalSurface; + +public final class CrystalGeometry { + private CrystalGeometry() { + } + + public static double[] surfaceNormal(IrisCrystalSurface surface) { + return switch (surface) { + case FLOOR -> new double[]{0.0, 1.0, 0.0}; + case CEILING -> new double[]{0.0, -1.0, 0.0}; + case WALL -> { + double len = Math.sqrt(1.0 + 0.5 * 0.5); + yield new double[]{1.0 / len, 0.5 / len, 0.0}; + } + }; + } + + public static double[] orthonormalBasisU(double[] normal) { + double[] reference = Math.abs(normal[1]) > 0.99 ? new double[]{1.0, 0.0, 0.0} : new double[]{0.0, 1.0, 0.0}; + double[] u = cross(reference, normal); + normalize(u); + return u; + } + + public static double[] orthonormalBasisV(double[] normal, double[] u) { + double[] v = cross(normal, u); + normalize(v); + return v; + } + + public static double[] coneDirection(double[] normal, double[] u, double[] v, double coneAngleRadians, double azimuthRadians) { + double sin = Math.sin(coneAngleRadians); + double cos = Math.cos(coneAngleRadians); + double ca = Math.cos(azimuthRadians); + double sa = Math.sin(azimuthRadians); + double[] dir = new double[3]; + for (int i = 0; i < 3; i++) { + dir[i] = cos * normal[i] + sin * (ca * u[i] + sa * v[i]); + } + normalize(dir); + return dir; + } + + public static double[] cross(double[] a, double[] b) { + return new double[]{ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0] + }; + } + + public static void normalize(double[] vec) { + double len = Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); + if (len < 1e-9) { + vec[0] = 0.0; + vec[1] = 1.0; + vec[2] = 0.0; + return; + } + vec[0] /= len; + vec[1] /= len; + vec[2] /= len; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java new file mode 100644 index 000000000..14413beac --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java @@ -0,0 +1,25 @@ +/* + * 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.procedural.crystal; + +public enum CrystalRole { + BASE, + SHARD, + TIP +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java new file mode 100644 index 000000000..c65872317 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java @@ -0,0 +1,125 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; +import art.arcane.iris.engine.object.procedural.crystal.IrisCrystalDistribution; +import art.arcane.volmlib.util.math.RNG; + +public final class CrystalShardBuilder { + private static final double GOLDEN_ANGLE = 137.50776405003785; + + private CrystalShardBuilder() { + } + + public static void build(CrystalCanvas canvas, IrisCrystal crystal, RNG rng) { + double[] normal = CrystalGeometry.surfaceNormal(crystal.getGrowthSurface()); + double[] u = CrystalGeometry.orthonormalBasisU(normal); + double[] v = CrystalGeometry.orthonormalBasisV(normal, u); + + int countLo = Math.min(crystal.getShardCountMin(), crystal.getShardCountMax()); + int countHi = Math.max(crystal.getShardCountMin(), crystal.getShardCountMax()); + int shardCount = Math.max(1, rng.i(countLo, countHi + 1)); + + int lengthLo = Math.min(crystal.getShardLengthMin(), crystal.getShardLengthMax()); + int lengthHi = Math.max(crystal.getShardLengthMin(), crystal.getShardLengthMax()); + + double spreadRadians = Math.toRadians(Math.max(0.0, Math.min(90.0, crystal.getSpreadAngle()))); + double jitterAmount = Math.max(0.0, Math.min(1.0, crystal.getJitter())); + double emitRadius = Math.max(0.0, crystal.getBaseRadius() * 0.6); + + for (int i = 0; i < shardCount; i++) { + double azimuth = azimuth(crystal.getDistribution(), i, rng); + azimuth += rng.d(-Math.PI, Math.PI) * jitterAmount * 0.5; + + double cone = spreadRadians * fanFraction(shardCount, i, rng); + cone += rng.d(-spreadRadians, spreadRadians) * jitterAmount * 0.5; + cone = Math.max(0.0, Math.min(Math.PI / 2.0, cone)); + + double[] direction = CrystalGeometry.coneDirection(normal, u, v, cone, azimuth); + + double ox = normal[0] * emitRadius + u[0] * Math.cos(azimuth) * emitRadius + v[0] * Math.sin(azimuth) * emitRadius; + double oy = normal[1] * emitRadius + u[1] * Math.cos(azimuth) * emitRadius + v[1] * Math.sin(azimuth) * emitRadius; + double oz = normal[2] * emitRadius + u[2] * Math.cos(azimuth) * emitRadius + v[2] * Math.sin(azimuth) * emitRadius; + + int length = Math.max(1, rng.i(lengthLo, lengthHi + 1)); + rasterizeShard(canvas, crystal, ox, oy, oz, direction, length); + } + } + + private static void rasterizeShard(CrystalCanvas canvas, IrisCrystal crystal, double ox, double oy, double oz, double[] direction, int length) { + double baseRadius = Math.max(0.5, crystal.getShardBaseRadius()); + double taper = Math.max(0.0, Math.min(1.0, crystal.getShardTaper())); + + int samples = Math.max(1, length * 3); + + for (int s = 0; s <= samples; s++) { + double t = s / (double) samples; + double cx = ox + direction[0] * length * t; + double cy = oy + direction[1] * length * t; + double cz = oz + direction[2] * length * t; + + double radius = baseRadius * (1.0 - taper * t); + if (t >= 1.0) { + radius = 0.0; + } + radius = Math.max(0.0, radius); + + int reach = (int) Math.floor(radius); + int centerX = (int) Math.round(cx); + int centerY = (int) Math.round(cy); + int centerZ = (int) Math.round(cz); + + if (reach <= 0) { + canvas.set(centerX, centerY, centerZ, CrystalRole.SHARD); + } else { + for (int dx = -reach; dx <= reach; dx++) { + for (int dy = -reach; dy <= reach; dy++) { + for (int dz = -reach; dz <= reach; dz++) { + double dist = Math.sqrt((double) dx * dx + (double) dy * dy + (double) dz * dz); + if (dist <= radius) { + canvas.set(centerX + dx, centerY + dy, centerZ + dz, CrystalRole.SHARD); + } + } + } + } + } + } + + int tipX = (int) Math.round(ox + direction[0] * length); + int tipY = (int) Math.round(oy + direction[1] * length); + int tipZ = (int) Math.round(oz + direction[2] * length); + canvas.set(tipX, tipY, tipZ, CrystalRole.TIP); + } + + private static double azimuth(IrisCrystalDistribution distribution, int index, RNG rng) { + if (distribution == IrisCrystalDistribution.GOLDEN_ANGLE) { + return Math.toRadians(index * GOLDEN_ANGLE); + } + return rng.d(0.0, Math.PI * 2.0); + } + + private static double fanFraction(int count, int index, RNG rng) { + if (count <= 1) { + return rng.d(0.0, 1.0); + } + double base = index / (double) (count - 1); + return Math.max(0.0, Math.min(1.0, base * 0.7 + rng.d(0.0, 0.3))); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java new file mode 100644 index 000000000..971c2349d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java @@ -0,0 +1,230 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.placement.IrisObjectLimit; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisStiltSettings; +import art.arcane.iris.engine.object.placement.IrisVacuumSettings; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.procedural.crystal.CrystalGenerator; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("crystal") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A single procedurally generated crystal cluster: a budding base blob with faceted, tapered shards radiating from it (geode / amethyst-style). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Built for caves.") +@Data +public class IrisCrystal implements IrisProceduralPlacement { + private final transient AtomicCache> variantCache = new AtomicCache<>(); + + @Desc("A human readable name used in logs and as the variant load key.") + private String name = "crystal"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per chunk for this crystal cluster to attempt placement. Use density for multiple per chunk.") + private double chance = 0.2; + + @MinNumber(1) + @Desc("If the chance check passes, attempt this many placements in the chunk.") + private int density = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("How many distinct variants to pre-bake for this crystal cluster. Higher means more variety at a small memory cost.") + private int variants = 6; + + @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") + private long seed = 1337; + + @Desc("The placement mode used to anchor the crystal cluster to the terrain.") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + + @Desc("Rotate this crystal cluster's placement.") + private IrisObjectRotation rotation = new IrisObjectRotation(); + + @Desc("Limit the max or min height of placement.") + private IrisObjectLimit clamp = new IrisObjectLimit(); + + @Desc("Whether this crystal cluster may place on the terrain surface, under carvings, or both. Crystals are meant for caves, so this defaults to CARVING_ONLY.") + private CarvingMode carvingSupport = CarvingMode.CARVING_ONLY; + + @Desc("If true, the crystal cluster anchors on the terrain height ignoring the water surface.") + private boolean underwater = false; + + @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + + @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") + private IrisStiltSettings stiltSettings; + + @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") + private IrisVacuumSettings vacuumSettings; + + @Desc("The surface this crystal grows from (FLOOR shards up, CEILING shards down, WALL shards outward). This orients the baked geometry only.") + private IrisCrystalSurface growthSurface = IrisCrystalSurface.FLOOR; + + @Required + @Desc("The primary crystal shard block, e.g. minecraft:amethyst_block. Ignored when blockPalette is set.") + @RegistryListBlockType + private String block = "minecraft:amethyst_block"; + + @Desc("A noise-driven palette for the crystal shards (a prismatic mix, e.g. amethyst_block, calcite, tinted_glass). When set this overrides the single block, letting the shards mix blocks by noise. Palette wins.") + private IrisMaterialPalette blockPalette = null; + + @Desc("Optional block placed at the very tip of each shard for a different colored or sparkling point (e.g. minecraft:amethyst_cluster or glowstone). Ignored when tipPalette is set. If unset and glow is true, a light-emitting block is sprinkled among the tips instead.") + @RegistryListBlockType + private String tipBlock = null; + + @Desc("A noise-driven palette for the shard tips. When set this overrides the single tipBlock. Palette wins.") + private IrisMaterialPalette tipPalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per shard that its very tip is replaced by the tip block (or glow block).") + private double tipChance = 0.6; + + @Desc("If true and no tipBlock/tipPalette is set, sprinkle a light-emitting block (the glowBlock) among the shard tips for a sparkling geode.") + private boolean glow = false; + + @Desc("The light-emitting block sprinkled among the tips when glow is true and no tip block is configured.") + @RegistryListBlockType + private String glowBlock = "minecraft:glowstone"; + + @Desc("Optional block for the budding base blob the shards grow from, e.g. minecraft:budding_amethyst or calcite. Ignored when basePalette is set. If unset, the base is built from the primary shard block.") + @RegistryListBlockType + private String baseBlock = "minecraft:budding_amethyst"; + + @Desc("A noise-driven palette for the budding base blob. When set this overrides the single baseBlock. Palette wins.") + private IrisMaterialPalette basePalette = null; + + @MinNumber(0) + @Desc("Radius in blocks of the budding base blob the shards radiate from. 0 places no base blob (shards spring from a single point).") + private double baseRadius = 1.6; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How strongly value noise perturbs the surface of the base blob, for a lumpy organic budding base rather than a clean sphere.") + private double baseNoise = 0.35; + + @MinNumber(1) + @Desc("Minimum number of shards radiating from the base.") + private int shardCountMin = 5; + + @MinNumber(1) + @Desc("Maximum number of shards radiating from the base.") + private int shardCountMax = 11; + + @MinNumber(1) + @Desc("Minimum length in blocks of a shard, measured from the base out to its pointed tip.") + private int shardLengthMin = 3; + + @MinNumber(1) + @Desc("Maximum length in blocks of a shard, measured from the base out to its pointed tip.") + private int shardLengthMax = 8; + + @MinNumber(0.5) + @Desc("Starting radius in blocks of a shard at its thick base end. The shard tapers from this down to a single block at the tip.") + private double shardBaseRadius = 1.4; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How aggressively each shard narrows from base to tip. 0 keeps a near-constant column; 1 tapers fully to a sharp point at the very tip. Each shard always ends in a single pointed block.") + private double shardTaper = 0.85; + + @MinNumber(0) + @MaxNumber(90) + @Desc("The half-angle in degrees of the cone the shards fan within around the surface normal. 0 makes all shards parallel to the normal; larger values splay them outward into a starburst.") + private double spreadAngle = 45; + + @Desc("How the shard azimuths are distributed around the normal (RANDOM for a chaotic clump, GOLDEN_ANGLE for an evenly spaced rosette).") + private IrisCrystalDistribution distribution = IrisCrystalDistribution.GOLDEN_ANGLE; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Per-shard angular randomness (0-1) added on top of the chosen distribution so the cluster never looks mechanically regular. 0 is perfectly distributed; 1 is heavily jittered.") + private double jitter = 0.25; + + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> { + KList baked = new KList<>(); + int count = Math.max(1, variants); + + for (int i = 0; i < count; i++) { + IrisObject object = CrystalGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + name + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + }); + } + + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(mode); + placement.setRotation(rotation); + placement.setClamp(clamp); + placement.setCarvingSupport(carvingSupport); + placement.setUnderwater(underwater); + placement.setTranslate(translate); + placement.setStiltSettings(stiltSettings); + placement.setVacuumSettings(vacuumSettings); + placement.setChance(chance); + placement.setDensity(density); + return placement; + } + + public boolean isPlausible() { + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java new file mode 100644 index 000000000..52eadb53e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java @@ -0,0 +1,30 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How the shards of a crystal cluster are angularly distributed around the surface normal.") +public enum IrisCrystalDistribution { + @Desc("Each shard gets a uniformly random azimuth around the normal. Produces a chaotic, naturally clumped cluster.") + RANDOM, + + @Desc("Each shard's azimuth advances by the golden angle (~137.5 degrees) from the previous one. Produces an evenly spaced sunflower-like fan with no two shards overlapping, ideal for a geode rosette.") + GOLDEN_ANGLE +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java new file mode 100644 index 000000000..ddabd7879 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java @@ -0,0 +1,33 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The surface a crystal cluster grows from. This only orients the baked geometry (which way the shards point); placement of the object into a cave is handled by the placement system, not here.") +public enum IrisCrystalSurface { + @Desc("Grows from a cave floor. The budding base sits at the bottom and the shards point upward, fanning within the spread cone around the up axis. Built with positive py so the cluster grows up from the base layer.") + FLOOR, + + @Desc("Grows from a cave ceiling. The budding base sits at the top and the shards point downward like stalactites, fanning within the spread cone around the down axis. Built with negative py so the cluster grows down from the ceiling.") + CEILING, + + @Desc("Grows from a cave wall. The budding base hugs the wall and the shards point outward and slightly upward, fanning within the spread cone around a tilted normal so the cluster reads as a wall sconce of shards.") + WALL +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java new file mode 100644 index 000000000..5c97110f3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java @@ -0,0 +1,66 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.procedural.formation.IrisFormation; +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +public final class FormationBlockResolver { + private FormationBlockResolver() { + } + + public static PlatformBlockState resolve(IrisFormation f, IrisData data, FormationCanvas.Role role, Vector3i raw) { + int x = raw.getBlockX(); + int y = raw.getBlockY(); + int z = raw.getBlockZ(); + RNG paletteRng = new RNG(f.getSeed()); + + if (role == FormationCanvas.Role.CAP && capDefined(f)) { + PlatformBlockState cap = IrisProceduralBlocks.resolve(f.getCapBlock(), f.getCapPalette(), data, x, y, z, paletteRng); + if (cap != null) { + return cap; + } + } + + if (strataDefined(f)) { + IrisMaterialPalette strata = f.getStrataPalette(); + int thickness = Math.max(1, f.getStrataThickness()); + int band = Math.floorDiv(y, thickness); + PlatformBlockState strataState = strata.get(new RNG(f.getSeed() + (band * 31L)), x, band, z, data); + if (strataState != null) { + return strataState; + } + } + + return IrisProceduralBlocks.resolve(f.getBlock(), f.getBlockPalette(), data, x, y, z, paletteRng); + } + + private static boolean capDefined(IrisFormation f) { + return IrisProceduralBlocks.paletteSet(f.getCapPalette()) || (f.getCapBlock() != null && !f.getCapBlock().isEmpty()); + } + + private static boolean strataDefined(IrisFormation f) { + return IrisProceduralBlocks.paletteSet(f.getStrataPalette()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java new file mode 100644 index 000000000..7bf533008 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java @@ -0,0 +1,61 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.util.common.math.Vector3i; + +import java.util.HashMap; +import java.util.Map; + +public final class FormationCanvas { + public enum Role { + BODY, + CAP + } + + private final Map cells = new HashMap<>(); + + public void setBody(int x, int y, int z) { + Vector3i key = new Vector3i(x, y, z); + if (cells.get(key) == Role.CAP) { + return; + } + cells.put(key, Role.BODY); + } + + public void setCap(int x, int y, int z) { + cells.put(new Vector3i(x, y, z), Role.CAP); + } + + public void remove(int x, int y, int z) { + cells.remove(new Vector3i(x, y, z)); + } + + public boolean has(int x, int y, int z) { + return cells.containsKey(new Vector3i(x, y, z)); + } + + public Map getCells() { + return cells; + } + + public boolean isEmpty() { + return cells.isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java new file mode 100644 index 000000000..bebb43360 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java @@ -0,0 +1,75 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.procedural.formation.IrisFormation; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.HashMap; +import java.util.Map; + +public final class FormationGenerator { + private FormationGenerator() { + } + + public static IrisObject generate(IrisFormation f, int variantIndex, RNG rng, IrisData data) { + int lo = Math.min(f.getHeightMin(), f.getHeightMax()); + int hi = Math.max(f.getHeightMin(), f.getHeightMax()); + int height = Math.max(3, rng.i(lo, hi + 1)); + + int wLo = Math.min(f.getBaseWidthMin(), f.getBaseWidthMax()); + int wHi = Math.max(f.getBaseWidthMin(), f.getBaseWidthMax()); + double baseRadius = Math.max(1, rng.i(wLo, wHi + 1)); + + FormationCanvas canvas = new FormationCanvas(); + + switch (f.getForm()) { + case SPIRE -> FormationShapeBuilder.spire(canvas, f, height, baseRadius, rng); + case HOODOO -> FormationShapeBuilder.hoodoo(canvas, f, height, baseRadius, rng); + case ARCH -> FormationShapeBuilder.arch(canvas, f, height, baseRadius, rng); + case SEA_STACK -> FormationShapeBuilder.seaStack(canvas, f, height, baseRadius, rng); + case BOULDER -> FormationShapeBuilder.boulder(canvas, f, height, baseRadius, rng); + case BASALT_COLUMN -> FormationShapeBuilder.basaltColumns(canvas, f, height, baseRadius, rng); + case ICEBERG -> FormationShapeBuilder.iceberg(canvas, f, height, baseRadius, rng); + case FISSURE -> FormationShapeBuilder.fissure(canvas, f, height, baseRadius, rng); + case SPIRAL -> FormationShapeBuilder.spiral(canvas, f, height, baseRadius, rng); + case OVERHANG -> FormationShapeBuilder.overhang(canvas, f, height, baseRadius, rng); + } + + if (canvas.isEmpty()) { + return null; + } + + Map resolved = new HashMap<>(); + for (Map.Entry entry : canvas.getCells().entrySet()) { + PlatformBlockState bd = FormationBlockResolver.resolve(f, data, entry.getValue(), entry.getKey()); + if (bd == null) { + continue; + } + resolved.put(entry.getKey(), bd); + } + + return IrisProceduralBlocks.assemble(resolved); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java new file mode 100644 index 000000000..d6edb576c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java @@ -0,0 +1,57 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.engine.object.procedural.formation.IrisFormation; + +public final class FormationProfiles { + private FormationProfiles() { + } + + public static double radiusAt(IrisFormation f, double baseRadius, double topRadius, double t) { + double clamped = Math.max(0.0, Math.min(1.0, t)); + return switch (f.getProfile()) { + case CONSTANT -> baseRadius; + case LINEAR -> baseRadius + (topRadius - baseRadius) * clamped; + case TAPER -> baseRadius + (topRadius - baseRadius) * smoothstep(clamped); + case PARABOLIC -> parabolic(f, baseRadius, topRadius, clamped); + case BULGE -> baseRadius + (Math.max(baseRadius, topRadius) - baseRadius) * bell(clamped) + (topRadius - baseRadius) * clamped * 0.25; + }; + } + + private static double parabolic(IrisFormation f, double baseRadius, double topRadius, double t) { + double waist = Math.max(0.0, Math.min(1.0, f.getProfileWaist())); + double floor = Math.max(0.0, Math.min(1.0, f.getProfileWaistFloor())); + double denom = Math.pow(Math.max(waist, 1.0 - waist), 2); + if (denom == 0) { + denom = 1; + } + double envelope = baseRadius + (topRadius - baseRadius) * t; + double pinch = floor + (1.0 - floor) * (Math.pow(t - waist, 2) / denom); + return Math.max(0.5, envelope * pinch); + } + + private static double smoothstep(double t) { + return 3.0 * t * t - 2.0 * t * t * t; + } + + private static double bell(double t) { + return Math.exp(-Math.pow(t - 0.5, 2) / (2.0 * 0.22 * 0.22)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java new file mode 100644 index 000000000..edae9a400 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java @@ -0,0 +1,429 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.engine.object.procedural.formation.IrisFormation; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.HashMap; +import java.util.Map; + +public final class FormationShapeBuilder { + private FormationShapeBuilder() { + } + + public static void spire(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + double topRadius = f.getTopWidth(); + column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, true); + double lean = Math.toRadians(f.getLean()); + double azimuth = Math.toRadians(f.getLeanAzimuth()); + int previousX = 0; + int previousZ = 0; + for (int y = 0; y < height; y++) { + double shear = Math.tan(lean) * y; + int centerX = (int) Math.round(Math.cos(azimuth) * shear); + int centerZ = (int) Math.round(Math.sin(azimuth) * shear); + boolean cap = y >= height - 2; + for (int x = Math.min(previousX, centerX); x <= Math.max(previousX, centerX); x++) { + setSpireCenter(canvas, x, y, previousZ, cap); + } + for (int z = Math.min(previousZ, centerZ); z <= Math.max(previousZ, centerZ); z++) { + setSpireCenter(canvas, centerX, y, z, cap); + } + previousX = centerX; + previousZ = centerZ; + } + } + + public static void seaStack(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + double topRadius = Math.max(1.0, baseRadius * 0.55); + if (f.getTopWidth() > 0) { + topRadius = f.getTopWidth(); + } + column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, true); + } + + public static void hoodoo(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + double topRadius = f.getTopWidth() > 0 ? f.getTopWidth() : Math.max(1.0, baseRadius * 0.7); + column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, false); + + int capRadius = f.getHoodooCapRadius(); + if (capRadius <= 0) { + return; + } + int capHeight = Math.max(1, f.getHoodooCapHeight()); + double lean = Math.toRadians(f.getLean()); + double azimuth = Math.toRadians(f.getLeanAzimuth()); + double shear = Math.tan(lean) * height; + double topOffX = Math.cos(azimuth) * shear; + double topOffZ = Math.sin(azimuth) * shear; + double wideRadius = topRadius + capRadius; + + for (int cy = 0; cy < capHeight; cy++) { + int y = height + cy; + double shrink = capHeight <= 1 ? 0 : (cy / (double) (capHeight - 1)) * 0.5; + double r = wideRadius * (1.0 - shrink); + disc(canvas, f, (int) Math.round(topOffX), y, (int) Math.round(topOffZ), r, true, rng); + } + } + + public static void boulder(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + double rx = baseRadius; + double ry = Math.max(2.0, height * 0.5); + double rz = baseRadius * (0.8 + rng.d(0.0, 0.3)); + double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); + long noiseSeed = f.getSeed() + 4201L; + + int maxR = (int) Math.ceil(Math.max(rx, Math.max(ry, rz))) + 2; + for (int x = -maxR; x <= maxR; x++) { + for (int y = 0; y <= (int) Math.ceil(ry * 2) + 1; y++) { + for (int z = -maxR; z <= maxR; z++) { + double nx = x / rx; + double ny = (y - ry) / ry; + double nz = z / rz; + double d = nx * nx + ny * ny + nz * nz; + double wobble = (TreeFunctions.valueNoise3D(x, y, z, noiseSeed) - 0.5) * roughness * 0.9; + if (d + wobble <= 1.0) { + canvas.setBody(x, y, z); + } + } + } + } + } + + public static void arch(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + double span = Math.max(2.0, f.getArchSpan()); + double tubeRadius = Math.max(0.75, f.getArchThickness() * 0.5); + double asymmetry = Math.max(0.0, Math.min(1.0, f.getArchAsymmetry())); + double leftFootX = -span * 0.5 - tubeRadius - rng.d(0.0, span * 0.16) * asymmetry; + double rightFootX = span * 0.5 + tubeRadius + rng.d(0.0, span * 0.16) * asymmetry; + double leftFootZ = rng.d(-tubeRadius * 0.45, tubeRadius * 0.45) * asymmetry; + double rightFootZ = rng.d(-tubeRadius * 0.45, tubeRadius * 0.45) * asymmetry; + double crownZ = rng.d(-span * 0.2, span * 0.2) * asymmetry; + double crownShiftX = rng.d(-span * 0.12, span * 0.12) * asymmetry; + double depthTwist = rng.d(-span * 0.1, span * 0.1) * asymmetry; + double crownPosition = 0.5 + rng.d(-0.12, 0.12) * asymmetry; + double leftSteepness = 0.58 + rng.d(-0.16, 0.16) * asymmetry; + double rightSteepness = 0.58 + rng.d(-0.16, 0.16) * asymmetry; + double radiusWave = rng.d(-0.22, 0.22) * asymmetry; + double radiusPhase = rng.d(0.0, Math.PI * 2.0); + double crownCenterY = Math.max(tubeRadius + 2.0, height - 1.0 - tubeRadius); + double footRadius = tubeRadius + Math.min(tubeRadius * 0.45, baseRadius * 0.18); + long noiseSeed = rng.nextLong(); + int steps = Math.max(24, (int) Math.ceil((rightFootX - leftFootX + height) * 4.0)); + + ball(canvas, f, (int) Math.round(leftFootX), (int) Math.round(footRadius), + (int) Math.round(leftFootZ), footRadius, false, noiseSeed, rng); + ball(canvas, f, (int) Math.round(rightFootX), (int) Math.round(footRadius), + (int) Math.round(rightFootZ), footRadius, false, noiseSeed, rng); + + for (int step = 0; step <= steps; step++) { + double t = step / (double) steps; + double normalizedRise; + double steepness; + if (t <= crownPosition) { + normalizedRise = Math.sin((t / crownPosition) * Math.PI * 0.5); + steepness = leftSteepness; + } else { + normalizedRise = Math.sin(((1.0 - t) / (1.0 - crownPosition)) * Math.PI * 0.5); + steepness = rightSteepness; + } + double rise = Math.pow(Math.max(0.0, normalizedRise), steepness); + double x = leftFootX + (rightFootX - leftFootX) * t + + Math.sin(Math.PI * t) * crownShiftX; + double inverse = 1.0 - t; + double z = inverse * inverse * leftFootZ + 2.0 * inverse * t * crownZ + t * t * rightFootZ + + Math.sin(Math.PI * 2.0 * t) * depthTwist; + double y = tubeRadius + (crownCenterY - tubeRadius) * rise; + double radius = tubeRadius * (1.0 + radiusWave * Math.sin(Math.PI * t) + * Math.sin(Math.PI * 2.0 * t + radiusPhase)); + radius = Math.max(tubeRadius * 0.68, Math.min(tubeRadius * 1.32, radius)); + ball(canvas, f, (int) Math.round(x), (int) Math.round(y), (int) Math.round(z), + radius, false, noiseSeed, rng); + } + if (asymmetry == 0.0) { + mirrorAcrossX(canvas); + } + } + + public static void basaltColumns(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + int count = Math.max(2, f.getBasaltColumns()); + int colRadius = Math.max(1, f.getBasaltColumnRadius()); + double variance = Math.max(0.0, Math.min(1.0, f.getBasaltHeightVariance())); + int spread = (int) Math.ceil(baseRadius); + + for (int c = 0; c < count; c++) { + double angle = rng.d(0.0, Math.PI * 2.0); + double dist = rng.d(0.0, spread); + int ox = (int) Math.round(Math.cos(angle) * dist); + int oz = (int) Math.round(Math.sin(angle) * dist); + double hVar = 1.0 - variance + rng.d(0.0, variance * 2.0); + int colHeight = Math.max(3, (int) Math.round(height * hVar)); + + for (int y = 0; y < colHeight; y++) { + for (int x = -colRadius; x <= colRadius; x++) { + for (int z = -colRadius; z <= colRadius; z++) { + if (Math.abs(x) + Math.abs(z) > colRadius) { + continue; + } + canvas.setBody(ox + x, y, oz + z); + } + } + } + if (colRadius > 0) { + canvas.setCap(ox, colHeight - 1, oz); + } + } + } + + public static void iceberg(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + long noiseSeed = rng.nextLong(); + double bodyHeight = Math.max(2.0, height * 0.42); + double radiusX = baseRadius * rng.d(1.15, 1.5); + double radiusZ = baseRadius * rng.d(1.0, 1.35); + ellipsoid(canvas, radiusX, bodyHeight, radiusZ, bodyHeight * 0.36, noiseSeed, f.getRoughness()); + + int peaks = Math.max(1, f.getIcebergPeaks()); + double phase = rng.d(0.0, Math.PI * 2.0); + for (int i = 0; i < peaks; i++) { + double angle = phase + (Math.PI * 2.0 * i / peaks) + rng.d(-0.35, 0.35); + double distance = rng.d(0.0, baseRadius * 0.62); + int offsetX = (int) Math.round(Math.cos(angle) * distance); + int offsetZ = (int) Math.round(Math.sin(angle) * distance); + int peakHeight = Math.max(3, (int) Math.round(height * rng.d(0.58, 1.0))); + double peakRadius = Math.max(1.0, baseRadius * rng.d(0.28, 0.58)); + double leanDistance = rng.d(0.0, Math.max(1.0, baseRadius * 0.45)); + taperedPeak(canvas, f, peakHeight, peakRadius, offsetX, offsetZ, angle, leanDistance, rng); + } + } + + public static void fissure(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + int count = Math.max(2, f.getFractureCount()); + double separation = Math.max(1.0, f.getFractureSeparation()); + double shardRadius = Math.max(1.0, baseRadius / Math.max(1.6, count * 0.72)); + double phase = rng.d(0.0, Math.PI * 2.0); + + for (int i = 0; i < count; i++) { + double lane = i - ((count - 1) / 2.0); + double offset = lane * (shardRadius * 2.0 + separation); + int offsetX = (int) Math.round(Math.cos(phase) * offset); + int offsetZ = (int) Math.round(Math.sin(phase) * offset); + double outwardAngle = lane < 0 ? phase + Math.PI : phase; + int shardHeight = Math.max(3, (int) Math.round(height * rng.d(0.62, 1.0))); + double leanDistance = rng.d(separation * 0.4, separation + baseRadius * 0.8); + taperedPeak(canvas, f, shardHeight, shardRadius, offsetX, offsetZ, outwardAngle, leanDistance, rng); + } + } + + public static void spiral(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + int steps = Math.max(12, height * 4); + double turns = Math.max(0.25, f.getSpiralTurns()); + double startRadius = Math.max(1.0, f.getSpiralRadius()); + double startThickness = Math.max(1.0, f.getSpiralThickness()); + double phase = rng.d(0.0, Math.PI * 2.0); + long noiseSeed = rng.nextLong(); + + for (int step = 0; step <= steps; step++) { + double t = step / (double) steps; + double angle = phase + Math.PI * 2.0 * turns * t; + double radius = startRadius * (1.0 - 0.72 * t); + int x = (int) Math.round(Math.cos(angle) * radius); + int y = (int) Math.round(t * (height - 1)); + int z = (int) Math.round(Math.sin(angle) * radius); + double thickness = Math.max(0.75, startThickness * (1.0 - 0.48 * t)); + ball(canvas, f, x, y, z, thickness, step == steps, noiseSeed, rng); + } + + double footRadius = Math.max(1.0, Math.min(baseRadius, startThickness + 1.0)); + disc(canvas, f, (int) Math.round(Math.cos(phase) * startRadius), 0, + (int) Math.round(Math.sin(phase) * startRadius), footRadius, false, rng); + } + + public static void overhang(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + int steps = Math.max(12, height * 4); + double reach = Math.max(1.0, f.getOverhangReach()); + double drop = Math.max(0.0, f.getOverhangDrop()); + double phase = Math.toRadians(f.getLeanAzimuth()) + rng.d(-0.18, 0.18); + double trunkHeight = Math.max(3.0, height * 0.62); + long noiseSeed = rng.nextLong(); + + for (int step = 0; step <= steps; step++) { + double t = step / (double) steps; + double extension; + double y; + if (t <= 0.58) { + double rise = t / 0.58; + extension = reach * 0.16 * rise * rise; + y = trunkHeight * rise; + } else { + double hook = (t - 0.58) / 0.42; + extension = reach * (0.16 + 0.84 * Math.sin(hook * Math.PI * 0.5)); + y = trunkHeight + Math.sin(hook * Math.PI) * height * 0.18 - drop * hook * hook; + } + int x = (int) Math.round(Math.cos(phase) * extension); + int z = (int) Math.round(Math.sin(phase) * extension); + double thickness = Math.max(0.9, baseRadius * (1.0 - 0.64 * t)); + ball(canvas, f, x, Math.max(0, (int) Math.round(y)), z, thickness, step == steps, noiseSeed, rng); + } + } + + private static void column(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, double topRadius, int extraBaseX, int extraBaseZ, RNG rng, boolean capTop) { + double lean = Math.toRadians(f.getLean()); + double azimuth = Math.toRadians(f.getLeanAzimuth()); + double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); + double jitter = Math.max(0.0, Math.min(1.0, f.getJitter())); + long noiseSeed = f.getSeed() + 9001L; + + for (int y = 0; y < height; y++) { + double t = height <= 1 ? 1.0 : (y / (double) (height - 1)); + double radius = FormationProfiles.radiusAt(f, baseRadius, topRadius, t); + double shear = Math.tan(lean) * y; + int cx = extraBaseX + (int) Math.round(Math.cos(azimuth) * shear); + int cz = extraBaseZ + (int) Math.round(Math.sin(azimuth) * shear); + boolean cap = capTop && y >= height - 2; + ringDisc(canvas, f, cx, y, cz, radius, roughness, jitter, noiseSeed, cap, rng); + } + } + + private static void setSpireCenter(FormationCanvas canvas, int x, int y, int z, boolean cap) { + if (cap) { + canvas.setCap(x, y, z); + } else { + canvas.setBody(x, y, z); + } + } + + private static void ringDisc(FormationCanvas canvas, IrisFormation f, int cx, int y, int cz, double radius, double roughness, double jitter, long noiseSeed, boolean cap, RNG rng) { + int r = (int) Math.ceil(radius) + 1; + for (int x = -r; x <= r; x++) { + for (int z = -r; z <= r; z++) { + double dist = Math.sqrt(x * x + z * z); + double perturb = (TreeFunctions.valueNoise3D(cx + x, y, cz + z, noiseSeed) - 0.5) * roughness * (radius + 1.0); + double effective = radius + perturb; + if (dist <= effective) { + if (jitter > 0 && dist > effective - 1.0 && rng.chance(jitter * 0.5)) { + continue; + } + if (cap) { + canvas.setCap(cx + x, y, cz + z); + } else { + canvas.setBody(cx + x, y, cz + z); + } + } + } + } + } + + private static void disc(FormationCanvas canvas, IrisFormation f, int cx, int y, int cz, double radius, boolean cap, RNG rng) { + int r = (int) Math.ceil(radius) + 1; + for (int x = -r; x <= r; x++) { + for (int z = -r; z <= r; z++) { + if (Math.sqrt(x * x + z * z) <= radius) { + if (cap) { + canvas.setCap(cx + x, y, cz + z); + } else { + canvas.setBody(cx + x, y, cz + z); + } + } + } + } + } + + private static void taperedPeak(FormationCanvas canvas, IrisFormation f, int height, double radius, + int offsetX, int offsetZ, double leanAngle, double leanDistance, RNG rng) { + long noiseSeed = rng.nextLong(); + double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); + double jitter = Math.max(0.0, Math.min(1.0, f.getJitter())); + for (int y = 0; y < height; y++) { + double t = height <= 1 ? 1.0 : y / (double) (height - 1); + int x = offsetX + (int) Math.round(Math.cos(leanAngle) * leanDistance * t * t); + int z = offsetZ + (int) Math.round(Math.sin(leanAngle) * leanDistance * t * t); + double layerRadius = Math.max(0.45, radius * Math.pow(1.0 - t, 0.72)); + ringDisc(canvas, f, x, y, z, layerRadius, roughness, jitter, noiseSeed, y >= height - 2, rng); + } + } + + private static void ellipsoid(FormationCanvas canvas, double radiusX, double radiusY, double radiusZ, + double centerY, long noiseSeed, double configuredRoughness) { + double roughness = Math.max(0.0, Math.min(1.0, configuredRoughness)); + int maxX = (int) Math.ceil(radiusX) + 1; + int maxY = (int) Math.ceil(radiusY) + 1; + int maxZ = (int) Math.ceil(radiusZ) + 1; + for (int x = -maxX; x <= maxX; x++) { + for (int y = 0; y <= maxY; y++) { + for (int z = -maxZ; z <= maxZ; z++) { + double nx = x / radiusX; + double ny = (y - centerY) / radiusY; + double nz = z / radiusZ; + double distance = nx * nx + ny * ny + nz * nz; + double wobble = (TreeFunctions.valueNoise3D(x, y, z, noiseSeed) - 0.5) * roughness * 0.55; + if (distance + wobble <= 1.0) { + canvas.setBody(x, y, z); + } + } + } + } + } + + private static void ball(FormationCanvas canvas, IrisFormation f, int centerX, int centerY, int centerZ, + double radius, boolean cap, long noiseSeed, RNG rng) { + int extent = (int) Math.ceil(radius); + double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); + double jitter = Math.max(0.0, Math.min(1.0, f.getJitter())); + for (int x = -extent; x <= extent; x++) { + for (int y = -extent; y <= extent; y++) { + for (int z = -extent; z <= extent; z++) { + double distance = Math.sqrt(x * x + y * y + z * z); + double perturb = (TreeFunctions.valueNoise3D(centerX + x, centerY + y, centerZ + z, noiseSeed) - 0.5) + * roughness * Math.max(1.0, radius * 0.6); + double effectiveRadius = radius + perturb; + if (distance > effectiveRadius + 0.2) { + continue; + } + if (jitter > 0.0 && distance > effectiveRadius - 0.75 && rng.chance(jitter * 0.35)) { + continue; + } + int targetY = centerY + y; + if (targetY < 0) { + continue; + } + if (cap) { + canvas.setCap(centerX + x, targetY, centerZ + z); + } else { + canvas.setBody(centerX + x, targetY, centerZ + z); + } + } + } + } + } + + private static void mirrorAcrossX(FormationCanvas canvas) { + Map cells = new HashMap<>(canvas.getCells()); + for (Map.Entry entry : cells.entrySet()) { + Vector3i position = entry.getKey(); + if (entry.getValue() == FormationCanvas.Role.CAP) { + canvas.setCap(-position.getBlockX(), position.getBlockY(), position.getBlockZ()); + } else { + canvas.setBody(-position.getBlockX(), position.getBlockY(), position.getBlockZ()); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java new file mode 100644 index 000000000..b13a70d7b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java @@ -0,0 +1,304 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.placement.IrisObjectLimit; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisStiltSettings; +import art.arcane.iris.engine.object.placement.IrisVacuumSettings; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.procedural.formation.FormationGenerator; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("formation") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A single procedurally generated natural formation, including rock landmarks and magical glacial silhouettes. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") +@Data +public class IrisFormation implements IrisProceduralPlacement { + private final transient AtomicCache> variantCache = new AtomicCache<>(); + + @Desc("A human readable name used in logs and as the variant load key.") + private String name = "formation"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per chunk for this formation to attempt placement. Use density for multiple per chunk.") + private double chance = 0.02; + + @MinNumber(1) + @Desc("If the chance check passes, attempt this many placements in the chunk.") + private int density = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("How many distinct variants to pre-bake for this formation. Higher means more variety at a small memory cost.") + private int variants = 6; + + @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") + private long seed = 1337; + + @Desc("The placement mode used to anchor the formation to the terrain.") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + + @Desc("Rotate this formation's placement.") + private IrisObjectRotation rotation = new IrisObjectRotation(); + + @Desc("Limit the max or min height of placement.") + private IrisObjectLimit clamp = new IrisObjectLimit(); + + @Desc("Whether this formation may place on the terrain surface, under carvings, or both.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + + @MinNumber(0) + @MaxNumber(16) + @Desc("Horizontal buffer, in blocks, beyond each lowest solid foundation block that must also be solid, un-carved ground.") + private int surfaceSupportBuffer = 3; + + @Desc("If true, the formation anchors on the terrain height ignoring the water surface.") + private boolean underwater = false; + + @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + + @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") + private IrisStiltSettings stiltSettings; + + @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") + private IrisVacuumSettings vacuumSettings; + + @Desc("The overall silhouette of the formation. Drives which sculpting routine the generator uses.") + private IrisFormationForm form = IrisFormationForm.SPIRE; + + @Required + @Desc("The main rock block, e.g. minecraft:stone. Ignored when blockPalette is set.") + @RegistryListBlockType + private String block = "minecraft:stone"; + + @Desc("A noise-driven palette for the main rock body. When set this overrides the single block, letting the body mix blocks by noise.") + private IrisMaterialPalette blockPalette = null; + + @Desc("Optional caprock block placed on the top crown of the formation (and the wide overhanging cap for HOODOO). Ignored when capPalette is set. When null and capPalette is unset, the formation uses its main rock everywhere.") + @RegistryListBlockType + private String capBlock = null; + + @Desc("A noise-driven palette for the caprock. When set this overrides the single capBlock.") + private IrisMaterialPalette capPalette = null; + + @Desc("Optional palette of strata (horizontal colored bands) blended into the rock body by y level. When set, every strataThickness blocks of height switches to the next strata block, producing the signature banded look. Falls back to the main block where unset.") + private IrisMaterialPalette strataPalette = null; + + @MinNumber(1) + @MaxNumber(32) + @Desc("The thickness in blocks of each horizontal strata band when strataPalette is set.") + private int strataThickness = 3; + + @MinNumber(1) + @Desc("Minimum total height of the formation in blocks.") + private int heightMin = 14; + + @MinNumber(1) + @Desc("Maximum total height of the formation in blocks.") + private int heightMax = 26; + + @MinNumber(1) + @Desc("Minimum base radius (half-width) of the formation in blocks.") + private int baseWidthMin = 3; + + @MinNumber(1) + @Desc("Maximum base radius (half-width) of the formation in blocks.") + private int baseWidthMax = 6; + + @MinNumber(0) + @Desc("The target radius (half-width) at the very top of the formation in blocks, before the profile is applied. 0 means taper to a point.") + private int topWidth = 0; + + @Desc("The function used to shape the formation radius over its height.") + private IrisFormationProfile profile = IrisFormationProfile.TAPER; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The normalized height (0 base, 1 top) of the pinched waist for the PARABOLIC profile (used by HOODOO).") + private double profileWaist = 0.55; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The minimum radius fraction at the waist for the PARABOLIC profile. Lower values pinch the waist tighter.") + private double profileWaistFloor = 0.35; + + @MinNumber(0) + @Desc("How far the formation leans, in degrees from vertical. 0 is perfectly upright. The whole body is sheared by this amount over its height.") + private double lean = 0; + + @Desc("Compass direction in degrees the formation leans toward when lean is non-zero.") + private double leanAzimuth = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Surface roughness from 0 (a clean smooth solid) to 1 (heavily eroded and pitted). Driven by 3D value noise that perturbs the radius so the formation never reads as a clean cylinder.") + private double roughness = 0.3; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Per-block surface jitter from 0 (none) to 1 (maximum). Randomly carves and adds isolated edge blocks to break up the silhouette.") + private double jitter = 0.15; + + @MinNumber(0) + @Desc("Extra wide cap radius in blocks added on top for the HOODOO form, producing the overhanging mushroom caprock. 0 disables the overhang.") + private int hoodooCapRadius = 3; + + @MinNumber(1) + @MaxNumber(6) + @Desc("The height in blocks of the HOODOO overhanging caprock slab.") + private int hoodooCapHeight = 3; + + @MinNumber(0) + @Desc("How wide the ARCH opening is in blocks (the gap between the two legs). The arch span is rasterized over this width.") + private int archSpan = 10; + + @MinNumber(1) + @Desc("The thickness in blocks of the ARCH legs and spanning curve.") + private int archThickness = 3; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How strongly an ARCH varies its leg steepness, crown position, depth bow and tube width between deterministic variants. 0 is symmetric and 1 is highly organic.") + private double archAsymmetry = 0.35; + + @MinNumber(2) + @MaxNumber(12) + @Desc("How many separate columns make up a BASALT_COLUMN cluster. Each column gets a randomized height around the formation height range.") + private int basaltColumns = 5; + + @MinNumber(1) + @Desc("The radius (half-width) in blocks of each individual column in a BASALT_COLUMN cluster.") + private int basaltColumnRadius = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How much the heights of individual BASALT_COLUMN columns vary from each other, from 0 (all equal) to 1 (highly varied).") + private double basaltHeightVariance = 0.45; + + @MinNumber(1) + @MaxNumber(12) + @Desc("How many tapered summits crown an ICEBERG formation.") + private int icebergPeaks = 3; + + @MinNumber(2) + @MaxNumber(8) + @Desc("How many separated shards form a FISSURE.") + private int fractureCount = 3; + + @MinNumber(1) + @MaxNumber(16) + @Desc("Open-air separation in blocks between the shards of a FISSURE.") + private int fractureSeparation = 2; + + @MinNumber(0.25) + @MaxNumber(6) + @Desc("How many complete turns a SPIRAL makes from base to tip.") + private double spiralTurns = 1.5; + + @MinNumber(1) + @MaxNumber(32) + @Desc("The starting distance in blocks between a SPIRAL and its open center.") + private int spiralRadius = 4; + + @MinNumber(1) + @MaxNumber(8) + @Desc("The radius in blocks of the tube swept along a SPIRAL.") + private int spiralThickness = 2; + + @MinNumber(1) + @MaxNumber(32) + @Desc("How far the hooked arm of an OVERHANG projects from its base.") + private int overhangReach = 8; + + @MinNumber(0) + @MaxNumber(16) + @Desc("How many blocks the tip of an OVERHANG curls downward.") + private int overhangDrop = 3; + + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> { + KList baked = new KList<>(); + int count = Math.max(1, variants); + + for (int i = 0; i < count; i++) { + IrisObject object = FormationGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + name + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + }); + } + + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(mode); + placement.setRotation(rotation); + placement.setClamp(clamp); + placement.setCarvingSupport(carvingSupport); + placement.setSurfaceSupportBuffer(surfaceSupportBuffer); + placement.setUnderwater(underwater); + placement.setTranslate(translate); + placement.setStiltSettings(stiltSettings); + placement.setVacuumSettings(vacuumSettings); + placement.setChance(chance); + placement.setDensity(density); + return placement; + } + + public boolean isPlausible() { + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java new file mode 100644 index 000000000..635066991 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java @@ -0,0 +1,45 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The overall silhouette of a procedural natural formation. Each form drives a distinct sculpting routine in the formation generator.") +public enum IrisFormationForm { + @Desc("A tall, slender needle of rock that tapers smoothly to a point at the top (a sharp pinnacle or stone spire).") + SPIRE, + @Desc("A column with a pinched, eroded waist and a wide overhanging caprock balanced on top (the classic desert hoodoo / mushroom rock).") + HOODOO, + @Desc("Two stout legs joined by a spanning curved bridge of rock overhead (a natural stone arch).") + ARCH, + @Desc("A chunky, blocky stack that tapers gently as it rises, like an isolated pillar of rock standing in water (a sea stack).") + SEA_STACK, + @Desc("A rounded, lumpy boulder formed from a noise-perturbed ellipsoid that sits low on the terrain.") + BOULDER, + @Desc("A tightly packed cluster of several vertical, near-hexagonal columns of varying height (a basalt column formation / giant's causeway).") + BASALT_COLUMN, + @Desc("A broad, faceted mound crowned by several irregular tapered peaks, suitable for icebergs and glacial outcrops.") + ICEBERG, + @Desc("Several separated, outward-leaning shards divided by open cracks.") + FISSURE, + @Desc("A tapered tube swept around a tightening helix, leaving open air through its curled center.") + SPIRAL, + @Desc("A grounded pillar that bends into a long hooked cantilever and curls downward at its tip.") + OVERHANG +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java new file mode 100644 index 000000000..de0d1ae40 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java @@ -0,0 +1,35 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("A width-shaping function evaluated over normalized height (0 at the base, 1 at the top). Controls how the formation radius scales between baseWidth at the bottom and topWidth at the top.") +public enum IrisFormationProfile { + @Desc("Same radius at every height (a straight cylinder of constant baseWidth).") + CONSTANT, + @Desc("Radius ramps straight from baseWidth at the bottom to topWidth at the top.") + LINEAR, + @Desc("Radius shrinks smoothly toward a point as height increases (an ease that drives the SPIRE needle and gentle SEA_STACK taper).") + TAPER, + @Desc("Radius pinches to a narrow waist near profileWaist then widens again toward the top (the eroded waist used by HOODOO columns).") + PARABOLIC, + @Desc("Radius bulges out to its maximum in the middle of the height range and narrows at both ends (a barrel / bulged column).") + BULGE +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java new file mode 100644 index 000000000..2c0f95362 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java @@ -0,0 +1,118 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.engine.object.procedural.fungi.IrisFungusCapShape; +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.iris.util.common.math.Vector3i; + +import java.util.Map; + +public final class FungusCapBuilder { + private FungusCapBuilder() { + } + + public static void build(Map roles, IrisFungus fungus, int baseRadius, double cx, int baseY, double cz, long seed) { + int radius = (int) Math.round(baseRadius + Math.max(0.0, fungus.getCapOverhang())); + int thickness = Math.max(1, Math.min(3, fungus.getCapThickness())); + double squish = Math.max(0.0, Math.min(1.0, fungus.getCapSquish())); + double droop = Math.max(0.0, fungus.getCapDroop()); + IrisFungusCapShape shape = fungus.getCapShape() == null ? IrisFungusCapShape.DOME : fungus.getCapShape(); + int icx = (int) Math.round(cx); + int icz = (int) Math.round(cz); + + boolean hasGill = blockOrPaletteSet(fungus.getGillBlock(), fungus.getGillPalette()); + boolean hasSpot = blockOrPaletteSet(fungus.getSpotBlock(), fungus.getSpotPalette()); + + double apexRise = apexRise(shape, radius) * (1.0 - 0.6 * squish); + double droopReach = Math.tan(Math.toRadians(droop)) * radius; + + for (int dx = -radius; dx <= radius; dx++) { + for (int dz = -radius; dz <= radius; dz++) { + double dist = Math.sqrt(dx * dx + dz * dz); + if (dist > radius + 0.5) { + continue; + } + double normalized = dist / Math.max(1.0, radius); + double surfaceTop = baseY + capSurface(shape, normalized, apexRise); + surfaceTop -= droopReach * Math.pow(normalized, 3); + + int topYi = (int) Math.round(surfaceTop); + for (int layer = 0; layer < thickness; layer++) { + int y = topYi - layer; + if (y < baseY - thickness) { + continue; + } + Vector3i pos = new Vector3i(icx + dx, y, icz + dz); + FungusCellRole role = FungusCellRole.CAP; + + boolean underside = layer == thickness - 1; + boolean topFace = layer == 0; + + if (underside && hasGill && rollNoise(icx + dx, y, icz + dz, seed + 4111L) <= fungus.getGillChance()) { + role = FungusCellRole.GILL; + } else if (topFace && hasSpot && spotNoise(icx + dx, y, icz + dz, seed + 9311L) <= fungus.getSpotChance()) { + role = FungusCellRole.SPOT; + } + + roles.putIfAbsent(pos, role); + } + } + } + } + + private static double apexRise(IrisFungusCapShape shape, int radius) { + return switch (shape) { + case DOME -> radius * 0.85; + case CONICAL -> radius * 1.4; + case FUNNEL -> radius * 0.5; + case FLAT -> radius * 0.35; + case FLAT_WIDE -> radius * 0.2; + }; + } + + private static double capSurface(IrisFungusCapShape shape, double normalized, double apexRise) { + double n = Math.max(0.0, Math.min(1.0, normalized)); + return switch (shape) { + case DOME -> apexRise * Math.sqrt(Math.max(0.0, 1.0 - n * n)); + case CONICAL -> apexRise * (1.0 - n); + case FUNNEL -> apexRise * (n * n); + case FLAT -> apexRise * Math.max(0.0, 1.0 - Math.pow(n, 4)); + case FLAT_WIDE -> apexRise * Math.max(0.0, 1.0 - Math.pow(n, 6)); + }; + } + + private static double rollNoise(int x, int y, int z, long seed) { + return TreeFunctions.valueNoise3D(x, y, z, seed); + } + + private static double spotNoise(int x, int y, int z, long seed) { + return TreeFunctions.valueNoise3D(Math.floorDiv(x, 2), y, Math.floorDiv(z, 2), seed); + } + + static boolean blockOrPaletteSet(String block, IrisMaterialPalette palette) { + if (IrisProceduralBlocks.paletteSet(palette)) { + return true; + } + return block != null && !block.isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java new file mode 100644 index 000000000..2dac80c8c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java @@ -0,0 +1,26 @@ +/* + * 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.procedural.fungi; + +enum FungusCellRole { + STEM, + CAP, + GILL, + SPOT +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java new file mode 100644 index 000000000..25f9d673c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java @@ -0,0 +1,104 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.HashMap; +import java.util.Map; + +public final class FungusGenerator { + private FungusGenerator() { + } + + public static IrisObject generate(IrisFungus fungus, int height, RNG rng, IrisData data) { + Map roles = new HashMap<>(); + long baseSeed = rng.getSeed(); + + if (fungus.isShelf()) { + FungusShelfBuilder.build(roles, fungus, rng, baseSeed); + } else { + buildUpright(roles, fungus, height, rng, baseSeed); + } + + if (roles.isEmpty()) { + return null; + } + + RNG paletteRng = new RNG(fungus.getSeed()); + Map resolved = new HashMap<>(); + for (Map.Entry entry : roles.entrySet()) { + Vector3i pos = entry.getKey(); + PlatformBlockState bd = resolveRole(fungus, entry.getValue(), data, pos, paletteRng); + if (bd == null) { + continue; + } + resolved.put(pos, bd); + } + + return IrisProceduralBlocks.assemble(resolved); + } + + private static void buildUpright(Map roles, IrisFungus fungus, int height, RNG rng, long baseSeed) { + int stemHeight = Math.max(1, height); + Map stemCells = new HashMap<>(); + double[] top = FungusStemBuilder.build(stemCells, fungus, stemHeight, baseSeed); + for (Vector3i v : stemCells.keySet()) { + roles.put(v, FungusCellRole.STEM); + } + + int radius = pickRadius(fungus, rng); + double cx = top[0]; + double cz = top[2]; + int capBaseY = (int) Math.round(top[1]); + FungusCapBuilder.build(roles, fungus, radius, cx, capBaseY, cz, baseSeed + 5557L); + } + + private static int pickRadius(IrisFungus fungus, RNG rng) { + int lo = Math.min(fungus.getCapRadiusMin(), fungus.getCapRadiusMax()); + int hi = Math.max(fungus.getCapRadiusMin(), fungus.getCapRadiusMax()); + lo = Math.max(1, lo); + hi = Math.max(lo, hi); + return rng.i(lo, hi + 1); + } + + private static PlatformBlockState resolveRole(IrisFungus fungus, FungusCellRole role, IrisData data, Vector3i pos, RNG paletteRng) { + int x = pos.getBlockX(); + int y = pos.getBlockY(); + int z = pos.getBlockZ(); + return switch (role) { + case STEM -> IrisProceduralBlocks.resolve(fungus.getStem(), fungus.getStemPalette(), data, x, y, z, paletteRng); + case CAP -> IrisProceduralBlocks.resolve(fungus.getCap(), fungus.getCapPalette(), data, x, y, z, paletteRng); + case GILL -> { + PlatformBlockState gill = IrisProceduralBlocks.resolve(fungus.getGillBlock(), fungus.getGillPalette(), data, x, y, z, paletteRng); + yield gill != null ? gill : IrisProceduralBlocks.resolve(fungus.getCap(), fungus.getCapPalette(), data, x, y, z, paletteRng); + } + case SPOT -> { + PlatformBlockState spot = IrisProceduralBlocks.resolve(fungus.getSpotBlock(), fungus.getSpotPalette(), data, x, y, z, paletteRng); + yield spot != null ? spot : IrisProceduralBlocks.resolve(fungus.getCap(), fungus.getCapPalette(), data, x, y, z, paletteRng); + } + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java new file mode 100644 index 000000000..9b10d7aa5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java @@ -0,0 +1,81 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.Map; + +public final class FungusShelfBuilder { + private FungusShelfBuilder() { + } + + public static void build(Map roles, IrisFungus fungus, RNG rng, long seed) { + int radius = Math.max(1, fungus.getShelfRadius()); + double azimuth = rng.d(0.0, Math.PI * 2.0); + double fanX = Math.sin(azimuth); + double fanZ = Math.cos(azimuth); + int stubHeight = Math.max(0, Math.min(2, fungus.getStemWidth())); + + for (int y = 0; y < stubHeight; y++) { + roles.put(new Vector3i(0, y, 0), FungusCellRole.STEM); + } + + int fanY = stubHeight; + boolean hasGill = FungusCapBuilder.blockOrPaletteSet(fungus.getGillBlock(), fungus.getGillPalette()); + boolean hasSpot = FungusCapBuilder.blockOrPaletteSet(fungus.getSpotBlock(), fungus.getSpotPalette()); + + for (int dx = -radius; dx <= radius; dx++) { + for (int dz = -radius; dz <= radius; dz++) { + double dist = Math.sqrt(dx * dx + dz * dz); + if (dist > radius + 0.5) { + continue; + } + double forward = dx * fanX + dz * fanZ; + if (forward < -0.5) { + continue; + } + double normalized = dist / Math.max(1.0, radius); + int lift = (int) Math.round(radius * 0.25 * (1.0 - normalized)); + int y = fanY + lift; + + FungusCellRole role = FungusCellRole.CAP; + if (hasSpot && spotNoise(dx, y, dz, seed + 9311L) <= fungus.getSpotChance()) { + role = FungusCellRole.SPOT; + } + roles.putIfAbsent(new Vector3i(dx, y, dz), role); + + if (hasGill && rollNoise(dx, y - 1, dz, seed + 4111L) <= fungus.getGillChance()) { + roles.putIfAbsent(new Vector3i(dx, y - 1, dz), FungusCellRole.GILL); + } + } + } + } + + private static double rollNoise(int x, int y, int z, long seed) { + return TreeFunctions.valueNoise3D(x, y, z, seed); + } + + private static double spotNoise(int x, int y, int z, long seed) { + return TreeFunctions.valueNoise3D(Math.floorDiv(x, 2), y, Math.floorDiv(z, 2), seed); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java new file mode 100644 index 000000000..397abfb52 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java @@ -0,0 +1,95 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; + +import java.util.Map; + +public final class FungusStemBuilder { + private FungusStemBuilder() { + } + + public static double[] build(Map stemCells, IrisFungus fungus, int stemHeight, long seed) { + int width = Math.max(1, Math.min(3, fungus.getStemWidth())); + double maxLean = stemHeight * Math.tan(Math.toRadians(Math.max(0.0, fungus.getStemCurve()))); + double leanRad = Math.toRadians(fungus.getStemLeanAzimuth()); + double leanX = Math.sin(leanRad); + double leanZ = Math.cos(leanRad); + double waveAmp = Math.max(0.0, fungus.getStemWaveAmplitude()); + double wavePeriods = fungus.getStemWavePeriods() == 0 ? 1.0 : fungus.getStemWavePeriods(); + double waveAzimuth = Math.toRadians(fungus.getStemLeanAzimuth() + 90.0); + double waveX = Math.sin(waveAzimuth); + double waveZ = Math.cos(waveAzimuth); + + double topCx = 0.0; + double topCz = 0.0; + int topY = Math.max(0, stemHeight - 1); + + for (int y = 0; y < stemHeight; y++) { + double t = stemHeight <= 1 ? 0.0 : y / (double) (stemHeight - 1); + double lean = maxLean * (t * t); + double wave = waveAmp * Math.sin(2.0 * Math.PI * wavePeriods * t + TreeFunctions.valueNoise1D(seed, seed) * Math.PI * 2.0); + double cx = lean * leanX + wave * waveX; + double cz = lean * leanZ + wave * waveZ; + + for (int[] xz : squarePositions(cx, cz, width)) { + stemCells.put(new Vector3i(xz[0], y, xz[1]), null); + } + + topCx = cx; + topCz = cz; + } + + return new double[]{topCx, topY, topCz}; + } + + static int[][] squarePositions(double cx, double cz, int width) { + if (width % 2 == 1) { + int half = width / 2; + int icx = (int) Math.round(cx); + int icz = (int) Math.round(cz); + int[][] out = new int[width * width][2]; + int idx = 0; + for (int dx = -half; dx <= half; dx++) { + for (int dz = -half; dz <= half; dz++) { + out[idx][0] = icx + dx; + out[idx][1] = icz + dz; + idx++; + } + } + return out; + } + int ox = (int) Math.floor(cx) - width / 2 + 1; + int oz = (int) Math.floor(cz) - width / 2 + 1; + int[][] out = new int[width * width][2]; + int idx = 0; + for (int dx = 0; dx < width; dx++) { + for (int dz = 0; dz < width; dz++) { + out[idx][0] = ox + dx; + out[idx][1] = oz + dz; + idx++; + } + } + return out; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java new file mode 100644 index 000000000..ba6fde25b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java @@ -0,0 +1,262 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.placement.IrisObjectLimit; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisStiltSettings; +import art.arcane.iris.engine.object.placement.IrisVacuumSettings; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.procedural.fungi.FungusGenerator; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("fungus") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A single procedurally generated fungus (giant mushroom or shelf fungus). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. The fungus is built as a stem column with a cap dome grown on top, mirroring the trunk-and-canopy model used by procedural trees.") +@Data +public class IrisFungus implements IrisProceduralPlacement { + private final transient AtomicCache> variantCache = new AtomicCache<>(); + + @Desc("A human readable name used in logs and as the variant load key.") + private String name = "fungus"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per chunk for this fungus to attempt placement. Use density for multiple per chunk.") + private double chance = 0.4; + + @MinNumber(1) + @Desc("If the chance check passes, attempt this many placements in the chunk.") + private int density = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("How many distinct variants to pre-bake for this fungus. Higher means more variety at a small memory cost.") + private int variants = 6; + + @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") + private long seed = 1337; + + @Desc("The placement mode used to anchor the fungus to the terrain.") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + + @Desc("Rotate this fungus's placement.") + private IrisObjectRotation rotation = new IrisObjectRotation(); + + @Desc("Limit the max or min height of placement.") + private IrisObjectLimit clamp = new IrisObjectLimit(); + + @Desc("Whether this fungus may place on the terrain surface, under carvings, or both.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + + @Desc("If true, the fungus anchors on the terrain height ignoring the water surface.") + private boolean underwater = false; + + @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + + @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") + private IrisStiltSettings stiltSettings; + + @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") + private IrisVacuumSettings vacuumSettings; + + @Required + @Desc("The stem block, e.g. minecraft:mushroom_stem. Ignored when stemPalette is set.") + @RegistryListBlockType + private String stem = "minecraft:mushroom_stem"; + + @Desc("A noise-driven palette for the stem. When set this overrides the single stem block, letting the stem mix blocks by noise.") + private IrisMaterialPalette stemPalette = null; + + @Required + @Desc("The cap block, e.g. minecraft:red_mushroom_block. Ignored when capPalette is set.") + @RegistryListBlockType + private String cap = "minecraft:red_mushroom_block"; + + @Desc("A noise-driven palette for the cap. When set this overrides the single cap block, letting the cap mix blocks by noise.") + private IrisMaterialPalette capPalette = null; + + @MinNumber(1) + @Desc("Minimum total stem height in blocks. Variants spread between this and stemHeightMax.") + private int stemHeightMin = 5; + + @MinNumber(1) + @Desc("Maximum total stem height in blocks. Variants spread between stemHeightMin and this.") + private int stemHeightMax = 9; + + @MinNumber(1) + @MaxNumber(3) + @Desc("Base stem width in blocks. 1 is a single column, 2 is a 2x2 stem, 3 is a chunky 3x3 trunk.") + private int stemWidth = 1; + + @Desc("How far the stem leans away from vertical, in degrees. 0 is perfectly upright; small values give an organic tilt.") + private double stemCurve = 0; + + @Desc("Compass direction in degrees the stem leans toward when stemCurve is non-zero.") + private double stemLeanAzimuth = 0; + + @MinNumber(0) + @Desc("Amplitude in blocks of a gentle sideways wave applied up the stem so it is not a perfectly straight ruler.") + private double stemWaveAmplitude = 0.4; + + @MinNumber(0.0001) + @Desc("The number of full sine wobbles applied over the stem height for the stem wave.") + private double stemWavePeriods = 1; + + @Desc("The silhouette of the cap (dome, flat umbrella, funnel, cone, or wide shallow slab).") + private IrisFungusCapShape capShape = IrisFungusCapShape.DOME; + + @MinNumber(1) + @Desc("Minimum cap radius in blocks (measured from the cap center to its rim).") + private int capRadiusMin = 3; + + @MinNumber(1) + @Desc("Maximum cap radius in blocks (measured from the cap center to its rim).") + private int capRadiusMax = 5; + + @MinNumber(1) + @MaxNumber(3) + @Desc("How many blocks thick the cap shell is. 1 is a thin skin, 3 is a fleshy slab.") + private int capThickness = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Vertical flatten factor for the cap. 0 leaves the cap at full height, 1 squashes it flat into a disc.") + private double capSquish = 0.4; + + @MinNumber(0) + @Desc("How far the cap rim droops downward, in degrees, curling the edge of the cap toward the ground.") + private double capDroop = 20; + + @MinNumber(0) + @Desc("How far the cap radius extends past the stem before the rim begins, in blocks. Larger values make the cap overhang the stem more.") + private double capOverhang = 2; + + @Desc("Optional block forming the gill layer on the underside of the cap (gills or a glow layer), e.g. minecraft:brown_mushroom_block or minecraft:shroomlight. Ignored when gillPalette is set or left null.") + @RegistryListBlockType + private String gillBlock = null; + + @Desc("A noise-driven palette for the underside gill layer. When set this overrides the single gillBlock.") + private IrisMaterialPalette gillPalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The fraction of underside cap blocks replaced by the gill block when a gill block or palette is set.") + private double gillChance = 0.85; + + @Desc("Optional block speckled across the top of the cap by noise (white toadstool dots, warts, glowing spots), e.g. minecraft:bone_block or minecraft:white_concrete. Ignored when spotPalette is set or left null.") + @RegistryListBlockType + private String spotBlock = null; + + @Desc("A noise-driven palette for the cap top spots. When set this overrides the single spotBlock.") + private IrisMaterialPalette spotPalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The fraction of top cap blocks replaced by the spot block, selected by value noise so spots cluster naturally.") + private double spotChance = 0.18; + + @Desc("If true, generate a bracket / shelf fungus instead of an upright mushroom: a small flat fan that grows sideways off a very short or absent stem, like a polypore clinging to a trunk.") + private boolean shelf = false; + + @MinNumber(1) + @Desc("The radius in blocks of the sideways fan when shelf is true.") + private int shelfRadius = 3; + + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> { + KList baked = new KList<>(); + int count = Math.max(1, variants); + int lo = Math.min(stemHeightMin, stemHeightMax); + int hi = Math.max(stemHeightMin, stemHeightMax); + RNG heightRng = new RNG(seed); + + for (int i = 0; i < count; i++) { + int height; + if (count == 1 || lo == hi) { + height = heightRng.i(lo, hi + 1); + } else { + double step = (hi - lo) / (double) (count - 1); + double base = lo + step * i; + double jitter = heightRng.d(-step * 0.3, step * 0.3); + height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); + } + + IrisObject object = FungusGenerator.generate(this, Math.max(1, height), new RNG(seed + (i * 7919L)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + name + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + }); + } + + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(mode); + placement.setRotation(rotation); + placement.setClamp(clamp); + placement.setCarvingSupport(carvingSupport); + placement.setUnderwater(underwater); + placement.setTranslate(translate); + placement.setStiltSettings(stiltSettings); + placement.setVacuumSettings(vacuumSettings); + placement.setChance(chance); + placement.setDensity(density); + return placement; + } + + public boolean isPlausible() { + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java new file mode 100644 index 000000000..449532565 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java @@ -0,0 +1,35 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The silhouette of the mushroom cap. Each shape drives how the cap radius and thickness vary from its apex down to the rim, giving the fungus a distinct profile.") +public enum IrisFungusCapShape { + @Desc("A rounded hemisphere cap that bulges up and curls slightly under at the rim, the classic red toadstool dome.") + DOME, + @Desc("A wide, nearly flat umbrella that holds its full radius almost to the edge before dropping, the brown-mushroom plate look.") + FLAT, + @Desc("An upturned bowl whose rim lifts higher than its center, cupping upward like a chanterelle or funnel mushroom.") + FUNNEL, + @Desc("A tall pointed cone that tapers from a broad base to a sharp apex, the witch-hat parasol silhouette.") + CONICAL, + @Desc("A very wide but shallow slab, a low overhanging shelf-like roof that spreads far past the stem with minimal vertical rise.") + FLAT_WIDE +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java new file mode 100644 index 000000000..10e7f190a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java @@ -0,0 +1,219 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.placement.IrisObjectLimit; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisStiltSettings; +import art.arcane.iris.engine.object.placement.IrisVacuumSettings; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.RegistryListBlockType; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.procedural.ruin.RuinGenerator; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("ruin") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A single procedurally generated ruin: a crumbling man-made structure (pillar, wall, arch, foundation slab, or rubble pile). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Weathering swaps blocks for mossy or cracked variants by noise, erosion deletes blocks so the shape reads as collapsed, and a buried fraction sinks the ruin into the terrain.") +@Data +public class IrisRuin implements IrisProceduralPlacement { + private final transient AtomicCache> variantCache = new AtomicCache<>(); + + @Desc("A human readable name used in logs and as the variant load key (procedural/#).") + private String name = "ruin"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance (0-1) per chunk for this ruin to attempt placement. Use density to attempt more than one per chunk once the chance check passes.") + private double chance = 0.05; + + @MinNumber(1) + @Desc("If the chance check passes, attempt this many placements in the chunk. Defaults to a single ruin per qualifying chunk.") + private int density = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("How many distinct variants to pre-bake for this ruin. Higher means more variety (different heights, gap patterns, erosion seeds) at a small memory cost.") + private int variants = 6; + + @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants. Every random choice (size, weathering mask, erosion mask, accents) is derived from this.") + private long seed = 1337; + + @Desc("The placement mode used to anchor the ruin to the terrain. MIN_HEIGHT plants the lowest footprint corner on the ground (good for slabs and rubble on slopes); CENTER_HEIGHT averages the footprint (good for tall pillars and arches).") + private ObjectPlaceMode mode = ObjectPlaceMode.MIN_HEIGHT; + + @Desc("Rotate this ruin's placement so variants do not all face the same way.") + private IrisObjectRotation rotation = new IrisObjectRotation(); + + @Desc("Limit the max or min terrain height at which this ruin may place.") + private IrisObjectLimit clamp = new IrisObjectLimit(); + + @Desc("Whether this ruin may place on the terrain surface, under carvings (caves), or both. SURFACE_ONLY keeps ruins above ground.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + + @Desc("If true the ruin anchors on the terrain height ignoring the water surface, so it can sit submerged. If false (default) it anchors to the surface and avoids water.") + private boolean underwater = false; + + @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + + @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") + private IrisStiltSettings stiltSettings; + + @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") + private IrisVacuumSettings vacuumSettings; + + @Required + @Desc("The primary structural block, e.g. minecraft:cobblestone or minecraft:stone_bricks. Ignored when blockPalette is set. This is the bulk material of the ruin before weathering swaps some of it out.") + @RegistryListBlockType + private String block = "minecraft:cobblestone"; + + @Desc("A noise-driven palette for the primary block. When set this overrides the single block, letting the structure mix materials by noise. Palette wins over the block string via IrisProceduralBlocks.resolve.") + private IrisMaterialPalette blockPalette = null; + + @Desc("The overall silhouette of the ruin: PILLAR (broken column), WALL (gapped segment), ARCH (two legs plus a curved span), FLOOR_SLAB (foundation patch), or RUBBLE (low scattered pile).") + private IrisRuinForm form = IrisRuinForm.PILLAR; + + @MinNumber(1) + @Desc("Minimum structure height in blocks (PILLAR/WALL/ARCH height, slab thickness for FLOOR_SLAB, mound height for RUBBLE). Variants interpolate between this and heightMax.") + private int heightMin = 4; + + @MinNumber(1) + @Desc("Maximum structure height in blocks. Variants interpolate between heightMin and this so taller and shorter ruins coexist.") + private int heightMax = 9; + + @MinNumber(1) + @Desc("Minimum footprint width (X axis) in blocks: column/leg thickness for PILLAR/ARCH, wall thickness for WALL, slab width for FLOOR_SLAB, blob width for RUBBLE.") + private int widthMin = 1; + + @MinNumber(1) + @Desc("Maximum footprint width (X axis) in blocks. Variants interpolate between widthMin and this.") + private int widthMax = 3; + + @MinNumber(1) + @Desc("Minimum footprint length (Z axis) in blocks: wall run length, arch leg spacing, slab length, rubble blob length.") + private int lengthMin = 3; + + @MinNumber(1) + @Desc("Maximum footprint length (Z axis) in blocks. Variants interpolate between lengthMin and this.") + private int lengthMax = 7; + + @Desc("A palette of weathered variants (mossy/cracked block ids) blended over the structure by noise. When set this drives weathering; otherwise weatheredBlock is used.") + private IrisMaterialPalette weatheringPalette = null; + + @Desc("A single weathered block id used when weatheringPalette is not set, e.g. minecraft:mossy_cobblestone. Applied to a noise-selected fraction of the structure, biased toward the lower rows.") + @RegistryListBlockType + private String weatheredBlock = "minecraft:mossy_cobblestone"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How much of the structure is replaced by weathered blocks (0 none, 1 nearly all). The replacement mask is value-noise driven and weighted so lower rows weather more than upper rows, mimicking moss climbing from the ground.") + private double mossiness = 0.45; + + @MinNumber(0) + @MaxNumber(8) + @Desc("The scale of the weathering noise. Higher values produce smaller, busier moss/crack patches; lower values produce broad continuous weathered zones.") + private double weatheringScale = 1.0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How crumbled the ruin is (0 intact, 1 mostly gone). Blocks whose value-noise falls below this threshold are deleted, so the shape reads as collapsed. Structural integrity is preserved: the bottom row and core legs are never eroded away.") + private double erosion = 0.25; + + @MinNumber(0) + @MaxNumber(8) + @Desc("The scale of the erosion noise. Higher values knock out small speckled holes; lower values carve larger missing chunks out of the silhouette.") + private double erosionScale = 1.5; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How far the structure extends below the surface as a fraction of its height (0 sits fully on top, 1 sinks it a full height into the ground). The buried rows live at negative y so the ruin reads as settled and partly swallowed by the terrain.") + private double buriedFraction = 0.2; + + @ArrayType(min = 1, type = IrisRuinDecorator.class) + @Desc("Accent decorators applied after the ruin is built and eroded (moss carpets and lanterns on broken tops, vines and lichen on the faces, rubble and growth scattered around the base).") + private KList accents = new KList<>(); + + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> { + KList baked = new KList<>(); + int count = Math.max(1, variants); + + for (int i = 0; i < count; i++) { + IrisObject object = RuinGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + name + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + }); + } + + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(mode); + placement.setRotation(rotation); + placement.setClamp(clamp); + placement.setCarvingSupport(carvingSupport); + placement.setUnderwater(underwater); + placement.setTranslate(translate); + placement.setStiltSettings(stiltSettings); + placement.setVacuumSettings(vacuumSettings); + placement.setChance(chance); + placement.setDensity(density); + return placement; + } + + public boolean isPlausible() { + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java new file mode 100644 index 000000000..35f2a74b4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java @@ -0,0 +1,60 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +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.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("ruin-decorator") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("An accent block applied to a generated ruin after it is built and eroded, such as moss carpets on broken tops, vines on the faces, or rubble scattered around the base.") +@Data +public class IrisRuinDecorator { + @Desc("Where on the ruin this accent is placed. TOP sits on the highest block of each column, SURFACE clings to air-facing vertical faces, BASE_SCATTER rings the ground footprint around the base.") + private IrisRuinDecoratorTarget target = IrisRuinDecoratorTarget.TOP; + + @Required + @Desc("The block id to place, e.g. minecraft:moss_carpet or minecraft:vine. Ignored when palette is set.") + @RegistryListBlockType + private String block = ""; + + @Desc("A noise-driven palette for this decorator. When set this overrides the single block, letting the accent mix blocks by noise. Resolved through IrisProceduralBlocks.resolve so the palette wins over the string.") + private IrisMaterialPalette palette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance (0-1) per candidate position for this decorator to actually place. 1 covers every candidate, lower values leave sparse, patchy accents.") + private double chance = 0.4; + + @MinNumber(1) + @Desc("For the BASE_SCATTER target, how many blocks beyond the ruin footprint the scatter ring extends outward in each direction. Higher values fling rubble and growth further from the structure.") + private int scatterRadius = 2; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java new file mode 100644 index 000000000..f3e13b96a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java @@ -0,0 +1,31 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Where a ruin accent block is placed after the ruin has been built and eroded.") +public enum IrisRuinDecoratorTarget { + @Desc("On top of the highest surviving block in each column (moss carpets, snow, sculk, lanterns on broken tops).") + TOP, + @Desc("On air-facing vertical sides of any surviving block (vines, glow lichen, climbing growth on the ruin faces).") + SURFACE, + @Desc("Scattered across the ground footprint around the y=0 base ring, wider than the structure itself (loose rubble, mushrooms, grass tufts ringing the ruin).") + BASE_SCATTER +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java new file mode 100644 index 000000000..507eac57d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java @@ -0,0 +1,35 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("The overall silhouette of a procedural ruin. Each form rasterizes a different crumbling man-made shape from the same size, weathering, and erosion settings.") +public enum IrisRuinForm { + @Desc("A broken vertical column. A square trunk (widthMin..widthMax footprint) rises to a randomized height then snaps off with a jagged crown, leaving a toppled stub. Use for ancient pillars and obelisk stumps.") + PILLAR, + @Desc("A standing wall segment. A flat slab spanning lengthMin..lengthMax long and heightMin..heightMax tall, thickness widthMin..widthMax, punched through with noise-driven gaps and a ragged top edge. Use for collapsed building sides and fortifications.") + WALL, + @Desc("A freestanding arch. Two legs spaced by lengthMin..lengthMax joined at the top by a rasterized semicircular span (the lintel), so the structure literally arches. Use for gateways, aqueduct bays, and ruined doorways.") + ARCH, + @Desc("A flat foundation patch. A single (or few) block-thick slab covering a widthMin..lengthMax footprint at ground level, heavily eroded into an irregular outline. Use for floor remnants, plazas, and building foundations.") + FLOOR_SLAB, + @Desc("A low scattered debris pile. A noise blob of partial blocks mounded near the ground, tallest at the center and thinning toward the edges. Use for collapsed-structure rubble and scree.") + RUBBLE +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java new file mode 100644 index 000000000..abdd58932 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java @@ -0,0 +1,107 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.Vector3i; + +import java.util.HashMap; +import java.util.Map; + +final class RuinBlockCanvas { + enum Role { + STRUCTURE, + ACCENT + } + + static final class Cell { + private Role role; + private boolean structural; + private PlatformBlockState accentData; + + Cell(Role role, boolean structural) { + this.role = role; + this.structural = structural; + } + + Role role() { + return role; + } + + boolean structural() { + return structural; + } + + PlatformBlockState accentData() { + return accentData; + } + + void promote(Role next, boolean structuralNext) { + this.role = next; + this.structural = this.structural || structuralNext; + } + + void makeAccent(PlatformBlockState data) { + this.role = Role.ACCENT; + this.structural = false; + this.accentData = data; + } + } + + private final Map cells = new HashMap<>(); + + Map cells() { + return cells; + } + + void set(int x, int y, int z, Role role, boolean structural) { + Vector3i key = new Vector3i(x, y, z); + Cell existing = cells.get(key); + if (existing == null) { + cells.put(key, new Cell(role, structural)); + } else { + existing.promote(role, structural); + } + } + + void accent(int x, int y, int z, PlatformBlockState data) { + if (data == null) { + return; + } + cells.put(new Vector3i(x, y, z), accentCell(data)); + } + + private static Cell accentCell(PlatformBlockState data) { + Cell cell = new Cell(Role.ACCENT, false); + cell.makeAccent(data); + return cell; + } + + boolean has(int x, int y, int z) { + return cells.containsKey(new Vector3i(x, y, z)); + } + + Cell get(int x, int y, int z) { + return cells.get(new Vector3i(x, y, z)); + } + + void remove(int x, int y, int z) { + cells.remove(new Vector3i(x, y, z)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java new file mode 100644 index 000000000..430d04683 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java @@ -0,0 +1,122 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.engine.object.procedural.ruin.IrisRuinDecorator; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +final class RuinDecoratorApplier { + private static final int[][] HORIZONTAL = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}}; + + private RuinDecoratorApplier() { + } + + static void apply(RuinBlockCanvas canvas, IrisRuinDecorator decorator, IrisData data, long seed, RNG rng) { + List candidates = switch (decorator.getTarget()) { + case TOP -> topCandidates(canvas); + case SURFACE -> surfaceCandidates(canvas); + case BASE_SCATTER -> baseScatterCandidates(canvas, Math.max(1, decorator.getScatterRadius())); + }; + + RNG paletteRng = new RNG(seed); + for (Vector3i v : candidates) { + if (!rng.chance(decorator.getChance())) { + continue; + } + PlatformBlockState bd = IrisProceduralBlocks.resolve(decorator.getBlock(), decorator.getPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + if (bd != null) { + canvas.accent(v.getBlockX(), v.getBlockY(), v.getBlockZ(), bd); + } + } + } + + private static List topCandidates(RuinBlockCanvas canvas) { + Map highest = new HashMap<>(); + for (Vector3i v : canvas.cells().keySet()) { + long key = columnKey(v.getBlockX(), v.getBlockZ()); + Integer current = highest.get(key); + if (current == null || v.getBlockY() > current) { + highest.put(key, v.getBlockY()); + } + } + List out = new ArrayList<>(); + for (Map.Entry entry : highest.entrySet()) { + int x = (int) (entry.getKey() >> 32); + int z = (int) (entry.getKey() & 0xFFFFFFFFL); + int y = entry.getValue() + 1; + if (!canvas.has(x, y, z)) { + out.add(new Vector3i(x, y, z)); + } + } + return out; + } + + private static List surfaceCandidates(RuinBlockCanvas canvas) { + List out = new ArrayList<>(); + for (Vector3i v : new ArrayList<>(canvas.cells().keySet())) { + for (int[] dir : HORIZONTAL) { + int nx = v.getBlockX() + dir[0]; + int ny = v.getBlockY(); + int nz = v.getBlockZ() + dir[2]; + if (!canvas.has(nx, ny, nz)) { + out.add(new Vector3i(nx, ny, nz)); + } + } + } + return out; + } + + private static List baseScatterCandidates(RuinBlockCanvas canvas, int radius) { + int minX = Integer.MAX_VALUE; + int minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; + int minY = Integer.MAX_VALUE; + for (Vector3i v : canvas.cells().keySet()) { + minX = Math.min(minX, v.getBlockX()); + minZ = Math.min(minZ, v.getBlockZ()); + maxX = Math.max(maxX, v.getBlockX()); + maxZ = Math.max(maxZ, v.getBlockZ()); + minY = Math.min(minY, v.getBlockY()); + } + + List out = new ArrayList<>(); + for (int x = minX - radius; x <= maxX + radius; x++) { + for (int z = minZ - radius; z <= maxZ + radius; z++) { + if (!canvas.has(x, minY, z) && !canvas.has(x, minY + 1, z)) { + out.add(new Vector3i(x, minY, z)); + } + } + } + return out; + } + + private static long columnKey(int x, int z) { + return ((long) x << 32) | (z & 0xFFFFFFFFL); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java new file mode 100644 index 000000000..ea65ecd9f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java @@ -0,0 +1,199 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.engine.object.procedural.ruin.IrisRuin; +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class RuinGenerator { + private RuinGenerator() { + } + + public static IrisObject generate(IrisRuin ruin, int variantIndex, RNG rng, IrisData data) { + int count = Math.max(1, ruin.getVariants()); + int height = pick(ruin.getHeightMin(), ruin.getHeightMax(), variantIndex, count, rng); + int width = pick(ruin.getWidthMin(), ruin.getWidthMax(), variantIndex, count, rng); + int length = pick(ruin.getLengthMin(), ruin.getLengthMax(), variantIndex, count, rng); + + RuinBlockCanvas canvas = new RuinBlockCanvas(); + switch (ruin.getForm()) { + case PILLAR -> RuinShapes.pillar(canvas, Math.max(1, width), Math.max(2, height), rng); + case WALL -> RuinShapes.wall(canvas, Math.max(1, width), Math.max(2, length), Math.max(2, height), rng); + case ARCH -> RuinShapes.arch(canvas, Math.max(1, width), Math.max(3, length), Math.max(3, height), rng); + case FLOOR_SLAB -> RuinShapes.floorSlab(canvas, Math.max(3, width), Math.max(3, length), Math.max(1, Math.min(height, 2))); + case RUBBLE -> RuinShapes.rubble(canvas, Math.max(3, width), Math.max(3, length), Math.max(1, Math.min(height, 4)), rng); + } + + applyBurial(ruin, canvas, height); + applyErosion(ruin, canvas); + applyAccents(ruin, canvas, rng, data); + + return resolve(ruin, canvas, data); + } + + private static int pick(int lo, int hi, int variantIndex, int count, RNG rng) { + int min = Math.min(lo, hi); + int max = Math.max(lo, hi); + if (min == max || count <= 1) { + return rng.i(min, max + 1); + } + double step = (max - min) / (double) (count - 1); + double base = min + step * variantIndex; + double jitter = rng.d(-step * 0.3, step * 0.3); + return (int) Math.round(Math.max(min, Math.min(max, base + jitter))); + } + + private static void applyBurial(IrisRuin ruin, RuinBlockCanvas canvas, int height) { + double fraction = clamp01(ruin.getBuriedFraction()); + if (fraction <= 0.0) { + return; + } + int sink = (int) Math.round(height * fraction); + if (sink <= 0) { + return; + } + Map moved = new HashMap<>(); + for (Map.Entry entry : canvas.cells().entrySet()) { + Vector3i v = entry.getKey(); + moved.put(new Vector3i(v.getBlockX(), v.getBlockY() - sink, v.getBlockZ()), entry.getValue()); + } + canvas.cells().clear(); + canvas.cells().putAll(moved); + } + + private static void applyErosion(IrisRuin ruin, RuinBlockCanvas canvas) { + double erosion = clamp01(ruin.getErosion()); + if (erosion <= 0.0) { + return; + } + double scale = Math.max(0.0001, ruin.getErosionScale()); + long erosionSeed = ruin.getSeed() * 0x2545F4914F6CDD1DL + 17L; + int minY = Integer.MAX_VALUE; + for (Vector3i v : canvas.cells().keySet()) { + minY = Math.min(minY, v.getBlockY()); + } + + List doomed = new ArrayList<>(); + for (Map.Entry entry : canvas.cells().entrySet()) { + Vector3i v = entry.getKey(); + RuinBlockCanvas.Cell cell = entry.getValue(); + if (cell.structural() || v.getBlockY() <= minY) { + continue; + } + int sx = (int) Math.round(v.getBlockX() * scale); + int sy = (int) Math.round(v.getBlockY() * scale); + int sz = (int) Math.round(v.getBlockZ() * scale); + double n = TreeFunctions.valueNoise3D(sx, sy, sz, erosionSeed); + if (n < erosion) { + doomed.add(v); + } + } + for (Vector3i v : doomed) { + canvas.cells().remove(v); + } + } + + private static void applyAccents(IrisRuin ruin, RuinBlockCanvas canvas, RNG rng, IrisData data) { + if (ruin.getAccents() == null || ruin.getAccents().isEmpty()) { + return; + } + int decoratorIndex = 0; + for (art.arcane.iris.engine.object.procedural.ruin.IrisRuinDecorator decorator : ruin.getAccents()) { + RuinDecoratorApplier.apply(canvas, decorator, data, ruin.getSeed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); + decoratorIndex++; + } + } + + private static IrisObject resolve(IrisRuin ruin, RuinBlockCanvas canvas, IrisData data) { + if (canvas.cells().isEmpty()) { + return null; + } + double scale = Math.max(0.0001, ruin.getWeatheringScale()); + double mossiness = clamp01(ruin.getMossiness()); + long weatherSeed = ruin.getSeed() * 0x9E3779B97F4A7C15L + 101L; + RNG paletteRng = new RNG(ruin.getSeed()); + + int minY = Integer.MAX_VALUE; + int maxY = Integer.MIN_VALUE; + for (Vector3i v : canvas.cells().keySet()) { + minY = Math.min(minY, v.getBlockY()); + maxY = Math.max(maxY, v.getBlockY()); + } + int span = Math.max(1, maxY - minY); + + Map blocks = new HashMap<>(); + for (Map.Entry entry : canvas.cells().entrySet()) { + Vector3i v = entry.getKey(); + RuinBlockCanvas.Cell cell = entry.getValue(); + PlatformBlockState bd; + if (cell.role() == RuinBlockCanvas.Role.ACCENT) { + bd = cell.accentData(); + } else { + bd = structuralBlock(ruin, cell, v, data, paletteRng, scale, mossiness, weatherSeed, minY, span); + } + if (bd != null) { + blocks.put(v, bd); + } + } + + return IrisProceduralBlocks.assemble(blocks); + } + + private static PlatformBlockState structuralBlock(IrisRuin ruin, RuinBlockCanvas.Cell cell, Vector3i v, IrisData data, RNG paletteRng, double scale, double mossiness, long weatherSeed, int minY, int span) { + boolean weathered = false; + if (mossiness > 0.0) { + int sx = (int) Math.round(v.getBlockX() * scale); + int sy = (int) Math.round(v.getBlockY() * scale); + int sz = (int) Math.round(v.getBlockZ() * scale); + double n = TreeFunctions.valueNoise3D(sx, sy, sz, weatherSeed); + double normalized = (v.getBlockY() - minY) / (double) span; + double gradient = 1.0 - 0.6 * normalized; + weathered = n < mossiness * gradient; + } + + if (weathered) { + PlatformBlockState wd = IrisProceduralBlocks.resolve(ruin.getWeatheredBlock(), ruin.getWeatheringPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + if (wd != null) { + return wd; + } + } + return IrisProceduralBlocks.resolve(ruin.getBlock(), ruin.getBlockPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + } + + private static double clamp01(double value) { + if (value < 0.0) { + return 0.0; + } + if (value > 1.0) { + return 1.0; + } + return value; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java new file mode 100644 index 000000000..83e8ba91d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java @@ -0,0 +1,146 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; +import art.arcane.volmlib.util.math.RNG; + +final class RuinShapes { + private RuinShapes() { + } + + static void pillar(RuinBlockCanvas canvas, int width, int height, RNG rng) { + int half = (width - 1) / 2; + int broken = Math.max(2, height - rng.i(0, Math.max(1, height / 3))); + for (int y = 0; y < broken; y++) { + boolean bottom = y == 0; + int jitter = y >= broken - 1 ? rng.i(0, 2) : 0; + for (int x = -half; x <= half; x++) { + for (int z = -half; z <= half; z++) { + if (y == broken - 1 && jitter > 0 && (Math.abs(x) == half || Math.abs(z) == half) && rng.chance(0.5)) { + continue; + } + canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, bottom); + } + } + } + + int stub = rng.i(0, 3); + if (stub > 0) { + int dir = rng.i(0, 4); + int dx = dir == 0 ? 1 : (dir == 1 ? -1 : 0); + int dz = dir == 2 ? 1 : (dir == 3 ? -1 : 0); + for (int s = 1; s <= stub; s++) { + canvas.set((half + s) * dx, 0, (half + s) * dz, RuinBlockCanvas.Role.STRUCTURE, true); + } + } + } + + static void wall(RuinBlockCanvas canvas, int thickness, int length, int height, RNG rng) { + int half = (length - 1) / 2; + int tHalf = (thickness - 1) / 2; + long edgeSeed = rng.lmax(); + for (int z = -half; z <= half; z++) { + int top = height - jaggedDrop(z, height, edgeSeed); + for (int y = 0; y < top; y++) { + if (y > 0 && rng.chance(0.10)) { + continue; + } + for (int x = -tHalf; x <= thickness - 1 - tHalf; x++) { + canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, y == 0); + } + } + } + } + + static void arch(RuinBlockCanvas canvas, int thickness, int span, int height, RNG rng) { + int legSpacing = Math.max(2, span); + int legGap = (legSpacing - 1) / 2; + int tHalf = (thickness - 1) / 2; + int legTop = Math.max(2, height - Math.max(2, (legSpacing / 2))); + + for (int side = -1; side <= 1; side += 2) { + int legZ = side * legGap; + for (int y = 0; y < legTop; y++) { + for (int x = -tHalf; x <= thickness - 1 - tHalf; x++) { + canvas.set(x, y, legZ, RuinBlockCanvas.Role.STRUCTURE, y <= 1); + } + } + } + + double radius = legGap; + int crown = legTop + (int) Math.round(radius); + for (int z = -legGap; z <= legGap; z++) { + double inside = radius * radius - (z * z); + if (inside < 0) { + continue; + } + int y = legTop + (int) Math.round(Math.sqrt(inside)); + for (int yy = legTop; yy <= y && yy <= crown; yy++) { + boolean keystone = Math.abs(z) <= 1; + for (int x = -tHalf; x <= thickness - 1 - tHalf; x++) { + canvas.set(x, yy, z, RuinBlockCanvas.Role.STRUCTURE, keystone); + } + } + } + } + + static void floorSlab(RuinBlockCanvas canvas, int width, int length, int thickness) { + int xHalf = (width - 1) / 2; + int zHalf = (length - 1) / 2; + for (int y = 0; y < thickness; y++) { + for (int x = -xHalf; x <= width - 1 - xHalf; x++) { + for (int z = -zHalf; z <= length - 1 - zHalf; z++) { + canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, y == 0); + } + } + } + } + + static void rubble(RuinBlockCanvas canvas, int width, int length, int peak, RNG rng) { + int xHalf = (width - 1) / 2; + int zHalf = (length - 1) / 2; + long blobSeed = rng.lmax(); + double rx = Math.max(1.0, width / 2.0); + double rz = Math.max(1.0, length / 2.0); + + for (int x = -xHalf; x <= width - 1 - xHalf; x++) { + for (int z = -zHalf; z <= length - 1 - zHalf; z++) { + double radial = (x * x) / (rx * rx) + (z * z) / (rz * rz); + if (radial > 1.2) { + continue; + } + double falloff = Math.max(0.0, 1.0 - radial); + double noise = art.arcane.iris.engine.object.procedural.tree.TreeFunctions.valueNoise3D(x, 0, z, blobSeed); + int columnHeight = (int) Math.round(peak * falloff * (0.6 + 0.4 * noise)); + for (int y = 0; y <= columnHeight; y++) { + if (y > 0 && rng.chance(0.25)) { + continue; + } + canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, y == 0 && radial < 0.5); + } + } + } + } + + private static int jaggedDrop(int z, int height, long seed) { + double n = art.arcane.iris.engine.object.procedural.tree.TreeFunctions.valueNoise1D(z * 0.9, seed); + return (int) Math.round(n * Math.max(1, height - 1) * 0.6); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java new file mode 100644 index 000000000..7d4f9a7a3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java @@ -0,0 +1,343 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.placement.IrisObjectLimit; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisStiltSettings; +import art.arcane.iris.engine.object.placement.IrisVacuumSettings; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.RegistryListBlockType; +import art.arcane.iris.engine.object.annotations.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.engine.object.procedural.tree.ProceduralTreeGenerator; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("procedural-tree") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A single procedurally generated tree. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") +@Data +public class IrisProceduralTree implements IrisProceduralPlacement { + private final transient AtomicCache> variantCache = new AtomicCache<>(); + + @Desc("A human readable name used in logs and as the variant load key.") + private String name = "procedural-tree"; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per chunk for this tree to attempt placement. Use density for multiple per chunk.") + private double chance = 0.4; + + @MinNumber(1) + @Desc("If the chance check passes, attempt this many placements in the chunk.") + private int density = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("How many distinct variants to pre-bake for this tree. Higher means more variety at a small memory cost.") + private int variants = 8; + + @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") + private long seed = 1337; + + @Desc("If true (default) leaves are placed with vanilla distance-from-wood values and persistent=false so leaf decay behaves naturally and the tree reads as plausible. If false, leaves are forced persistent and never decay (a raw object dump).") + private boolean plausible = true; + + @Desc("The placement mode used to anchor the tree to the terrain.") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + + @Desc("Rotate this tree's placement.") + private IrisObjectRotation rotation = new IrisObjectRotation(); + + @Desc("Limit the max or min height of placement.") + private IrisObjectLimit clamp = new IrisObjectLimit(); + + @Desc("Whether this tree may place on the terrain surface, under carvings, or both.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + + @Desc("If true, the tree anchors on the terrain height ignoring the water surface.") + private boolean underwater = false; + + @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") + private IrisObjectTranslate translate = new IrisObjectTranslate(); + + @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") + private IrisStiltSettings stiltSettings; + + @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") + private IrisVacuumSettings vacuumSettings; + + @Required + @Desc("The trunk (log) block, e.g. minecraft:oak_log. Ignored when trunkPalette is set.") + @RegistryListBlockType + private String trunk = "minecraft:oak_log"; + + @Desc("A noise-driven palette for the trunk. When set this overrides the single trunk block, letting the trunk mix blocks by noise.") + private IrisMaterialPalette trunkPalette = null; + + @Required + @Desc("The leaf block, e.g. minecraft:oak_leaves. Ignored when leavesPalette is set.") + @RegistryListBlockType + private String leaves = "minecraft:oak_leaves"; + + @Desc("A noise-driven palette for the leaves. When set this overrides the single leaf block, letting the canopy mix leaf (or other) blocks by noise. Only blocks that are actually leaves get vanilla decay distances.") + private IrisMaterialPalette leavesPalette = null; + + @Desc("The named canopy profile that drives default crown radii and shape.") + private IrisTreeProfile profile = IrisTreeProfile.OAK; + + @MinNumber(1) + @Desc("Minimum trunk height in blocks.") + private int heightMin = 8; + + @MinNumber(1) + @Desc("Maximum trunk height in blocks.") + private int heightMax = 12; + + @MinNumber(1) + @Desc("Base trunk width in blocks. 1 is a single column, 2 is a 2x2 trunk, etc.") + private int trunkWidth = 1; + + @Desc("The function used to shape trunk width over height.") + private IrisTreeFunction trunkShape = IrisTreeFunction.CONSTANT; + + @Desc("Width multiplier at the base for the LINEAR trunk shape.") + private double shapeStart = 1; + + @Desc("Width multiplier at the top for the LINEAR trunk shape.") + private double shapeEnd = 1; + + @Desc("Steepness for the SIGMOID trunk shape.") + private double shapeSteepness = 5; + + @Desc("Base for the LOG trunk shape.") + private double shapeBase = 2.718281828; + + @Desc("Period for the SINE trunk shape.") + private double shapePeriod = 1; + + @Desc("Amplitude for the SINE trunk shape.") + private double shapeAmplitude = 0.2; + + @Desc("Pinch position (0-1) for the PARABOLIC trunk shape.") + private double shapePeakOffset = 0.5; + + @Desc("Minimum width fraction at the waist for the PARABOLIC trunk shape.") + private double shapeFloor = 0.5; + + @Desc("Compass direction in degrees the trunk leans toward.") + private double leanAzimuth = 0; + + @Desc("How far the trunk leans, in degrees from vertical. 0 is perfectly upright.") + private double leanAngle = 0; + + @Desc("How the lean accumulates over height.") + private IrisTreeFunction trunkCurve = IrisTreeFunction.LINEAR; + + @Desc("Steepness for the SIGMOID trunk curve.") + private double curveSteepness = 8; + + @Desc("How the lean azimuth itself changes over height (for spiraling or wandering trunks).") + private IrisTreeAzimuthMode leanAzimuthMode = IrisTreeAzimuthMode.CONSTANT; + + @Desc("Azimuth at the base for the LINEAR azimuth mode.") + private double azimuthStart = 0; + + @Desc("Azimuth at the top for the LINEAR azimuth mode.") + private double azimuthEnd = 0; + + @Desc("Number of full turns for the SPIRAL azimuth mode.") + private double azimuthTurns = 1; + + @Desc("Amplitude for the SINE azimuth mode.") + private double azimuthAmplitude = 90; + + @Desc("Period for the SINE azimuth mode.") + private double azimuthPeriod = 1; + + @Desc("Offset for the SINE azimuth mode.") + private double azimuthOffset = 0; + + @Desc("Scale for the NOISE azimuth mode.") + private double azimuthScale = 1; + + @MinNumber(1) + @Desc("Number of branches per whorl ring for the WHORL branch azimuth mode.") + private int azimuthWhorlCount = 5; + + @Desc("Optional accent leaf block scattered through the canopy (blossoms, shroomlight).") + @RegistryListBlockType + private String secondaryLeaves = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The fraction of leaves replaced by the secondary leaf block(s).") + private double secondaryLeafFraction = 0.35; + + @ArrayType(min = 1, type = IrisTreeSecondaryLeaf.class) + @Desc("Optional weighted set of accent leaf blocks. When set this overrides the single secondaryLeaves block.") + private KList weightedSecondaryLeaves = new KList<>(); + + @Desc("A noise-driven palette for the secondary (accent) leaves. When set this overrides both secondaryLeaves and weightedSecondaryLeaves.") + private IrisMaterialPalette secondaryLeavesPalette = null; + + @Desc("Optional secondary trunk block used over a height band (for color-banded trunks). Ignored when secondaryTrunkPalette is set.") + @RegistryListBlockType + private String secondaryTrunk = null; + + @Desc("A noise-driven palette for the secondary trunk band. When set this overrides the single secondaryTrunk block.") + private IrisMaterialPalette secondaryTrunkPalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The normalized height where the secondary trunk band starts.") + private double secondaryTrunkStart = 0.5; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The normalized height where the secondary trunk band ends.") + private double secondaryTrunkEnd = 1; + + @Desc("If true, a root system extends below (and around) the base so the tree connects to the ground on uneven terrain.") + private boolean roots = true; + + @Desc("How the root system is built when roots is true.") + private IrisTreeRootStyle rootStyle = IrisTreeRootStyle.BUTTRESS; + + @MinNumber(0) + @Desc("Override the root depth/reach in blocks. 0 means auto (scales with tree height).") + private int rootDepth = 0; + + @MinNumber(0) + @Desc("Override the root flare radius in blocks. 0 means auto.") + private double rootFlare = 0; + + @MinNumber(1) + @MaxNumber(6) + @Desc("How many separate trunks the tree splits into above forkHeight. 1 is a single trunk.") + private int trunkForks = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The normalized height where the trunk splits into forks.") + private double forkHeight = 0.5; + + @Desc("The outward lean angle in degrees of each fork.") + private double forkAngle = 25; + + @Desc("The leaf crown configuration.") + private IrisTreeCanopy canopy = new IrisTreeCanopy(); + + @ArrayType(min = 1, type = IrisTreeDecorator.class) + @Desc("Accent decorators applied after the tree is built (fruit, vines, snow, glow).") + private KList decorators = new KList<>(); + + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> { + KList baked = new KList<>(); + int count = Math.max(1, variants); + int lo = Math.min(heightMin, heightMax); + int hi = Math.max(heightMin, heightMax); + RNG heightRng = new RNG(seed); + + for (int i = 0; i < count; i++) { + int height; + if (count == 1 || lo == hi) { + height = heightRng.i(lo, hi + 1); + } else { + double step = (hi - lo) / (double) (count - 1); + double base = lo + step * i; + double jitter = heightRng.d(-step * 0.3, step * 0.3); + height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); + } + + IrisObject object = ProceduralTreeGenerator.generate(this, Math.max(2, height), new RNG(seed + (i * 7919L)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey(getVariantLoadKey(i)); + object.setLoader(data); + baked.add(object); + } + + if (new java.io.File("plugins/Iris/goldendebug.txt").isFile()) { + for (IrisObject object : baked) { + long[] digest = new long[]{0L}; + object.getBlocks().forEach((vector, state) -> { + long position = ((long) vector.getBlockX() << 40) ^ ((long) vector.getBlockY() << 20) ^ vector.getBlockZ(); + digest[0] ^= Long.rotateLeft(position * 0x9E3779B97F4A7C15L ^ state.key().hashCode(), (int) (position & 63)); + }); + IrisLogging.debug("Goldendebug bake: " + object.getLoadKey() + " blocks=" + object.getBlocks().size() + " digest=" + Long.toHexString(digest[0])); + } + } + + return baked; + }); + } + + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + public String getVariantLoadKey(int index) { + if (index < 0) { + throw new IllegalArgumentException("index must not be negative"); + } + return "procedural/tree/" + name + "#" + index; + } + + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(mode); + placement.setRotation(rotation); + placement.setClamp(clamp); + placement.setCarvingSupport(carvingSupport); + placement.setUnderwater(underwater); + placement.setTranslate(translate); + placement.setStiltSettings(stiltSettings); + placement.setVacuumSettings(vacuumSettings); + placement.setChance(chance); + placement.setDensity(density); + return placement; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java new file mode 100644 index 000000000..88dccbd99 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java @@ -0,0 +1,45 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls the compass direction (azimuth) of trunk lean as it rises, or the direction each branch is thrown.") +public enum IrisTreeAzimuthMode { + @Desc("A single fixed azimuth.") + CONSTANT, + @Desc("Azimuth ramps straight from start to end with height.") + LINEAR, + @Desc("Azimuth winds around the trunk a number of turns (corkscrew).") + SPIRAL, + @Desc("Azimuth oscillates with a sine wave.") + SINE, + @Desc("Azimuth wanders using deterministic noise.") + NOISE, + @Desc("Each branch picks a uniformly random azimuth (falls back to constant for trunk lean).") + RANDOM, + @Desc("Phyllotaxis: each successive branch is offset by the 137.5 degree golden angle for the most natural spiral packing (branches).") + GOLDEN_ANGLE, + @Desc("Each successive branch is thrown to the opposite side (180 degrees apart).") + ALTERNATING, + @Desc("Branches are grouped into evenly spaced whorls of azimuthWhorlCount around each ring.") + WHORL, + @Desc("Azimuth zigzags by +/- amplitude on alternating branches.") + ZIGZAG +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java new file mode 100644 index 000000000..6b07b0a10 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java @@ -0,0 +1,47 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how the chance of spawning a branch varies with trunk height (0 at the base, 1 at the top).") +public enum IrisTreeBranchProbability { + @Desc("Same branch chance at every height.") + CONSTANT, + @Desc("Ramps straight from base chance to crown chance.") + LINEAR, + @Desc("S-curve that switches on around a midpoint height.") + SIGMOID, + @Desc("Chance rises with height raised to an exponent, clustering branches near the crown.") + TOP_HEAVY, + @Desc("Bell curve peaking in a height band.") + GAUSSIAN, + @Desc("Irregular organic branching from deterministic noise.") + NOISE, + @Desc("Chance falls with height (1-t)^exponent, clustering branches near the base.") + BOTTOM_HEAVY, + @Desc("Regular whorl rings of branches at evenly spaced heights (periods controls count).") + PERIODIC, + @Desc("Branches only within a height window around mean +/- std.") + BAND, + @Desc("Inverse of GAUSSIAN: branches avoid the mean band and favor base and crown.") + INVERSE_GAUSSIAN, + @Desc("Exponential decay from the base upward (constant * e^-exponent*t).") + EXPONENTIAL_DECAY +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java new file mode 100644 index 000000000..e78f06868 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java @@ -0,0 +1,131 @@ +/* + * 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.procedural.tree; + +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("tree-branches") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A branch system that throws limbs out of the trunk and places a leaf ball at each tip. When present, branches drive the canopy and only the topmost crown disc of the profile is still placed.") +@Data +public class IrisTreeBranches { + @Desc("How branch spawn chance varies over trunk height.") + private IrisTreeBranchProbability probabilityFunction = IrisTreeBranchProbability.TOP_HEAVY; + + @MinNumber(0) + @Desc("Branch chance for the CONSTANT probability function.") + private double probabilityConstant = 0.5; + + @MinNumber(0) + @Desc("Branch chance at the base for the LINEAR probability function.") + private double probabilityBase = 0; + + @MinNumber(0) + @Desc("Branch chance at the crown for the LINEAR probability function.") + private double probabilityCrown = 1; + + @Desc("Steepness for the SIGMOID probability function.") + private double probabilitySteepness = 10; + + @Desc("Midpoint height (0-1) for the SIGMOID probability function.") + private double probabilityMidpoint = 0.7; + + @Desc("Exponent for the TOP_HEAVY probability function.") + private double probabilityExponent = 2; + + @Desc("Mean height (0-1) for the GAUSSIAN probability function.") + private double probabilityMean = 0.7; + + @Desc("Standard deviation for the GAUSSIAN probability function.") + private double probabilityStd = 0.15; + + @Desc("Noise scale for the NOISE probability function.") + private double probabilityScale = 1; + + @MinNumber(0) + @Desc("Number of whorl rings over the trunk height for the PERIODIC probability function.") + private double probabilityPeriods = 5; + + @Desc("How branch length varies over trunk height.") + private IrisTreeFunction lengthFunction = IrisTreeFunction.LINEAR; + + @MinNumber(0) + @Desc("Branch length at the base for the LINEAR length function.") + private double lengthBase = 1; + + @MinNumber(0) + @Desc("Branch length at the crown for the LINEAR length function.") + private double lengthCrown = 4; + + @MinNumber(0) + @Desc("Branch length for the CONSTANT length function.") + private double lengthConstant = 3; + + @MinNumber(0) + @Desc("Maximum branch length for the SIGMOID, LOG and PARABOLIC length functions.") + private double lengthMax = 4; + + @Desc("Steepness for the SIGMOID length function.") + private double lengthSteepness = 5; + + @Desc("How the compass direction of each branch is chosen.") + private IrisTreeAzimuthMode azimuthMode = IrisTreeAzimuthMode.RANDOM; + + @Desc("Fixed azimuth in degrees when azimuthMode is CONSTANT.") + private double azimuth = 0; + + @Desc("Elevation angle in degrees from horizontal. 0 is flat, positive points up, negative droops down.") + private double elevation = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How much each branch sags/droops along its length (catenary). 0 is a straight branch; higher values arc the branch and its tip downward.") + private double sag = 0; + + @MinNumber(0) + @MaxNumber(6) + @Desc("How many recursive levels of sub-branches to grow. 0 is none, 1 is a single level, 2+ produces fractal branching.") + private int branchDepth = 1; + + @Desc("If true, branches are clamped to never droop below horizontal (useful for upright species).") + private boolean leafStartUp = false; + + @MinNumber(0) + @Desc("Leaf ball radius placed at each branch tip.") + private int clusterRadius = 2; + + @Desc("How the branch tip leaf cluster fills.") + private IrisTreeLeafMode clusterMode = IrisTreeLeafMode.TRIMMED; + + @MinNumber(0) + @Desc("Fill density for the branch tip leaf cluster when clusterMode is density or noise.") + private double clusterDensity = 0.85; + + @Desc("Optional one level of recursive sub-branches sprouting from each branch tip.") + private IrisTreeSubBranches subBranches = null; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java new file mode 100644 index 000000000..fb14d2c57 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java @@ -0,0 +1,71 @@ +/* + * 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.procedural.tree; + +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.Snippet; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("tree-canopy") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("The leaf crown of a procedural tree. Built from stacked dome-shaped discs (driven by the profile or by explicit layers) and optionally a branch system.") +@Data +public class IrisTreeCanopy { + @MinNumber(0) + @MaxNumber(180) + @Desc("Elevation angle in degrees from vertical for each leaf dome. 90 is a flat disc, below 90 domes downward into a sphere, above 90 flares outward into an umbrella.") + private double startAngle = 90; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Vertical scale of the canopy volume. Lower values flatten the crown.") + private double squish = 1; + + @Desc("How leaves fill each canopy disc.") + private IrisTreeLeafMode mode = IrisTreeLeafMode.TRIMMED; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Fill probability used by the density and noise leaf modes.") + private double leafDensity = 0.85; + + @MinNumber(0.1) + @Desc("Horizontal X stretch of the crown for elliptical or wind-blown shapes. 1 is circular.") + private double crownStretchX = 1; + + @MinNumber(0.1) + @Desc("Horizontal Z stretch of the crown for elliptical or wind-blown shapes. 1 is circular.") + private double crownStretchZ = 1; + + @ArrayType(min = 1, type = IrisTreeLayer.class) + @Desc("Optional explicit crown discs. When provided these replace the profile-driven layers and let you sculpt the silhouette by hand.") + private KList layers = new KList<>(); + + @Desc("Optional branch system. When present, branches build most of the canopy and only the topmost profile disc is still placed as a crown.") + private IrisTreeBranches branches = null; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java new file mode 100644 index 000000000..78fbe258e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java @@ -0,0 +1,62 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +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.Required; +import art.arcane.iris.engine.object.annotations.Snippet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("tree-decorator") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("An accent block applied to a generated tree such as fruit on branch tips, vines on the trunk, snow on the crown, or a glowing underside.") +@Data +public class IrisTreeDecorator { + @Desc("Where this decorator is placed on the tree.") + private IrisTreeDecoratorTarget target = IrisTreeDecoratorTarget.BRANCH_TIP; + + @Required + @Desc("The block id to place, e.g. minecraft:magma_block. Ignored when palette is set.") + @RegistryListBlockType + private String block = ""; + + @Desc("A noise-driven palette for this decorator. When set this overrides the single block.") + private IrisMaterialPalette palette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance per candidate position for this decorator to place.") + private double chance = 0.5; + + @MinNumber(1) + @Desc("Maximum strand length downward for the CANOPY_HANG target (random 1..length per column).") + private int length = 1; + + @Desc("If true the block's facing is oriented away from the trunk (for trunk-mounted fences/gates/banners).") + private boolean axisAware = false; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java new file mode 100644 index 000000000..734d89150 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java @@ -0,0 +1,45 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Where a tree decorator block is placed.") +public enum IrisTreeDecoratorTarget { + @Desc("At the tip of each generated branch (vines, fruit, lanterns).") + BRANCH_TIP, + @Desc("On air-facing sides of trunk and branch blocks (vines, moss).") + TRUNK_SURFACE, + @Desc("On top of the highest block in each column (snow, sculk).") + CANOPY_TOP, + @Desc("One block below the lowest leaf in each column (glowing underside).") + CANOPY_BOTTOM, + @Desc("Around the y=0 ring at the base of the trunk (roots, mushrooms).") + TRUNK_BASE, + @Desc("On air-facing sides of leaf blocks (berries, lights nestled in the foliage).") + LEAF_SURFACE, + @Desc("Hanging strands of up to 'length' blocks below the lowest leaf in each column (vines, icicles).") + CANOPY_HANG, + @Desc("On the top face of trunk and branch blocks (moss, snow on limbs).") + BRANCH_SURFACE, + @Desc("One block above the very top of the trunk (nest, beehive, beacon).") + TRUNK_TOP, + @Desc("Scattered across the ground footprint around the base, wider than the trunk-base ring.") + GROUND_SCATTER +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java new file mode 100644 index 000000000..5bbf1efed --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java @@ -0,0 +1,47 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("A shaping function evaluated over normalized height (0 at the base, 1 at the top). Used for trunk width, trunk curve and branch length.") +public enum IrisTreeFunction { + @Desc("Same value at every height.") + CONSTANT, + @Desc("Ramps straight from start to end.") + LINEAR, + @Desc("S-curve transition controlled by steepness.") + SIGMOID, + @Desc("Logarithmic falloff controlled by base.") + LOG, + @Desc("Sine ripple controlled by period and amplitude.") + SINE, + @Desc("Parabolic pinch, narrowest at peakOffset.") + PARABOLIC, + @Desc("Geometric (exponential) interpolation from start to end.") + EXPONENTIAL, + @Desc("Square-root ease: fast change low, slow high.") + SQRT, + @Desc("Hard step that jumps from start to end at the threshold (peakOffset).") + STEP, + @Desc("Bell bulge peaking in the middle of the height range.") + BELL, + @Desc("Smoothstep ease-in-out (3t^2 - 2t^3).") + EASE_IN_OUT +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java new file mode 100644 index 000000000..526d437e3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java @@ -0,0 +1,42 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.Snippet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("tree-layer") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("An explicit canopy disc at a given vertical offset and radius. Define a list of these to bypass the profile and sculpt the crown by hand.") +@Data +public class IrisTreeLayer { + @Desc("The vertical offset of this disc, measured in blocks above the trunk base.") + private int yOffset = 0; + + @MinNumber(0.5) + @Desc("The radius of this leaf disc in blocks.") + private double radius = 2; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java new file mode 100644 index 000000000..3801e148f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java @@ -0,0 +1,43 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How leaves fill a disc or cluster.") +public enum IrisTreeLeafMode { + @Desc("Corner-trimmed disc/sphere for a rounded silhouette.") + TRIMMED, + @Desc("Completely filled disc/sphere.") + FILLED, + @Desc("Seeded probabilistic falloff toward the edge controlled by leafDensity.") + DENSITY, + @Desc("Seeded value-noise mask controlled by leafDensity.") + NOISE, + @Desc("Only the outer shell is placed, leaving the interior hollow.") + HOLLOW, + @Desc("Quadratic radial gradient: dense at the center, thinning sharply toward the edge.") + GRADIENT, + @Desc("Coarse low-frequency noise that forms clumps and gaps of foliage.") + CLUMPED, + @Desc("Trimmed with heavy random erosion of the outer ring for a ragged, weathered look.") + TATTERED, + @Desc("Very thin scattering of leaves across the volume.") + SPARSE +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java new file mode 100644 index 000000000..060e506ed --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java @@ -0,0 +1,30 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Sapling override object picking options") +public enum IrisTreeModes { + @Desc("Check biome, then region, pick the first one that has options. Dimension placements are not consulted.") + FIRST, + + @Desc("Check biome, regions, and dimensions, and pick any option from the total list") + ALL +} \ No newline at end of file diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java new file mode 100644 index 000000000..e5fca1397 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java @@ -0,0 +1,53 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Named canopy presets that drive default layer radii and shape, scaled to the tree height.") +public enum IrisTreeProfile { + @Desc("Rounded broadleaf crown.") + OAK, + @Desc("Slim upright broadleaf crown.") + BIRCH, + @Desc("Narrow conifer cone.") + SPRUCE, + @Desc("Tall thin crown concentrated near the very top.") + JUNGLE, + @Desc("Flat shallow umbrella crown.") + ACACIA, + @Desc("Dense rounded broadleaf crown.") + DARK_OAK, + @Desc("Flat wide umbrella crown compressed into the top quarter (vanilla dark oak look).") + DARK_OAK_FLAT, + @Desc("Extra wide flat umbrella that overlaps into a continuous roofed canopy.") + DARK_OAK_FLAT_WIDE, + @Desc("Broad rounded blossom crown.") + CHERRY, + @Desc("Bare trunk with a small tuft of fronds only at the very top.") + PALM, + @Desc("Broad crown with wide drooping radii, ideal with a low startAngle to make a weeping skirt.") + WILLOW, + @Desc("Very narrow tall crown hugging the trunk (cypress / lombardy poplar).") + COLUMNAR, + @Desc("Squat, wide, low crown for shrubs and saplings.") + BUSH, + @Desc("Giant conifer cone for 2x2 mega spruce trunks.") + MEGA_SPRUCE +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java new file mode 100644 index 000000000..d8b80e7b9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java @@ -0,0 +1,31 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How a procedural tree's root system is built below (and around) the trunk base.") +public enum IrisTreeRootStyle { + @Desc("A single tapering taproot straight down from the base.") + TAPROOT, + @Desc("A taproot plus a ring of flared buttress legs that splay outward as they descend (default).") + BUTTRESS, + @Desc("Visible above-ground prop roots that arch out and down from the lower trunk to the ground (mangrove style).") + STILT +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java new file mode 100644 index 000000000..160b9d48f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java @@ -0,0 +1,46 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListBlockType; +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("tree-secondary-leaf") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A weighted accent leaf or foliage block scattered through the canopy (blossoms, shroomlight, berries).") +@Data +public class IrisTreeSecondaryLeaf { + @Required + @Desc("The block id to scatter, e.g. minecraft:shroomlight") + @RegistryListBlockType + private String block = ""; + + @MinNumber(0) + @Desc("The relative weight of this block among the secondary leaves.") + private int weight = 1; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java new file mode 100644 index 000000000..4a88bbf4c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java @@ -0,0 +1,45 @@ +/* + * 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.procedural.tree; + +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.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("tree-settings") +@Accessors(chain = true) +@AllArgsConstructor +@NoArgsConstructor +@Desc("Tree growth override settings") +@Data +@EqualsAndHashCode(callSuper = false) +public class IrisTreeSettings { + + @Required + @Desc("Turn replacing on and off") + boolean enabled = false; + + @Desc("Object picking modes") + IrisTreeModes mode = IrisTreeModes.FIRST; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java new file mode 100644 index 000000000..a6a591dd2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java @@ -0,0 +1,66 @@ +/* + * 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.procedural.tree; + +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("tree-sub-branches") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("One recursive level of sub-branches sprouting from each primary branch tip.") +@Data +public class IrisTreeSubBranches { + @MinNumber(1) + @Desc("How many sub-branches sprout from each primary branch tip.") + private int count = 1; + + @Desc("Pitch deflection in degrees applied to each sub-branch relative to its parent. Positive bends up, negative droops down. Cumulative pitch past 90 makes sub-branches point downward.") + private double pitchDelta = 0; + + @Desc("Yaw (horizontal) spread in degrees fanned between sub-branches.") + private double yawDelta = 45; + + @MinNumber(0) + @Desc("Sub-branch length as a fraction of its parent branch length.") + private double lengthScale = 0.5; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How much each sub-branch sags/droops along its length (catenary).") + private double sag = 0; + + @MinNumber(0) + @Desc("Leaf ball radius placed at each sub-branch tip.") + private int clusterRadius = 1; + + @Desc("How the sub-branch tip leaf cluster fills.") + private IrisTreeLeafMode clusterMode = IrisTreeLeafMode.TRIMMED; + + @MinNumber(0) + @Desc("Fill density for the sub-branch leaf cluster when clusterMode is density or noise.") + private double clusterDensity = 0.85; +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java new file mode 100644 index 000000000..2ff68a5a0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -0,0 +1,126 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public final class ProceduralTreeGenerator { + private ProceduralTreeGenerator() { + } + + public static IrisObject generate(IrisProceduralTree tree, int height, RNG rng, IrisData data) { + TreeBlockCanvas canvas = new TreeBlockCanvas(); + long baseSeed = rng.getSeed(); + + List limbs = TreeTrunkBuilder.build(canvas, tree, height); + + boolean wantEndpoints = tree.getDecorators() != null && !tree.getDecorators().isEmpty(); + List branchEndpoints = wantEndpoints ? new ArrayList<>() : null; + + int limbIndex = 0; + for (TreeTrunkBuilder.Limb limb : limbs) { + TreeCanopyBuilder.build(canvas, tree, height, limb.offsets(), limb.branchStartY(), baseSeed + limbIndex * 131L, branchEndpoints); + limbIndex++; + } + + if (wantEndpoints) { + TreeDecoratorApplier.apply(canvas, tree, baseSeed, branchEndpoints); + } + + if (tree.isRoots()) { + TreeRootBuilder.build(canvas, tree, height, baseSeed); + } + + if (tree.isPlausible()) { + TreeSupport.ensureLeavesSupported(canvas, 24); + } + + Map resolved = new HashMap<>(); + Set trunkPositions = new HashSet<>(); + Set leafPositions = new HashSet<>(); + for (Map.Entry entry : canvas.getCells().entrySet()) { + TreeBlockCanvas.Cell cell = entry.getValue(); + PlatformBlockState state = TreeBlockResolver.resolve(tree, data, cell, entry.getKey()); + if (state == null) { + continue; + } + resolved.put(entry.getKey(), state); + if (cell.role() == TreeBlockCanvas.Role.TRUNK || cell.role() == TreeBlockCanvas.Role.SECONDARY_TRUNK) { + trunkPositions.add(entry.getKey()); + } else if (cell.role() == TreeBlockCanvas.Role.LEAF || cell.role() == TreeBlockCanvas.Role.SECONDARY_LEAF) { + leafPositions.add(entry.getKey()); + } + } + + TreePlausibility.apply(resolved, trunkPositions, leafPositions, tree); + + return assemble(resolved); + } + + private static IrisObject assemble(Map resolved) { + if (resolved.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 (TreeBlockCanvas.Vec v : resolved.keySet()) { + minX = Math.min(minX, v.x()); + minY = Math.min(minY, v.y()); + minZ = Math.min(minZ, v.z()); + maxX = Math.max(maxX, v.x()); + maxY = Math.max(maxY, v.y()); + maxZ = Math.max(maxZ, v.z()); + } + + int w = maxX - minX + 1; + int h = maxY - minY + 1; + int d = maxZ - minZ + 1; + int cx = w / 2; + int cy = h / 2; + int cz = d / 2; + + IrisObject object = new IrisObject(w, h, d); + for (Map.Entry entry : resolved.entrySet()) { + TreeBlockCanvas.Vec v = entry.getKey(); + int nx = v.x() - minX - cx; + int ny = v.y() - cy + 1; + int nz = v.z() - minZ - cz; + object.getBlocks().put(new IrisBlockVector(nx, ny, nz), entry.getValue()); + } + + return object; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java new file mode 100644 index 000000000..ad0261b81 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java @@ -0,0 +1,102 @@ +/* + * 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.procedural.tree; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class TreeBlockCanvas { + public record Vec(int x, int y, int z) { + } + + public enum Role { + TRUNK, SECONDARY_TRUNK, LEAF, SECONDARY_LEAF, DECORATOR + } + + public enum Axis { + NONE, X, Y, Z + } + + public record Cell(Role role, Axis axis, boolean exposed, int decoratorIndex, String facing) { + } + + private final Map cells = new HashMap<>(); + private final Set trunk = new HashSet<>(); + private final Set leaf = new HashSet<>(); + + public boolean has(int x, int y, int z) { + return cells.containsKey(new Vec(x, y, z)); + } + + public Cell get(int x, int y, int z) { + return cells.get(new Vec(x, y, z)); + } + + public void setTrunk(int x, int y, int z, Role role, Axis axis) { + Vec v = new Vec(x, y, z); + cells.put(v, new Cell(role, axis, false, -1, null)); + trunk.add(v); + leaf.remove(v); + } + + public boolean setLeaf(int x, int y, int z, Role role) { + Vec v = new Vec(x, y, z); + if (cells.containsKey(v)) { + return false; + } + cells.put(v, new Cell(role, Axis.NONE, false, -1, null)); + leaf.add(v); + return true; + } + + public boolean setDecor(int x, int y, int z, int decoratorIndex, String facing) { + Vec v = new Vec(x, y, z); + if (cells.containsKey(v)) { + return false; + } + cells.put(v, new Cell(Role.DECORATOR, Axis.NONE, false, decoratorIndex, facing)); + return true; + } + + public void markExposed(int x, int y, int z) { + Vec v = new Vec(x, y, z); + Cell c = cells.get(v); + if (c != null && !c.exposed()) { + cells.put(v, new Cell(c.role(), c.axis(), true, c.decoratorIndex(), c.facing())); + } + } + + public Map getCells() { + return cells; + } + + public Set getTrunk() { + return trunk; + } + + public Set getLeaf() { + return leaf; + } + + public boolean isEmpty() { + return cells.isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java new file mode 100644 index 000000000..feb18b5a1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java @@ -0,0 +1,170 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeDecorator; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.math.RNG; + +public final class TreeBlockResolver { + private TreeBlockResolver() { + } + + public static PlatformBlockState resolve(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Cell cell, TreeBlockCanvas.Vec pos) { + RNG paletteRng = new RNG(tree.getSeed()); + RNG posRng = new RNG(tree.getSeed() ^ positionHash(pos)); + + switch (cell.role()) { + case TRUNK -> { + PlatformBlockState state = resolveBlock(tree.getTrunk(), tree.getTrunkPalette(), data, pos, paletteRng); + return finishTrunk(state, cell); + } + case SECONDARY_TRUNK -> { + PlatformBlockState state = resolveBlock(tree.getSecondaryTrunk(), tree.getSecondaryTrunkPalette(), data, pos, paletteRng); + if (state == null) { + state = resolveBlock(tree.getTrunk(), tree.getTrunkPalette(), data, pos, paletteRng); + } + return finishTrunk(state, cell); + } + case LEAF -> { + return resolveBlock(tree.getLeaves(), tree.getLeavesPalette(), data, pos, paletteRng); + } + case SECONDARY_LEAF -> { + PlatformBlockState state = resolveSecondaryLeaf(tree, data, pos, paletteRng, posRng); + if (state == null) { + state = resolveBlock(tree.getLeaves(), tree.getLeavesPalette(), data, pos, paletteRng); + } + return state; + } + case DECORATOR -> { + int index = cell.decoratorIndex(); + if (index < 0 || tree.getDecorators() == null || index >= tree.getDecorators().size()) { + return null; + } + IrisTreeDecorator dec = tree.getDecorators().get(index); + PlatformBlockState state = resolveBlock(dec.getBlock(), dec.getPalette(), data, pos, paletteRng); + if (state != null && cell.facing() != null && IrisProceduralBlocks.hasProperty(state, "facing")) { + try { + state = state.withProperty("facing", cell.facing().toLowerCase()); + } catch (IllegalArgumentException ignored) { + } + } + return state; + } + default -> { + return null; + } + } + } + + private static PlatformBlockState finishTrunk(PlatformBlockState state, TreeBlockCanvas.Cell cell) { + if (state == null) { + return null; + } + if (cell.axis() != TreeBlockCanvas.Axis.NONE && IrisProceduralBlocks.hasProperty(state, "axis")) { + try { + state = state.withProperty("axis", cell.axis().name().toLowerCase()); + } catch (IllegalArgumentException ignored) { + } + } + if (cell.exposed()) { + return woodCap(state); + } + return state; + } + + private static PlatformBlockState resolveSecondaryLeaf(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng, RNG posRng) { + if (TreeTrunkBuilder.paletteSet(tree.getSecondaryLeavesPalette())) { + return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), data); + } + if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) { + String picked = pickWeighted(tree, posRng); + return picked == null ? null : B.getStateOrNull(picked, false); + } + if (tree.getSecondaryLeaves() != null && !tree.getSecondaryLeaves().isEmpty()) { + return B.getStateOrNull(tree.getSecondaryLeaves(), false); + } + return null; + } + + private static String pickWeighted(IrisProceduralTree tree, RNG rng) { + int total = 0; + for (art.arcane.iris.engine.object.procedural.tree.IrisTreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { + total += Math.max(0, s.getWeight()); + } + if (total <= 0) { + return null; + } + double r = rng.nextDouble() * total; + double cumulative = 0; + for (art.arcane.iris.engine.object.procedural.tree.IrisTreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { + cumulative += Math.max(0, s.getWeight()); + if (r < cumulative) { + return s.getBlock(); + } + } + return tree.getWeightedSecondaryLeaves().get(tree.getWeightedSecondaryLeaves().size() - 1).getBlock(); + } + + private static PlatformBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { + if (TreeTrunkBuilder.paletteSet(palette)) { + return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), data); + } + if (block != null && !block.isEmpty()) { + return B.getStateOrNull(block, false); + } + return null; + } + + private static PlatformBlockState woodCap(PlatformBlockState state) { + String key = state.key(); + int bracket = key.indexOf('['); + String base = bracket < 0 ? key : key.substring(0, bracket); + String woodKey = null; + if (base.endsWith("_log")) { + woodKey = base.substring(0, base.length() - 4) + "_wood"; + } else if (base.endsWith("_stem")) { + woodKey = base.substring(0, base.length() - 5) + "_hyphae"; + } + if (woodKey == null) { + return state; + } + PlatformBlockState wood = B.getStateOrNull(woodKey, false); + if (wood == null) { + return state; + } + String axis = IrisProceduralBlocks.propertyValue(state, "axis"); + if (axis != null && IrisProceduralBlocks.hasProperty(wood, "axis")) { + try { + wood = wood.withProperty("axis", axis); + } catch (IllegalArgumentException ignored) { + } + } + return wood; + } + + private static long positionHash(TreeBlockCanvas.Vec pos) { + return pos.x() * 73856093L ^ pos.y() * 19349663L ^ pos.z() * 83492791L; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java new file mode 100644 index 000000000..7721e22d0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java @@ -0,0 +1,351 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeBranches; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeCanopy; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeLayer; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeLeafMode; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeProfile; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeSubBranches; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +import java.util.List; + +public final class TreeCanopyBuilder { + private TreeCanopyBuilder() { + } + + public static void build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, double[][] offsets, + int branchStartY, long baseSeed, List branchEndpoints) { + IrisTreeCanopy canopy = tree.getCanopy(); + if (canopy == null) { + canopy = new IrisTreeCanopy(); + } + IrisTreeBranches branches = canopy.getBranches(); + + double[][] layers = resolveLayers(canopy, tree.getProfile(), height, branches != null); + + if (branches != null) { + if (layers.length > 0) { + double[][] crown = new double[][]{layers[layers.length - 1]}; + volumeCanopy(canvas, tree, crown, canopy, baseSeed, offsets); + } + placeApexCap(canvas, tree, height, layers, offsets, baseSeed); + branchCanopy(canvas, tree, height, branches, branchStartY, baseSeed, offsets, branchEndpoints); + } else { + volumeCanopy(canvas, tree, layers, canopy, baseSeed, offsets); + } + } + + private static void placeApexCap(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, double[][] layers, + double[][] offsets, long baseSeed) { + int ocx = 0; + int ocz = 0; + if (offsets != null && offsets.length > 0) { + ocx = (int) Math.round(offsets[offsets.length - 1][0]); + ocz = (int) Math.round(offsets[offsets.length - 1][1]); + } + double maxR = 2; + for (double[] layer : layers) { + maxR = Math.max(maxR, layer[1]); + } + int capRadius = Math.max(2, Math.min(3, (int) Math.round(maxR * 0.35))); + IrisTreeCanopy canopy = tree.getCanopy(); + IrisTreeLeafMode mode = canopy != null ? canopy.getMode() : IrisTreeLeafMode.TRIMMED; + double density = canopy != null ? canopy.getLeafDensity() : 1.0; + placeLeafCluster(canvas, tree, ocx, height - 1, ocz, capRadius, mode, density, baseSeed + 5555L); + } + + private static double[][] resolveLayers(IrisTreeCanopy canopy, IrisTreeProfile profile, int height, boolean branchDriven) { + KList explicit = canopy.getLayers(); + if (explicit != null && !explicit.isEmpty()) { + double[][] out = new double[explicit.size()][2]; + for (int i = 0; i < explicit.size(); i++) { + out[i][0] = explicit.get(i).getYOffset(); + out[i][1] = explicit.get(i).getRadius(); + } + return out; + } + return TreeProfiles.presetLayers(profile, height, branchDriven); + } + + private static void volumeCanopy(TreeBlockCanvas canvas, IrisProceduralTree tree, double[][] layers, + IrisTreeCanopy canopy, long baseSeed, double[][] offsets) { + int ocx = 0; + int ocz = 0; + if (offsets != null && offsets.length > 0) { + ocx = (int) Math.round(offsets[offsets.length - 1][0]); + ocz = (int) Math.round(offsets[offsets.length - 1][1]); + } + + double startAngle = canopy.getStartAngle(); + double squish = canopy.getSquish(); + IrisTreeLeafMode mode = canopy.getMode(); + double leafDensity = canopy.getLeafDensity(); + + for (double[] layer : layers) { + int yCenter = (int) Math.round(layer[0]); + double radius = layer[1]; + int halfH = layerHalfHeight(radius, startAngle, squish); + int downH = startAngle < 90.0 + ? (int) Math.ceil(radius * Math.cos(Math.toRadians(startAngle)) * squish) + : 0; + int skirt = downH; + + for (int y = yCenter - skirt; y <= yCenter + halfH; y++) { + int dy = y - yCenter; + double layerR; + if (halfH > 0 && dy >= 0) { + layerR = radius * Math.sqrt(Math.max(0.0, 1.0 - Math.pow(dy / (double) halfH, 2))); + } else if (skirt > 0 && dy < 0) { + layerR = radius * Math.sqrt(Math.max(0.0, 1.0 - Math.pow(dy / (double) skirt, 2))); + } else { + layerR = radius; + } + if (layerR < 0.5) { + continue; + } + placeLeafDisc(canvas, tree, ocx, y, ocz, layerR, mode, leafDensity, baseSeed + y); + } + } + } + + private static int layerHalfHeight(double radius, double startAngle, double squish) { + if (startAngle >= 180.0) { + return 0; + } + return (int) Math.ceil(radius * squish); + } + + private static void placeLeafDisc(TreeBlockCanvas canvas, IrisProceduralTree tree, int cx, int cy, int cz, + double radius, IrisTreeLeafMode mode, double density, long seed) { + double sx = stretchX(tree); + double sz = stretchZ(tree); + RNG rng = new RNG(seed); + int irx = (int) Math.ceil(radius * sx); + int irz = (int) Math.ceil(radius * sz); + for (int dx = -irx; dx <= irx; dx++) { + for (int dz = -irz; dz <= irz; dz++) { + double ddx = dx / sx; + double ddz = dz / sz; + double dist = Math.sqrt(ddx * ddx + ddz * ddz); + boolean corner = Math.abs(dx) == irx && Math.abs(dz) == irz; + if (!passesLeafTest(mode, dist, radius, density, rng, cx + dx, cy, cz + dz, seed, corner)) { + continue; + } + canvas.setLeaf(cx + dx, cy, cz + dz, resolveLeaf(tree, rng)); + } + } + } + + private static void placeLeafCluster(TreeBlockCanvas canvas, IrisProceduralTree tree, int cx, int cy, int cz, + int radius, IrisTreeLeafMode mode, double density, long seed) { + double sx = stretchX(tree); + double sz = stretchZ(tree); + RNG rng = new RNG(seed); + int irx = (int) Math.ceil(radius * sx); + int irz = (int) Math.ceil(radius * sz); + for (int dx = -irx; dx <= irx; dx++) { + for (int dy = -radius; dy <= radius; dy++) { + for (int dz = -irz; dz <= irz; dz++) { + double ddx = dx / sx; + double ddz = dz / sz; + double dist = Math.sqrt(ddx * ddx + dy * dy + ddz * ddz); + boolean corner = Math.abs(dx) == irx && Math.abs(dz) == irz; + if (!passesLeafTest(mode, dist, radius, density, rng, cx + dx, cy + dy, cz + dz, seed, corner)) { + continue; + } + canvas.setLeaf(cx + dx, cy + dy, cz + dz, resolveLeaf(tree, rng)); + } + } + } + } + + private static double stretchX(IrisProceduralTree tree) { + IrisTreeCanopy c = tree.getCanopy(); + return c == null ? 1.0 : Math.max(0.1, c.getCrownStretchX()); + } + + private static double stretchZ(IrisProceduralTree tree) { + IrisTreeCanopy c = tree.getCanopy(); + return c == null ? 1.0 : Math.max(0.1, c.getCrownStretchZ()); + } + + private static boolean passesLeafTest(IrisTreeLeafMode mode, double dist, double radius, double density, + RNG rng, int wx, int wy, int wz, long seed, boolean corner) { + switch (mode) { + case TRIMMED -> { + return !(dist > radius || corner); + } + case FILLED -> { + return dist <= radius; + } + case DENSITY -> { + if (dist > radius) { + return false; + } + return rng.nextDouble() <= density * (1.0 - (dist / (radius + 1.0))); + } + case NOISE -> { + if (dist > radius) { + return false; + } + return TreeFunctions.valueNoise3D(wx, wy, wz, seed) <= density; + } + case HOLLOW -> { + return dist <= radius && dist > radius - 1.0; + } + case GRADIENT -> { + if (dist > radius) { + return false; + } + return rng.nextDouble() <= density * Math.pow(1.0 - (dist / (radius + 1.0)), 2); + } + case CLUMPED -> { + if (dist > radius) { + return false; + } + return TreeFunctions.valueNoise3D(Math.floorDiv(wx, 2), Math.floorDiv(wy, 2), Math.floorDiv(wz, 2), seed) <= density; + } + case TATTERED -> { + if (dist > radius || corner) { + return false; + } + return !(dist > radius - 1.5 && rng.nextDouble() < 0.6); + } + case SPARSE -> { + if (dist > radius) { + return false; + } + return rng.nextDouble() <= density * 0.4; + } + default -> { + return dist <= radius; + } + } + } + + private static TreeBlockCanvas.Role resolveLeaf(IrisProceduralTree tree, RNG rng) { + boolean hasSecondary = TreeTrunkBuilder.paletteSet(tree.getSecondaryLeavesPalette()) + || (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) + || (tree.getSecondaryLeaves() != null && !tree.getSecondaryLeaves().isEmpty()); + if (!hasSecondary || tree.getSecondaryLeafFraction() <= 0.0) { + return TreeBlockCanvas.Role.LEAF; + } + if (rng.nextDouble() >= tree.getSecondaryLeafFraction()) { + return TreeBlockCanvas.Role.LEAF; + } + return TreeBlockCanvas.Role.SECONDARY_LEAF; + } + + private static void branchCanopy(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, + IrisTreeBranches branches, int branchStartY, long baseSeed, double[][] offsets, + List branchEndpoints) { + long branchSeed = baseSeed + 9999; + RNG branchRng = new RNG(branchSeed); + IrisTreeSubBranches sub = branches.getSubBranches(); + int depth = branches.getBranchDepth(); + int branchIndex = 0; + + for (int y = Math.max(0, branchStartY); y < height; y++) { + double t = y / (double) Math.max(height - 1, 1); + double p = TreeFunctions.branchProbability(branches, t, branchSeed); + if (branchRng.nextDouble() > p) { + continue; + } + + int ox = 0; + int oz = 0; + if (offsets != null && y < offsets.length) { + ox = (int) Math.round(offsets[y][0]); + oz = (int) Math.round(offsets[y][1]); + } + + double az = TreeFunctions.azimuthDegrees(branches.getAzimuthMode(), t, branchIndex, tree, branches.getAzimuth(), branchRng); + branchIndex++; + double branchLen = TreeFunctions.branchLength(branches, t); + double effElevation = branches.isLeafStartUp() ? Math.max(0.0, branches.getElevation()) : branches.getElevation(); + int[] end = branchEndpoint(ox, y, oz, az, effElevation, branchLen); + int[] tip = rasterizeBranch(canvas, ox, y, oz, end[0], end[1], end[2], branches.getSag()); + + if (branchEndpoints != null) { + branchEndpoints.add(new int[]{tip[0], tip[1], tip[2], ox, oz}); + } + placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], branches.getClusterRadius(), + branches.getClusterMode(), branches.getClusterDensity(), branchSeed + y); + + growSubBranches(canvas, tree, tip[0], tip[1], tip[2], az, effElevation, branchLen, sub, depth, branchSeed + y + 1000L); + } + } + + private static void growSubBranches(TreeBlockCanvas canvas, IrisProceduralTree tree, int ox, int oy, int oz, + double az, double el, double len, IrisTreeSubBranches sub, int depth, long seed) { + if (sub == null || depth <= 0) { + return; + } + int count = Math.max(1, sub.getCount()); + for (int si = 0; si < count; si++) { + double yawOffset = sub.getYawDelta() * (si - (count - 1) / 2.0); + double subAz = az + yawOffset; + double subEl = el + sub.getPitchDelta(); + double subLen = len * sub.getLengthScale(); + int[] end = branchEndpoint(ox, oy, oz, subAz, subEl, subLen); + int[] tip = rasterizeBranch(canvas, ox, oy, oz, end[0], end[1], end[2], sub.getSag()); + placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], sub.getClusterRadius(), + sub.getClusterMode(), sub.getClusterDensity(), seed + si * 131L); + growSubBranches(canvas, tree, tip[0], tip[1], tip[2], subAz, subEl, subLen, sub, depth - 1, seed + si * 131L + 17L); + } + } + + private static int[] branchEndpoint(int ox, int oy, int oz, double azimuthDeg, double elevationDeg, double length) { + double azRad = Math.toRadians(azimuthDeg); + double elRad = Math.toRadians(elevationDeg); + double dx = length * Math.cos(elRad) * Math.sin(azRad); + double dy = length * Math.sin(elRad); + double dz = length * Math.cos(elRad) * Math.cos(azRad); + return new int[]{ox + (int) Math.round(dx), oy + (int) Math.round(dy), oz + (int) Math.round(dz)}; + } + + private static int[] rasterizeBranch(TreeBlockCanvas canvas, int ox, int oy, int oz, int ex, int ey, int ez, double sag) { + int dx = ex - ox; + int dy = ey - oy; + int dz = ez - oz; + double horizontal = Math.sqrt(dx * dx + dz * dz); + double sagBlocks = sag * horizontal; + int steps = Math.max(Math.max(Math.abs(dx), Math.abs(dz)), + Math.max((int) (Math.abs(dy) + Math.ceil(sagBlocks)), 1)); + TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(dx, dy, dz); + + int[] tip = new int[]{ox, oy, oz}; + for (int i = 0; i <= steps; i++) { + double t = i / (double) steps; + int x = (int) Math.round(ox + dx * t); + int y = (int) Math.round(oy + dy * t - sagBlocks * t * t); + int z = (int) Math.round(oz + dz * t); + if (!canvas.has(x, y, z)) { + canvas.setTrunk(x, y, z, TreeBlockCanvas.Role.TRUNK, axis); + } + tip = new int[]{x, y, z}; + } + return tip; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java new file mode 100644 index 000000000..15da8c5a9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java @@ -0,0 +1,280 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeDecorator; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.math.RNG; + +import java.util.List; +import java.util.Map; + +public final class TreeDecoratorApplier { + private TreeDecoratorApplier() { + } + + public static void apply(TreeBlockCanvas canvas, IrisProceduralTree tree, long baseSeed, List branchEndpoints) { + KList decorators = tree.getDecorators(); + if (decorators == null || decorators.isEmpty()) { + return; + } + RNG rng = new RNG(baseSeed + 77777L); + + for (int idx = 0; idx < decorators.size(); idx++) { + IrisTreeDecorator dec = decorators.get(idx); + boolean hasBlock = (dec.getBlock() != null && !dec.getBlock().isEmpty()) || TreeTrunkBuilder.paletteSet(dec.getPalette()); + if (!hasBlock) { + continue; + } + switch (dec.getTarget()) { + case BRANCH_TIP -> branchTip(canvas, dec, idx, branchEndpoints, rng); + case TRUNK_SURFACE -> trunkSurface(canvas, dec, idx, rng); + case CANOPY_TOP -> canopyTop(canvas, dec, idx, rng); + case CANOPY_BOTTOM -> canopyBottom(canvas, dec, idx, rng); + case TRUNK_BASE -> trunkBase(canvas, dec, idx, rng); + case LEAF_SURFACE -> leafSurface(canvas, dec, idx, rng); + case CANOPY_HANG -> canopyHang(canvas, dec, idx, rng); + case BRANCH_SURFACE -> branchSurface(canvas, dec, idx, rng); + case TRUNK_TOP -> trunkTop(canvas, dec, idx, rng); + case GROUND_SCATTER -> groundScatter(canvas, dec, idx, rng); + } + } + } + + private static void branchTip(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, List branchEndpoints, RNG rng) { + if (branchEndpoints == null) { + return; + } + for (int[] e : branchEndpoints) { + if (rng.nextDouble() > dec.getChance()) { + continue; + } + if (canvas.has(e[0], e[1], e[2])) { + continue; + } + String facing = dec.isAxisAware() ? facingAway(e[3], e[4], e[0], e[2]) : null; + canvas.setDecor(e[0], e[1], e[2], idx, facing); + } + } + + private static void trunkSurface(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + String[] facings = {"west", "east", "north", "south"}; + for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { + for (int i = 0; i < sides.length; i++) { + int nx = v.x() + sides[i][0]; + int nz = v.z() + sides[i][1]; + if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(nx, v.y(), nz, idx, dec.isAxisAware() ? facings[i] : null); + } + } + } + + private static void leafSurface(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; + String[] facings = {"west", "east", "north", "south"}; + for (TreeBlockCanvas.Vec v : new KList<>(canvas.getLeaf())) { + for (int i = 0; i < sides.length; i++) { + int nx = v.x() + sides[i][0]; + int nz = v.z() + sides[i][1]; + if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(nx, v.y(), nz, idx, dec.isAxisAware() ? facings[i] : null); + } + } + } + + private static void branchSurface(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { + int ay = v.y() + 1; + if (canvas.has(v.x(), ay, v.z()) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(v.x(), ay, v.z(), idx, null); + } + } + + private static void canopyTop(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + KMap colTop = new KMap<>(); + for (TreeBlockCanvas.Vec v : canvas.getCells().keySet()) { + long key = pack(v.x(), v.z()); + Integer cur = colTop.get(key); + if (cur == null || v.y() > cur) { + colTop.put(key, v.y()); + } + } + for (Map.Entry e : colTop.entrySet()) { + int x = unpackX(e.getKey()); + int z = unpackZ(e.getKey()); + int aboveY = e.getValue() + 1; + if (canvas.has(x, aboveY, z) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(x, aboveY, z, idx, null); + } + } + + private static void canopyBottom(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + KMap colBottom = columnLeafBottoms(canvas); + for (Map.Entry e : colBottom.entrySet()) { + int x = unpackX(e.getKey()); + int z = unpackZ(e.getKey()); + int belowY = e.getValue() - 1; + if (canvas.has(x, belowY, z) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(x, belowY, z, idx, null); + } + } + + private static void canopyHang(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + int maxLen = Math.max(1, dec.getLength()); + KMap colBottom = columnLeafBottoms(canvas); + for (Map.Entry e : colBottom.entrySet()) { + if (rng.nextDouble() > dec.getChance()) { + continue; + } + int x = unpackX(e.getKey()); + int z = unpackZ(e.getKey()); + int strand = rng.i(1, maxLen + 1); + for (int k = 1; k <= strand; k++) { + int yy = e.getValue() - k; + if (canvas.has(x, yy, z)) { + break; + } + canvas.setDecor(x, yy, z, idx, null); + } + } + } + + private static void trunkBase(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + int[][] sides = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; + for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { + if (v.y() != 0) { + continue; + } + for (int[] side : sides) { + int nx = v.x() + side[0]; + int nz = v.z() + side[1]; + if (canvas.has(nx, 0, nz) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(nx, 0, nz, idx, null); + } + } + } + + private static void trunkTop(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + int maxY = Integer.MIN_VALUE; + for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { + maxY = Math.max(maxY, v.y()); + } + if (maxY == Integer.MIN_VALUE) { + return; + } + for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { + if (v.y() != maxY) { + continue; + } + int aboveY = v.y() + 1; + if (canvas.has(v.x(), aboveY, v.z()) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(v.x(), aboveY, v.z(), idx, null); + } + } + + private static void groundScatter(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + double cx = 0; + double cz = 0; + int count = 0; + double footprint = 1.0; + for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { + if (v.y() == 0) { + cx += v.x(); + cz += v.z(); + count++; + } + } + if (count == 0) { + return; + } + cx /= count; + cz /= count; + for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { + if (v.y() == 0) { + footprint = Math.max(footprint, Math.hypot(v.x() - cx, v.z() - cz)); + } + } + int radius = (int) Math.ceil(footprint + 3.0); + int icx = (int) Math.round(cx); + int icz = (int) Math.round(cz); + for (int dx = -radius; dx <= radius; dx++) { + for (int dz = -radius; dz <= radius; dz++) { + if (Math.hypot(dx, dz) > radius) { + continue; + } + int x = icx + dx; + int z = icz + dz; + if (canvas.has(x, 0, z) || rng.nextDouble() > dec.getChance()) { + continue; + } + canvas.setDecor(x, 0, z, idx, null); + } + } + } + + private static KMap columnLeafBottoms(TreeBlockCanvas canvas) { + KMap colBottom = new KMap<>(); + for (TreeBlockCanvas.Vec v : canvas.getLeaf()) { + long key = pack(v.x(), v.z()); + Integer cur = colBottom.get(key); + if (cur == null || v.y() < cur) { + colBottom.put(key, v.y()); + } + } + return colBottom; + } + + private static String facingAway(int cx, int cz, int x, int z) { + int dx = x - cx; + int dz = z - cz; + if (Math.abs(dx) >= Math.abs(dz)) { + return dx >= 0 ? "east" : "west"; + } + return dz >= 0 ? "south" : "north"; + } + + private static long pack(int x, int z) { + return (((long) x) << 32) ^ (z & 0xFFFFFFFFL); + } + + private static int unpackX(long key) { + return (int) (key >> 32); + } + + private static int unpackZ(long key) { + return (int) (key & 0xFFFFFFFFL); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java new file mode 100644 index 000000000..3b223a18f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java @@ -0,0 +1,197 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeAzimuthMode; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeBranches; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeFunction; +import art.arcane.volmlib.util.math.RNG; + +public final class TreeFunctions { + private static final double GOLDEN_ANGLE = 137.50776405003785; + + private TreeFunctions() { + } + + public static double trunkWidthMultiplier(IrisProceduralTree tree, double t) { + double start = tree.getShapeStart(); + double end = tree.getShapeEnd(); + return switch (tree.getTrunkShape()) { + case CONSTANT -> 1.0; + case LINEAR -> start + (end - start) * t; + case SIGMOID -> 1.0 / (1.0 + Math.exp(tree.getShapeSteepness() * (t - 0.5))); + case LOG -> { + double base = Math.max(1.0001, tree.getShapeBase()); + if (t <= 0.0) { + yield 1.0; + } + yield Math.max(0.0, 1.0 - Math.log(1.0 + t * (base - 1.0)) / Math.log(base)); + } + case SINE -> { + double period = tree.getShapePeriod() == 0 ? 1.0 : tree.getShapePeriod(); + yield 1.0 + tree.getShapeAmplitude() * Math.sin(2.0 * Math.PI * t / period); + } + case PARABOLIC -> { + double peak = tree.getShapePeakOffset(); + double floor = tree.getShapeFloor(); + double denom = Math.pow(Math.max(peak, 1.0 - peak), 2); + if (denom == 0) { + denom = 1; + } + yield floor + (1.0 - floor) * (Math.pow(t - peak, 2) / denom); + } + case EXPONENTIAL -> geometric(start, end, t); + case SQRT -> start + (end - start) * Math.sqrt(t); + case STEP -> t < tree.getShapePeakOffset() ? start : end; + case BELL -> start + (end - start) * bell(t); + case EASE_IN_OUT -> start + (end - start) * smoothstep(t); + }; + } + + public static double curveProgress(IrisTreeFunction fn, double t, double steepness) { + return switch (fn) { + case LINEAR, CONSTANT, SINE -> t; + case LOG -> Math.log(1.0 + t * (Math.E - 1.0)); + case SIGMOID -> 1.0 / (1.0 + Math.exp(-steepness * (t - 0.5))); + case PARABOLIC, EASE_IN_OUT -> smoothstep(t); + case EXPONENTIAL -> Math.pow(t, Math.max(1.0, steepness)); + case SQRT -> Math.sqrt(t); + case STEP -> t < 0.5 ? 0.0 : 1.0; + case BELL -> bell(t); + }; + } + + public static double branchLength(IrisTreeBranches b, double t) { + double base = b.getLengthBase(); + double crown = b.getLengthCrown(); + double max = b.getLengthMax(); + double v = switch (b.getLengthFunction()) { + case CONSTANT -> b.getLengthConstant(); + case LINEAR, SINE -> base + (crown - base) * t; + case SIGMOID -> max / (1.0 + Math.exp(-b.getLengthSteepness() * (t - 0.5))); + case LOG -> max * Math.log(1.0 + t * (Math.E - 1.0)); + case PARABOLIC -> max * (1.0 - Math.pow(2.0 * t - 1.0, 2)); + case EXPONENTIAL -> geometric(base, crown, t); + case SQRT -> base + (crown - base) * Math.sqrt(t); + case STEP -> t < 0.5 ? base : crown; + case BELL -> base + (max - base) * bell(t); + case EASE_IN_OUT -> base + (crown - base) * smoothstep(t); + }; + return Math.max(1.0, v); + } + + public static double branchProbability(IrisTreeBranches b, double t, long seed) { + double std = Math.max(b.getProbabilityStd(), 1e-6); + return switch (b.getProbabilityFunction()) { + case CONSTANT -> b.getProbabilityConstant(); + case LINEAR -> b.getProbabilityBase() + (b.getProbabilityCrown() - b.getProbabilityBase()) * t; + case SIGMOID -> 1.0 / (1.0 + Math.exp(-b.getProbabilitySteepness() * (t - b.getProbabilityMidpoint()))); + case TOP_HEAVY -> Math.pow(t, b.getProbabilityExponent()); + case GAUSSIAN -> Math.exp(-0.5 * Math.pow((t - b.getProbabilityMean()) / std, 2)); + case NOISE -> valueNoise1D(t * b.getProbabilityScale(), seed); + case BOTTOM_HEAVY -> Math.pow(1.0 - t, b.getProbabilityExponent()); + case PERIODIC -> b.getProbabilityConstant() * Math.pow(Math.max(0.0, Math.sin(2.0 * Math.PI * t * b.getProbabilityPeriods())), 8); + case BAND -> Math.abs(t - b.getProbabilityMean()) <= b.getProbabilityStd() ? b.getProbabilityConstant() : 0.0; + case INVERSE_GAUSSIAN -> b.getProbabilityConstant() * (1.0 - Math.exp(-0.5 * Math.pow((t - b.getProbabilityMean()) / std, 2))); + case EXPONENTIAL_DECAY -> b.getProbabilityConstant() * Math.exp(-b.getProbabilityExponent() * t); + }; + } + + public static double azimuthDegrees(IrisTreeAzimuthMode mode, double t, int index, IrisProceduralTree tree, double constantBase, RNG rng) { + return switch (mode) { + case CONSTANT -> constantBase; + case LINEAR -> tree.getAzimuthStart() + (tree.getAzimuthEnd() - tree.getAzimuthStart()) * t; + case SPIRAL -> tree.getAzimuthStart() + tree.getAzimuthTurns() * 360.0 * t; + case SINE -> { + double period = tree.getAzimuthPeriod() == 0 ? 1.0 : tree.getAzimuthPeriod(); + yield tree.getAzimuthOffset() + tree.getAzimuthAmplitude() * Math.sin(2.0 * Math.PI * t / period); + } + case NOISE -> noiseAzimuth(t, tree.getAzimuthScale(), tree.getSeed()); + case RANDOM -> rng != null ? rng.d(0.0, 360.0) : constantBase; + case GOLDEN_ANGLE -> index >= 0 ? constantBase + index * GOLDEN_ANGLE : constantBase; + case ALTERNATING -> index >= 0 ? constantBase + (index % 2) * 180.0 : constantBase; + case WHORL -> { + int count = Math.max(1, tree.getAzimuthWhorlCount()); + yield index >= 0 ? constantBase + (index % count) * (360.0 / count) : constantBase; + } + case ZIGZAG -> index >= 0 ? constantBase + ((index % 2 == 0) ? -tree.getAzimuthAmplitude() : tree.getAzimuthAmplitude()) : constantBase; + }; + } + + public static TreeBlockCanvas.Axis logAxis(double dx, double dy, double dz) { + double ax = Math.abs(dx); + double ay = Math.abs(dy) * 1.8; + double az = Math.abs(dz); + if (ay >= ax && ay >= az) { + return TreeBlockCanvas.Axis.Y; + } + if (ax >= az) { + return TreeBlockCanvas.Axis.X; + } + return TreeBlockCanvas.Axis.Z; + } + + private static double geometric(double a, double b, double t) { + if (a <= 0.0 || b <= 0.0) { + return a + (b - a) * t; + } + return a * Math.pow(b / a, t); + } + + private static double bell(double t) { + return Math.exp(-Math.pow(t - 0.5, 2) / (2.0 * 0.15 * 0.15)); + } + + private static double smoothstep(double t) { + return 3.0 * t * t - 2.0 * t * t * t; + } + + public static double noiseAzimuth(double t, double scale, long seed) { + double a = valueNoise1D(t * scale, seed); + double b = valueNoise1D(t * scale * 0.5, seed + 1); + return ((a + b) / 2.0) * 360.0; + } + + public static double valueNoise1D(double x, long seed) { + long h = mix(seed * 0x9E3779B97F4A7C15L + Math.round(x * 1000.0)); + return unit(h); + } + + public static double valueNoise3D(int x, int y, int z, long seed) { + long h = mix(seed); + h = mix(h + x * 0x9E3779B97F4A7C15L); + h = mix(h + y * 0xC2B2AE3D27D4EB4FL); + h = mix(h + z * 0x165667B19E3779F9L); + return unit(h); + } + + private static long mix(long a) { + a ^= (a >>> 33); + a *= 0xff51afd7ed558ccdL; + a ^= (a >>> 33); + a *= 0xc4ceb9fe1a85ec53L; + a ^= (a >>> 33); + return a; + } + + private static double unit(long h) { + return (h >>> 11) * 0x1.0p-53; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java new file mode 100644 index 000000000..ab62bab58 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java @@ -0,0 +1,104 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.spi.PlatformBlockState; + +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public final class TreePlausibility { + private static final int MAX_DISTANCE = 7; + private static final int[][] NEIGHBORS = { + {1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1} + }; + + private TreePlausibility() { + } + + public static void apply(Map resolved, Set trunkPositions, + Set leafPositions, IrisProceduralTree tree) { + Set realLeaves = new HashSet<>(); + for (TreeBlockCanvas.Vec v : leafPositions) { + PlatformBlockState state = resolved.get(v); + if (state != null && IrisProceduralBlocks.hasProperty(state, "persistent") && IrisProceduralBlocks.hasProperty(state, "distance")) { + realLeaves.add(v); + } + } + if (realLeaves.isEmpty()) { + return; + } + + Map distance = computeDistances(trunkPositions, realLeaves); + + for (TreeBlockCanvas.Vec v : realLeaves) { + PlatformBlockState leaf = resolved.get(v); + Integer d = distance.get(v); + if (!tree.isPlausible()) { + leaf = leaf.withProperty("persistent", "true").withProperty("distance", "1"); + } else if (d != null && d < MAX_DISTANCE) { + leaf = leaf.withProperty("persistent", "false").withProperty("distance", String.valueOf(Math.max(1, d))); + } else { + leaf = leaf.withProperty("persistent", "true").withProperty("distance", String.valueOf(MAX_DISTANCE)); + } + resolved.put(v, leaf); + } + } + + static Map computeDistances(Set trunkPositions, Set realLeaves) { + Map distance = new HashMap<>(); + ArrayDeque queue = new ArrayDeque<>(); + + for (TreeBlockCanvas.Vec v : realLeaves) { + for (int[] n : NEIGHBORS) { + if (trunkPositions.contains(new TreeBlockCanvas.Vec(v.x() + n[0], v.y() + n[1], v.z() + n[2]))) { + distance.put(v, 1); + queue.add(v); + break; + } + } + } + + while (!queue.isEmpty()) { + TreeBlockCanvas.Vec v = queue.poll(); + int d = distance.get(v); + if (d >= MAX_DISTANCE) { + continue; + } + for (int[] n : NEIGHBORS) { + TreeBlockCanvas.Vec nv = new TreeBlockCanvas.Vec(v.x() + n[0], v.y() + n[1], v.z() + n[2]); + if (!realLeaves.contains(nv)) { + continue; + } + Integer existing = distance.get(nv); + if (existing == null || existing > d + 1) { + distance.put(nv, d + 1); + queue.add(nv); + } + } + } + + return distance; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java new file mode 100644 index 000000000..f3bfabf6f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java @@ -0,0 +1,79 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.procedural.tree.IrisTreeProfile; + +public final class TreeProfiles { + private TreeProfiles() { + } + + static double radiusScale(IrisTreeProfile profile) { + return switch (profile) { + case OAK, DARK_OAK, CHERRY -> 1.0; + case BIRCH -> 0.7; + case SPRUCE -> 0.55; + case JUNGLE -> 0.45; + case ACACIA -> 0.6; + case DARK_OAK_FLAT -> 1.25; + case DARK_OAK_FLAT_WIDE -> 1.8; + case PALM -> 0.5; + case WILLOW -> 1.1; + case COLUMNAR -> 0.35; + case BUSH -> 1.3; + case MEGA_SPRUCE -> 0.7; + }; + } + + static double[][] fractions(IrisTreeProfile profile) { + return switch (profile) { + case OAK -> new double[][]{{0.55, 0.6}, {0.65, 0.9}, {0.75, 1.0}, {0.85, 0.9}, {0.92, 0.65}, {0.98, 0.35}}; + case BIRCH -> new double[][]{{0.6, 0.45}, {0.7, 0.75}, {0.8, 0.85}, {0.88, 0.75}, {0.94, 0.45}, {0.99, 0.2}}; + case SPRUCE, MEGA_SPRUCE -> new double[][]{{0.3, 1.0}, {0.42, 0.85}, {0.54, 0.7}, {0.65, 0.55}, {0.75, 0.4}, {0.84, 0.25}, {0.91, 0.15}, {0.97, 0.05}}; + case JUNGLE -> new double[][]{{0.82, 0.4}, {0.88, 0.8}, {0.93, 1.0}, {0.97, 0.7}, {1.0, 0.3}}; + case ACACIA -> new double[][]{{0.9, 0.5}, {0.95, 0.8}, {0.99, 0.4}}; + case DARK_OAK -> new double[][]{{0.5, 0.7}, {0.62, 1.0}, {0.72, 1.0}, {0.82, 0.9}, {0.91, 0.6}, {0.97, 0.3}}; + case DARK_OAK_FLAT -> new double[][]{{0.74, 0.62}, {0.83, 1.0}, {0.92, 1.0}, {1.0, 0.6}}; + case DARK_OAK_FLAT_WIDE -> new double[][]{{0.74, 0.62}, {0.83, 1.0}, {0.92, 1.0}, {1.0, 0.62}}; + case CHERRY -> new double[][]{{0.5, 0.5}, {0.62, 0.9}, {0.74, 1.0}, {0.84, 1.0}, {0.92, 0.7}, {0.98, 0.4}}; + case PALM -> new double[][]{{0.92, 0.45}, {0.97, 0.9}, {1.0, 1.0}, {1.03, 0.6}}; + case WILLOW -> new double[][]{{0.55, 0.7}, {0.68, 1.0}, {0.8, 1.0}, {0.9, 0.85}, {0.97, 0.6}}; + case COLUMNAR -> new double[][]{{0.4, 0.6}, {0.55, 0.9}, {0.7, 1.0}, {0.82, 0.9}, {0.92, 0.7}, {0.98, 0.4}}; + case BUSH -> new double[][]{{0.25, 0.7}, {0.45, 1.0}, {0.65, 1.0}, {0.82, 0.8}, {0.95, 0.5}}; + }; + } + + static double[][] presetLayers(IrisTreeProfile profile, int height, boolean branchDriven) { + double scale = radiusScale(profile); + int baseRadius = Math.max(3, (int) Math.round(height / 2.0 * scale)); + double[][] fractions = fractions(profile); + + int crownExtra = branchDriven ? 0 : Math.max(2, height / 4); + int yTop = (height - 1) + crownExtra; + + double[][] layers = new double[fractions.length][2]; + for (int i = 0; i < fractions.length; i++) { + int yOff = (int) Math.round(fractions[i][0] * yTop); + double radius = Math.max(1.5, baseRadius * fractions[i][1]); + layers[i][0] = yOff; + layers[i][1] = radius; + } + return layers; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java new file mode 100644 index 000000000..04950a18f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java @@ -0,0 +1,154 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeRootStyle; +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; + +public final class TreeRootBuilder { + private TreeRootBuilder() { + } + + public static void build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, long baseSeed) { + List cells = new ArrayList<>(); + for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { + if (v.y() == 0) { + cells.add(new int[]{v.x(), v.z()}); + } + } + if (cells.isEmpty()) { + return; + } + + int depth = tree.getRootDepth() > 0 ? tree.getRootDepth() : autoDepth(height); + RNG rng = new RNG(baseSeed ^ 0x5009L); + + double cx = 0; + double cz = 0; + for (int[] c : cells) { + cx += c[0]; + cz += c[1]; + } + cx /= cells.size(); + cz /= cells.size(); + + double baseRadius = 1.0; + for (int[] c : cells) { + baseRadius = Math.max(baseRadius, Math.hypot(c[0] - cx, c[1] - cz) + 0.5); + } + double flare = tree.getRootFlare() > 0 ? tree.getRootFlare() : baseRadius + Math.max(2.0, depth * 0.6); + + IrisTreeRootStyle style = tree.getRootStyle(); + switch (style) { + case TAPROOT -> taproot(canvas, cells, cx, cz, baseRadius, depth); + case BUTTRESS -> { + taproot(canvas, cells, cx, cz, baseRadius, depth); + buttress(canvas, cells, cx, cz, baseRadius, depth, flare, rng); + } + case STILT -> { + taproot(canvas, cells, cx, cz, baseRadius, Math.min(depth, 3)); + stilts(canvas, cx, cz, baseRadius, flare, height, cells.size(), rng); + } + } + } + + private static void taproot(TreeBlockCanvas canvas, List cells, double cx, double cz, double baseRadius, int depth) { + int icx = (int) Math.round(cx); + int icz = (int) Math.round(cz); + for (int k = 1; k <= depth; k++) { + double frac = k / (double) depth; + double keepR = baseRadius * (1.0 - 0.6 * frac); + for (int[] c : cells) { + if (Math.hypot(c[0] - cx, c[1] - cz) <= keepR + 1e-6) { + placeRoot(canvas, c[0], -k, c[1], TreeBlockCanvas.Axis.Y); + } + } + placeRoot(canvas, icx, -k, icz, TreeBlockCanvas.Axis.Y); + } + } + + private static void buttress(TreeBlockCanvas canvas, List cells, double cx, double cz, double baseRadius, + int depth, double flare, RNG rng) { + int nLegs = Math.max(4, Math.min(12, cells.size() + 2)); + for (int li = 0; li < nLegs; li++) { + double ang = 2.0 * Math.PI * li / nLegs + rng.d(-0.25, 0.25); + double ca = Math.cos(ang); + double sa = Math.sin(ang); + int prevX = (int) Math.round(cx + baseRadius * ca); + int prevZ = (int) Math.round(cz + baseRadius * sa); + for (int k = 1; k <= depth; k++) { + double frac = k / (double) depth; + double r = baseRadius + (flare - baseRadius) * frac; + int x = (int) Math.round(cx + r * ca); + int z = (int) Math.round(cz + r * sa); + placeRoot(canvas, x, -k, z, TreeBlockCanvas.Axis.Y); + if (x != prevX || z != prevZ) { + placeRoot(canvas, prevX, -k, prevZ, TreeBlockCanvas.Axis.Y); + } + prevX = x; + prevZ = z; + } + } + } + + private static void stilts(TreeBlockCanvas canvas, double cx, double cz, double baseRadius, double flare, + int height, int cellCount, RNG rng) { + int stiltTop = Math.max(2, Math.min(7, (int) Math.round(0.25 * height))); + int nProps = Math.max(4, Math.min(10, cellCount + 2)); + for (int p = 0; p < nProps; p++) { + double ang = 2.0 * Math.PI * p / nProps + rng.d(-0.25, 0.25); + double ca = Math.cos(ang); + double sa = Math.sin(ang); + int sx = (int) Math.round(cx + baseRadius * ca); + int sz = (int) Math.round(cz + baseRadius * sa); + int fx = (int) Math.round(cx + flare * ca); + int fz = (int) Math.round(cz + flare * sa); + rasterizeRoot(canvas, sx, stiltTop, sz, fx, -2, fz); + } + } + + private static void rasterizeRoot(TreeBlockCanvas canvas, int ox, int oy, int oz, int ex, int ey, int ez) { + int dx = ex - ox; + int dy = ey - oy; + int dz = ez - oz; + int steps = Math.max(Math.max(Math.abs(dx), Math.abs(dy)), Math.max(Math.abs(dz), 1)); + TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(dx, dy, dz); + for (int i = 0; i <= steps; i++) { + double t = i / (double) steps; + int x = (int) Math.round(ox + dx * t); + int y = (int) Math.round(oy + dy * t); + int z = (int) Math.round(oz + dz * t); + placeRoot(canvas, x, y, z, axis); + } + } + + private static void placeRoot(TreeBlockCanvas canvas, int x, int y, int z, TreeBlockCanvas.Axis axis) { + if (!canvas.has(x, y, z)) { + canvas.setTrunk(x, y, z, TreeBlockCanvas.Role.TRUNK, axis); + } + } + + private static int autoDepth(int height) { + return Math.max(2, Math.min(16, (int) Math.round(0.18 * height))); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java new file mode 100644 index 000000000..c6ef85c91 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java @@ -0,0 +1,90 @@ +/* + * 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.procedural.tree; + +import java.util.ArrayList; +import java.util.Map; + +public final class TreeSupport { + private static final int LEGAL_DISTANCE = 6; + private static final int REACH_GAP = 4; + + private TreeSupport() { + } + + public static void ensureLeavesSupported(TreeBlockCanvas canvas, int maxTendrils) { + for (int iter = 0; iter < maxTendrils; iter++) { + Map dist = TreePlausibility.computeDistances(canvas.getTrunk(), canvas.getLeaf()); + + TreeBlockCanvas.Vec worstLeaf = null; + TreeBlockCanvas.Vec worstWood = null; + int worstGap = -1; + + for (TreeBlockCanvas.Vec leaf : new ArrayList<>(canvas.getLeaf())) { + Integer d = dist.get(leaf); + if (d != null && d <= LEGAL_DISTANCE) { + continue; + } + TreeBlockCanvas.Vec nearest = null; + int best = Integer.MAX_VALUE; + for (TreeBlockCanvas.Vec wood : canvas.getTrunk()) { + int cd = chebyshev(leaf, wood); + if (cd < best) { + best = cd; + nearest = wood; + if (cd <= 1) { + break; + } + } + } + if (nearest != null && best > worstGap) { + worstGap = best; + worstLeaf = leaf; + worstWood = nearest; + } + } + + if (worstLeaf == null) { + return; + } + growTendril(canvas, worstWood, worstLeaf); + } + } + + private static void growTendril(TreeBlockCanvas canvas, TreeBlockCanvas.Vec from, TreeBlockCanvas.Vec to) { + int dx = to.x() - from.x(); + int dy = to.y() - from.y(); + int dz = to.z() - from.z(); + int length = Math.max(Math.max(Math.abs(dx), Math.abs(dy)), Math.max(Math.abs(dz), 1)); + int steps = Math.max(1, length - REACH_GAP); + TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(dx, dy, dz); + + for (int i = 1; i <= steps; i++) { + double t = i / (double) length; + int x = from.x() + (int) Math.round(dx * t); + int y = from.y() + (int) Math.round(dy * t); + int z = from.z() + (int) Math.round(dz * t); + canvas.setTrunk(x, y, z, TreeBlockCanvas.Role.TRUNK, axis); + } + } + + private static int chebyshev(TreeBlockCanvas.Vec a, TreeBlockCanvas.Vec b) { + return Math.max(Math.max(Math.abs(a.x() - b.x()), Math.abs(a.y() - b.y())), Math.abs(a.z() - b.z())); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java new file mode 100644 index 000000000..20698ab17 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java @@ -0,0 +1,206 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeAzimuthMode; + +import java.util.ArrayList; +import java.util.List; + +public final class TreeTrunkBuilder { + public record Limb(double[][] offsets, int branchStartY) { + } + + private TreeTrunkBuilder() { + } + + public static List build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height) { + boolean hasSecondary = hasSecondaryTrunk(tree); + double[][] mainOffsets = leanPath(tree, height); + int forks = Math.max(1, tree.getTrunkForks()); + + List limbs = new ArrayList<>(); + if (forks == 1) { + placeColumn(canvas, tree, mainOffsets, height, 0, height - 1, hasSecondary); + limbs.add(new Limb(mainOffsets, 0)); + markExposedEnds(canvas); + return limbs; + } + + int forkY = Math.max(1, Math.min(height - 2, (int) Math.round(tree.getForkHeight() * (height - 1)))); + placeColumn(canvas, tree, mainOffsets, height, 0, forkY, hasSecondary); + + double baseCx = mainOffsets[forkY][0]; + double baseCz = mainOffsets[forkY][1]; + double reachMax = (height - forkY) * Math.tan(Math.toRadians(tree.getForkAngle())); + + for (int f = 0; f < forks; f++) { + double az = Math.toRadians((360.0 / forks) * f); + double[][] forkOffsets = new double[height][2]; + for (int y = 0; y <= forkY; y++) { + forkOffsets[y][0] = mainOffsets[y][0]; + forkOffsets[y][1] = mainOffsets[y][1]; + } + for (int y = forkY + 1; y < height; y++) { + double p = (y - forkY) / (double) Math.max(1, height - 1 - forkY); + double reach = reachMax * p; + forkOffsets[y][0] = baseCx + reach * Math.sin(az); + forkOffsets[y][1] = baseCz + reach * Math.cos(az); + } + placeColumn(canvas, tree, forkOffsets, height, forkY + 1, height - 1, hasSecondary); + limbs.add(new Limb(forkOffsets, forkY)); + } + + markExposedEnds(canvas); + return limbs; + } + + private static double[][] leanPath(IrisProceduralTree tree, int height) { + double[][] offsets = new double[height][2]; + for (int y = 0; y < height; y++) { + double[] lean = leanOffset(tree, y, height); + offsets[y][0] = lean[0]; + offsets[y][1] = lean[1]; + } + return offsets; + } + + private static void placeColumn(TreeBlockCanvas canvas, IrisProceduralTree tree, double[][] offsets, int height, + int yStart, int yEnd, boolean hasSecondary) { + double prevCx = yStart > 0 ? offsets[yStart - 1][0] : 0.0; + double prevCz = yStart > 0 ? offsets[yStart - 1][1] : 0.0; + + for (int y = yStart; y <= yEnd; y++) { + double cx = offsets[y][0]; + double cz = offsets[y][1]; + int w = widthAt(tree, y, height); + TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(cx - prevCx, 1.0, cz - prevCz); + TreeBlockCanvas.Role role = trunkRole(tree, hasSecondary, y, height); + + for (int[] xz : squarePositions(cx, cz, w)) { + canvas.setTrunk(xz[0], y, xz[1], role, axis); + } + + double shift = Math.hypot(cx - prevCx, cz - prevCz); + if (shift > 1.0) { + int steps = (int) Math.ceil(shift); + for (int s = 1; s < steps; s++) { + double tFill = s / (double) steps; + double icx = prevCx + (cx - prevCx) * tFill; + double icz = prevCz + (cz - prevCz) * tFill; + int fillY = (int) Math.round(y - 1 + tFill); + for (int[] xz : squarePositions(icx, icz, w)) { + if (!canvas.has(xz[0], fillY, xz[1])) { + canvas.setTrunk(xz[0], fillY, xz[1], role, axis); + } + } + } + } + + prevCx = cx; + prevCz = cz; + } + } + + private static void markExposedEnds(TreeBlockCanvas canvas) { + for (TreeBlockCanvas.Vec v : new ArrayList<>(canvas.getTrunk())) { + if (!canvas.has(v.x(), v.y() + 1, v.z()) || !canvas.has(v.x(), v.y() - 1, v.z())) { + canvas.markExposed(v.x(), v.y(), v.z()); + } + } + } + + private static int widthAt(IrisProceduralTree tree, int y, int height) { + double t = y / (double) Math.max(height - 1, 1); + double multiplier = TreeFunctions.trunkWidthMultiplier(tree, t); + return Math.max(1, (int) Math.round(tree.getTrunkWidth() * multiplier)); + } + + private static TreeBlockCanvas.Role trunkRole(IrisProceduralTree tree, boolean hasSecondary, int y, int height) { + if (!hasSecondary) { + return TreeBlockCanvas.Role.TRUNK; + } + double t = y / (double) Math.max(height - 1, 1); + if (tree.getSecondaryTrunkStart() <= t && t <= tree.getSecondaryTrunkEnd()) { + return TreeBlockCanvas.Role.SECONDARY_TRUNK; + } + return TreeBlockCanvas.Role.TRUNK; + } + + private static boolean hasSecondaryTrunk(IrisProceduralTree tree) { + if (paletteSet(tree.getSecondaryTrunkPalette())) { + return true; + } + return tree.getSecondaryTrunk() != null && !tree.getSecondaryTrunk().isEmpty(); + } + + static boolean paletteSet(IrisMaterialPalette palette) { + return palette != null && palette.getPalette() != null && !palette.getPalette().isEmpty(); + } + + private static double[] leanOffset(IrisProceduralTree tree, int y, int height) { + if (tree.getLeanAngle() == 0.0 || height <= 1) { + return new double[]{0.0, 0.0}; + } + double t = y / (double) Math.max(height - 1, 1); + double progress = TreeFunctions.curveProgress(tree.getTrunkCurve(), t, tree.getCurveSteepness()); + double maxReach = height * Math.tan(Math.toRadians(tree.getLeanAngle())); + double reach = maxReach * progress; + double azDeg = tree.getLeanAzimuthMode() == IrisTreeAzimuthMode.CONSTANT + ? tree.getLeanAzimuth() + : TreeFunctions.azimuthDegrees(tree.getLeanAzimuthMode(), t, -1, tree, tree.getLeanAzimuth(), null); + double azRad = Math.toRadians(azDeg); + double dx = reach * Math.sin(azRad); + double dz = reach * Math.cos(azRad); + return new double[]{dx, dz}; + } + + private static List squarePositions(double cx, double cz, int width) { + List out = new ArrayList<>(); + if (width % 2 == 1) { + int half = width / 2; + int icx = (int) Math.round(cx); + int icz = (int) Math.round(cz); + for (int dx = -half; dx <= half; dx++) { + for (int dz = -half; dz <= half; dz++) { + out.add(new int[]{icx + dx, icz + dz}); + } + } + } else { + int ox = (int) Math.floor(cx) - width / 2 + 1; + int oz = (int) Math.floor(cz) - width / 2 + 1; + for (int dx = 0; dx < width; dx++) { + for (int dz = 0; dz < width; dz++) { + out.add(new int[]{ox + dx, oz + dz}); + } + } + } + return out; + } + + static String stripState(String block) { + if (block == null) { + return null; + } + int idx = block.indexOf('['); + return idx < 0 ? block : block.substring(0, idx); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java new file mode 100644 index 000000000..f465ec8a7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java @@ -0,0 +1,51 @@ +/* + * 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.entity.spawn.IrisSpawnerCooldowns; +import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.volmlib.util.collection.KMap; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +public class IrisEngineData extends IrisSpawnerCooldowns { + private IrisEngineStatistics statistics = new IrisEngineStatistics(); + private KMap chunks = new KMap<>(); + private Long seed = null; + + public void removeChunk(int x, int z) { + chunks.remove(Cache.key(x, z)); + } + + public IrisSpawnerCooldowns getChunk(int x, int z) { + return chunks.computeIfAbsent(Cache.key(x, z), k -> new IrisSpawnerCooldowns()); + } + + public void cleanup(Engine engine) { + super.cleanup(engine); + + chunks.values().removeIf(chunk -> { + chunk.cleanup(engine); + return chunk.isEmpty(); + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java new file mode 100644 index 000000000..ae392297d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java @@ -0,0 +1,67 @@ +/* + * 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 lombok.Data; + +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + +@Data +public class IrisEngineStatistics { + private static final AtomicIntegerFieldUpdater TOTAL_HOTLOADS = + AtomicIntegerFieldUpdater.newUpdater(IrisEngineStatistics.class, "totalHotloads"); + private static final AtomicIntegerFieldUpdater CHUNKS_GENERATED = + AtomicIntegerFieldUpdater.newUpdater(IrisEngineStatistics.class, "chunksGenerated"); + + private volatile int totalHotloads = 0; + private volatile int chunksGenerated = 0; + private volatile int IrisToUpgradedVersion = 0; + private volatile int IrisCreationVersion = 0; + private volatile int MinecraftVersion = 0; + + public void generatedChunk() { + CHUNKS_GENERATED.incrementAndGet(this); + } + + public void setUpgradedVersion(int i) { + IrisToUpgradedVersion = i; + } + public int getUpgradedVersion() { + return IrisToUpgradedVersion; + } + public void setVersion(int i) { + IrisCreationVersion = i; + } + + public int getVersion() { + return IrisCreationVersion; + } + + public void setMCVersion(int i) { + MinecraftVersion = i; + } + + public int getMCVersion() { + return MinecraftVersion; + } + + public void hotloaded() { + TOTAL_HOTLOADS.incrementAndGet(this); + } +} 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 new file mode 100644 index 000000000..ba0d23fad --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStreamType.java @@ -0,0 +1,55 @@ +/* + * 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 new file mode 100644 index 000000000..f676276b1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineValueType.java @@ -0,0 +1,50 @@ +/* + * 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 new file mode 100644 index 000000000..034eb6572 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/runtime/StudioMode.java @@ -0,0 +1,67 @@ +/* + * 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 new file mode 100644 index 000000000..e3bc5a159 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -0,0 +1,150 @@ +/* + * 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.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.loot.IrisObjectLoot; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisObjectReplace; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +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 = IrisObjectReplace.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(IrisLootTable.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 = ""; + + 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 IrisObjectLoot().setName(lootTable).setWeight(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/IrisStructureAnchorMode.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java new file mode 100644 index 000000000..b7d17991a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java @@ -0,0 +1,34 @@ +package art.arcane.iris.engine.object.structure; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Selects the vertical environment used to anchor an Iris structure placement.") +public enum IrisStructureAnchorMode { + @Desc("Preserve the historical underground boolean behavior.") + LEGACY, + + @Desc("Anchor to the terrain surface and use minHeight/maxHeight as a surface gate.") + SURFACE, + + @Desc("Choose a deterministic Y inside the minHeight/maxHeight band.") + HEIGHT_BAND, + + @Desc("Anchor in carved space with solid support below.") + CAVE_FLOOR, + + @Desc("Anchor in carved space with solid support above.") + CAVE_CEILING, + + @Desc("Anchor in carved space without nearby floor or ceiling support.") + CAVE_CENTER, + + @Desc("Anchor at any carved-space position.") + CAVE_ANY; + + public boolean isCave() { + return switch (this) { + case CAVE_FLOOR, CAVE_CEILING, CAVE_CENTER, CAVE_ANY -> true; + default -> false; + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java new file mode 100644 index 000000000..123367217 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java @@ -0,0 +1,36 @@ +package art.arcane.iris.engine.object.structure; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls the shape of the expanded terrain carve around an overbored structure.") +public enum IrisStructureCarveShape { + @Desc("Carves the full expanded rectangular volume with straight walls, ceiling, and floor.") + BOX, + + @Desc("Carves a smooth rounded volume around the structure without erosion noise.") + ROUNDED, + + @Desc("Carves a rounded volume whose outer boundary is eroded by deterministic noise.") + ERODED; + + public double maximumCeilingScale() { + return maximumCeilingScale(1D); + } + + public double maximumCeilingScale(double erosionStrength) { + double strength = Double.isFinite(erosionStrength) + ? Math.max(0D, Math.min(1D, erosionStrength)) : 1D; + return switch (this) { + case BOX, ROUNDED -> 1D; + case ERODED -> 1D + 0.8D * strength; + }; + } + + public int maximumCeilingExtension(int configuredHeight) { + return maximumCeilingExtension(configuredHeight, 1D); + } + + public int maximumCeilingExtension(int configuredHeight, double erosionStrength) { + return (int) Math.ceil(Math.max(0, configuredHeight) * maximumCeilingScale(erosionStrength)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java new file mode 100644 index 000000000..421098ab9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java @@ -0,0 +1,153 @@ +/* + * 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.engine.object.structure.vanilla.IrisNativeStructure; +import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; +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.MaxNumber; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.RegistryListStructure; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Attaches structures to a biome, region or dimension and controls where and how often they generate. This is independent of a structure's own native generation, so you can add custom placements in tandem with native generation or instead of it.") +@Data +public class IrisStructurePlacement { + @ArrayType(type = String.class, min = 1) + @RegistryListStructure + @Desc("Editable Iris assembly resources offered by this placement. Leave empty when nativeStructures supplies the source.") + private KList structures = new KList<>(); + + @ArrayType(type = IrisNativeStructure.class, min = 1) + @Desc("Live registered vanilla, datapack, and modded structures offered by this placement. Minecraft runs their native generator directly, independent of normal biome or dimension eligibility.") + private KList nativeStructures = new KList<>(); + + @Desc("Stable authored identity for this placement. Set this when multiple placements use the same structure and settings. When empty, Iris derives identity from the placement content so list reordering does not move generated structures.") + private String placementId = ""; + + @Desc("Controls native replacement for this placement. REPLACE_SOURCE suppresses each selected Iris structure's vanillaSource or registered native source, and is honored only for dimension-level placements. NONE leaves native generation untouched.") + private NativeStructureSuppression nativeSuppression = NativeStructureSuppression.NONE; + + @Desc("How start positions are scattered.") + private StructureDistribution distribution = StructureDistribution.RANDOM_SPREAD; + + @MinNumber(1) + @MaxNumber(4096) + @Desc("RANDOM_SPREAD only: the grid cell size in chunks. One placement attempt per cell. Larger = rarer.") + private int spacing = 32; + + @MinNumber(0) + @Desc("RANDOM_SPREAD only: the minimum chunk separation between placements within the grid. Must be smaller than spacing.") + private int separation = 8; + + @Desc("RANDOM_SPREAD only: a salt mixed into the placement RNG so different structures using the same spacing do not stack.") + private int salt = 165745296; + + @MinNumber(0) + @MaxNumber(1) + @Desc("DENSITY only: the per-chunk probability (0-1) of a placement starting in a chunk.") + private double density = 0.02; + + @MinNumber(1) + @Desc("CONCENTRIC_RINGS only: the number of placements distributed across the rings.") + private int ringCount = 128; + + @MinNumber(1) + @Desc("CONCENTRIC_RINGS only: the ring spacing in chunks.") + private int ringDistance = 32; + + @MinNumber(1) + @Desc("CONCENTRIC_RINGS only: how many placements share each ring before moving outward.") + private int ringSpread = 3; + + @Desc("Minimum world Y. SURFACE uses it as a terrain-height gate; HEIGHT_BAND and cave anchors use it as the lower candidate bound. LEGACY follows underground.") + private int minHeight = -2032; + + @Desc("Maximum world Y. SURFACE uses it as a terrain-height gate; HEIGHT_BAND and cave anchors use it as the upper candidate bound. LEGACY follows underground.") + private int maxHeight = 2032; + + @Desc("LEGACY anchor only: if true, choose a deterministic world Y inside [minHeight, maxHeight]; otherwise gate the terrain surface. Explicit anchor modes override this field.") + private boolean underground = false; + + @Desc("Vertical anchor policy. LEGACY preserves the underground boolean. Cave modes search existing carved-space data and implicitly behave as underground placements.") + private IrisStructureAnchorMode anchor = IrisStructureAnchorMode.LEGACY; + + @RegistryListResource(IrisBiome.class) + @ArrayType(type = String.class, min = 1) + @Desc("Optional cave-biome allowlist for cave anchor modes. Empty accepts the cave biome resolved at the selected anchor. Entries match by load key, including prefix matches.") + private KList caveBiomes = new KList<>(); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Cave anchor modes only: deterministic X/Z columns tested inside the start chunk before the placement is skipped.") + private int caveAnchorAttempts = 8; + + @MinNumber(1) + @MaxNumber(16) + @Desc("Cave anchor modes only: vertical scan step in blocks. One is exact; larger values trade precision for speed.") + private int caveAnchorScanStep = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("Cave anchor modes only: minimum contiguous carved-space height required at the selected anchor.") + private int caveMinimumClearance = 3; + + @Desc("Terrain integration for this placement. The editable structures backend supports SOURCE, PRESERVE, BORE, and FORCE_CARVE. The nativeStructures backend supports every terrain mode.") + private IrisStructureTerrain terrain = new IrisStructureTerrain(); + + @Desc("Optional foundation columns placed beneath the assembled structure's occupied bottom cells. Columns pass through air and fluids until they reach solid ground, up to maxDepth.") + private IrisStructureStiltSettings stilt = null; + + @Desc("If false, the placement is skipped when its selected surface or cave column is submerged.") + private boolean underwater = false; + + public IrisStructureTerrain resolvedTerrain() { + return terrain == null ? new IrisStructureTerrain() : terrain; + } + + public boolean hasIrisStructures() { + return structures != null && !structures.isEmpty(); + } + + public boolean hasNativeStructures() { + return nativeStructures != null && !nativeStructures.isEmpty(); + } + + public IrisStructureAnchorMode resolvedAnchor() { + if (anchor == null || anchor == IrisStructureAnchorMode.LEGACY) { + return underground ? IrisStructureAnchorMode.HEIGHT_BAND : IrisStructureAnchorMode.SURFACE; + } + return anchor; + } + + public boolean isAnchoredUnderground() { + IrisStructureAnchorMode activeAnchor = resolvedAnchor(); + return activeAnchor == IrisStructureAnchorMode.HEIGHT_BAND || activeAnchor.isCave(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java new file mode 100644 index 000000000..7d1e90337 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java @@ -0,0 +1,33 @@ +package art.arcane.iris.engine.object.structure; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +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 +@Desc("Defines foundation columns placed beneath a structure.") +@Data +public class IrisStructureStiltSettings { + @MinNumber(1) + @MaxNumber(4064) + @Desc("Maximum number of blocks each foundation column may descend while searching for solid ground.") + private int maxDepth = 64; + + @Desc("Block palette used for foundation columns.") + private IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:cobblestone"); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Horizontal spacing between support columns. One fills every eligible foundation column; larger values create sparse stilts.") + private int spacing = 1; + + @Desc("For Iris-authored structures, whether solid partial blocks such as slabs, stairs, and walls may seed foundation columns instead of requiring a fully occluding base block.") + private boolean supportNonOccluding = false; +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java new file mode 100644 index 000000000..311598130 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java @@ -0,0 +1,105 @@ +package art.arcane.iris.engine.object.structure; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +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("Terrain integration applied after a structure graph is assembled and before its pieces are placed.") +public class IrisStructureTerrain { + private static final double AUTO_LOBE_FREQUENCY_RATIO = 0.3D; + private static final double DEFAULT_EROSION_STRENGTH = 0.8D; + private static final double DEFAULT_EROSION_FREQUENCY = 0.07D; + private static final double DEFAULT_LOBE_STRENGTH = 0.85D; + private static final double MIN_EROSION_FREQUENCY = 0.001D; + private static final double MAX_EROSION_FREQUENCY = 1D; + private static final double MAX_LOBE_FREQUENCY = 1D; + + @Desc("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. VACUUM raises terrain from processed rigid-template foundations at or below each authored ground plane with a 12-block falloff without lowering existing ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement so native shells are not lost to pre-carved air.") + private IrisStructureTerrainMode mode = IrisStructureTerrainMode.SOURCE; + + @MinNumber(0) + @MaxNumber(128) + @Desc("Horizontal clearance around the assembled pieces for BORE, FORCE_CARVE, and ENCASE. VACUUM uses its fixed 12-block terrain falloff.") + private int horizontalPadding = 0; + + @MinNumber(0) + @MaxNumber(128) + @Desc("Air clearance above the assembled pieces.") + private int ceilingPadding = 0; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Terrain cleared below the assembled pieces. Zero preserves their supporting floor.") + private int floorPadding = 0; + + @Desc("Shape used by FORCE_CARVE.") + private IrisStructureCarveShape shape = IrisStructureCarveShape.BOX; + + @Desc("Block palette used by ENCASE. When unset, the Overworld uses stone or deepslate, the Nether uses netherrack, and the End uses end stone.") + private IrisMaterialPalette encasePalette = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Boundary erosion strength for ERODED force carving.") + private double erosionStrength = DEFAULT_EROSION_STRENGTH; + + @MinNumber(MIN_EROSION_FREQUENCY) + @MaxNumber(MAX_EROSION_FREQUENCY) + @Desc("Boundary noise frequency for ERODED force carving.") + private double erosionFrequency = DEFAULT_EROSION_FREQUENCY; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Low frequency lobe wavelength for ERODED force carving. Zero derives it from the erosion frequency.") + private double lobeFrequency = 0D; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Fraction of the horizontal padding the lobes may remove for ERODED force carving. Zero keeps a uniform boundary.") + private double lobeStrength = DEFAULT_LOBE_STRENGTH; + + public IrisStructureTerrainMode resolvedMode() { + return mode == null ? IrisStructureTerrainMode.SOURCE : mode; + } + + public IrisStructureCarveShape resolvedShape() { + return shape == null ? IrisStructureCarveShape.BOX : shape; + } + + public double resolvedErosionStrength() { + if (!Double.isFinite(erosionStrength)) { + return DEFAULT_EROSION_STRENGTH; + } + return Math.max(0D, Math.min(1D, erosionStrength)); + } + + public double resolvedErosionFrequency() { + if (!Double.isFinite(erosionFrequency)) { + return DEFAULT_EROSION_FREQUENCY; + } + return Math.max(MIN_EROSION_FREQUENCY, Math.min(MAX_EROSION_FREQUENCY, erosionFrequency)); + } + + public double resolvedLobeFrequency() { + if (!Double.isFinite(lobeFrequency) || lobeFrequency <= 0D) { + return resolvedErosionFrequency() * AUTO_LOBE_FREQUENCY_RATIO; + } + return Math.min(MAX_LOBE_FREQUENCY, lobeFrequency); + } + + public double resolvedLobeStrength() { + if (!Double.isFinite(lobeStrength)) { + return DEFAULT_LOBE_STRENGTH; + } + return Math.max(0D, Math.min(1D, lobeStrength)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java new file mode 100644 index 000000000..31ea63adf --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java @@ -0,0 +1,24 @@ +package art.arcane.iris.engine.object.structure; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how terrain is integrated with a structure.") +public enum IrisStructureTerrainMode { + @Desc("Replays the registered native structure's own authored terrain adaptation (beard surface fitting, BURY/ENCAPSULATE fill, legacy template-air clearing). Does nothing for editable Iris structures, which have no source adaptation to replay.") + SOURCE, + + @Desc("Disables all terrain integration. Pieces are placed into completely unmodified terrain and may end up embedded in solid rock or floating over dips.") + PRESERVE, + + @Desc("Clears one straight axis-aligned box around the assembled pieces, expanded by horizontalPadding, ceilingPadding, and floorPadding. Ignores the carve shape and erosion settings.") + BORE, + + @Desc("Clears the padded envelope using the configured carve shape (BOX, ROUNDED, or noise-eroded ERODED) so the cavity hugs the assembled pieces instead of a straight box.") + FORCE_CARVE, + + @Desc("Raises surface terrain from processed solid rigid-template foundations at or below each authored ground plane with a 12-block falloff, even when the registered structure has no terrain adaptation. Existing higher terrain and authored air remain untouched.") + VACUUM, + + @Desc("Fills the padded piece volume with solid blocks before any piece is placed so shells, walls, and floors land in solid ground instead of pre-carved air. Only air and liquid cells are filled; existing terrain and structures are never overwritten. Native pieces then carve their own interiors.") + ENCASE +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java new file mode 100644 index 000000000..c6c50e025 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java @@ -0,0 +1,34 @@ +package art.arcane.iris.engine.object.structure; + +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("An absolute world Y band a native structure is relocated into. Reversed bounds are normalized.") +public class IrisStructureYBand { + @MinNumber(-4064) + @MaxNumber(4064) + @Desc("Lowest absolute world Y of the band.") + private int min = 0; + + @MinNumber(-4064) + @MaxNumber(4064) + @Desc("Highest absolute world Y of the band.") + private int max = 0; + + public int resolvedMin() { + return Math.min(min, max); + } + + public int resolvedMax() { + return Math.max(min, max); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java b/src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java new file mode 100644 index 000000000..9add7fdf5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java @@ -0,0 +1,33 @@ +/* + * 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.engine.object.annotations.Desc; + +@Desc("Controls how structure start positions are scattered across the world.") +public enum StructureDistribution { + @Desc("Vanilla-style spacing/separation grid. One placement attempt per grid cell, randomly offset within it by the separation. Use spacing, separation and salt.") + RANDOM_SPREAD, + + @Desc("A per-chunk probability roll, like object density. Use density (0-1).") + DENSITY, + + @Desc("Concentric rings around the world origin, like vanilla strongholds. Use rings.") + CONCENTRIC_RINGS +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java new file mode 100644 index 000000000..09bfb0b92 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how an Iris jigsaw assembly handles an optional connector branch that exhausts its primary pool and direct fallback without attaching a piece.") +public enum IrisJigsawBranchFailurePolicy { + @Desc("Fails the complete assembly when an optional connector branch cannot attach before the maximum depth.") + FAIL_ASSEMBLY, + + @Desc("Ends only the unresolved optional connector branch, matching vanilla jigsaw placement behavior.") + TERMINATE_BRANCH +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java new file mode 100644 index 000000000..b8563a4cc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Declares the resource compatibility target of an Iris jigsaw structure.") +public enum IrisJigsawCompatibility { + @Desc("Allows Iris-specific connector metadata and placement behavior.") + IRIS_EXTENDED, + + @Desc("Restricts the graph to metadata that can be represented by vanilla jigsaw resources.") + VANILLA_PORTABLE +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java new file mode 100644 index 000000000..b34a5419f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java @@ -0,0 +1,71 @@ +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.RegistryListNativeJigsawPool; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Data +@Desc("Optional overrides applied to a live vanilla, datapack, or modded jigsaw definition before Minecraft assembles it. Omitted values preserve the registered source definition.") +public class IrisJigsawConfiguration { + @Desc("Optional registered template-pool key used instead of the source jigsaw's start pool. Empty preserves the source pool.") + @RegistryListNativeJigsawPool + private String startPool = ""; + + @Desc("Optional start connector name. Empty preserves the source value; the literal NONE removes the source constraint.") + private String startJigsawName = ""; + + @MinNumber(0) + @MaxNumber(20) + @Desc("Maximum jigsaw recursion depth. Null preserves the source value.") + private Integer maxDepth = null; + + @MinNumber(1) + @MaxNumber(128) + @Desc("Exact horizontal block distance allowed from the start. Null preserves the source value.") + private Integer maxDistanceHorizontal = null; + + @MinNumber(1) + @MaxNumber(4064) + @Desc("Exact vertical block distance allowed from the start. Null preserves the source value.") + private Integer maxDistanceVertical = null; + + @Desc("Expansion-hack override. Null preserves the source value.") + private Boolean useExpansionHack = null; + + @Desc("Heightmap projection override. SOURCE preserves the registered value and NONE removes projection.") + private IrisJigsawHeightmap projectStartToHeightmap = IrisJigsawHeightmap.SOURCE; + + @MinNumber(0) + @MaxNumber(Integer.MAX_VALUE) + @Desc("Minimum distance retained above the dimension floor. Null preserves the source value.") + private Integer dimensionPaddingBottom = null; + + @MinNumber(0) + @MaxNumber(Integer.MAX_VALUE) + @Desc("Minimum distance retained below the dimension ceiling. Null preserves the source value.") + private Integer dimensionPaddingTop = null; + + @Desc("Waterlogging override. SOURCE preserves the registered value.") + private IrisJigsawLiquidSettings liquidSettings = IrisJigsawLiquidSettings.SOURCE; + + public boolean hasOverrides() { + return (startPool != null && !startPool.isBlank()) + || (startJigsawName != null && !startJigsawName.isBlank()) + || maxDepth != null + || maxDistanceHorizontal != null + || maxDistanceVertical != null + || useExpansionHack != null + || (projectStartToHeightmap != null && projectStartToHeightmap != IrisJigsawHeightmap.SOURCE) + || dimensionPaddingBottom != null + || dimensionPaddingTop != null + || (liquidSettings != null && liquidSettings != IrisJigsawLiquidSettings.SOURCE); + } +} 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 new file mode 100644 index 000000000..dc99b49cc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java @@ -0,0 +1,96 @@ +/* + * 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/IrisJigsawHeightmap.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java new file mode 100644 index 000000000..79de9f12b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java @@ -0,0 +1,30 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls whether a configured native jigsaw projects its start onto a Minecraft heightmap.") +public enum IrisJigsawHeightmap { + @Desc("Keeps the registered structure's own heightmap projection exactly as the vanilla, datapack, or mod definition declares it.") + SOURCE, + + @Desc("Removes heightmap projection entirely, so the start piece lands at the structure's literal start height instead of following terrain.") + NONE, + + @Desc("Drops the start piece onto the terrain top counting water as solid, so ocean starts sit on the water surface.") + WORLD_SURFACE_WG, + + @Desc("Identical to WORLD_SURFACE_WG in Iris worlds: the start piece rides the terrain top including water.") + WORLD_SURFACE, + + @Desc("Drops the start piece onto solid terrain, ignoring water, so ocean starts sit on the seabed.") + OCEAN_FLOOR_WG, + + @Desc("Identical to OCEAN_FLOOR_WG in Iris worlds: the start piece sits on solid ground beneath any water.") + OCEAN_FLOOR, + + @Desc("Behaves like WORLD_SURFACE in Iris worlds; the start piece sits on the terrain top including water.") + MOTION_BLOCKING, + + @Desc("Behaves like WORLD_SURFACE in Iris worlds; Iris height queries have no leaf layer to skip.") + MOTION_BLOCKING_NO_LEAVES +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java new file mode 100644 index 000000000..d6004db29 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java @@ -0,0 +1,15 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls waterlogging behavior for a configured native jigsaw.") +public enum IrisJigsawLiquidSettings { + @Desc("Keeps the registered structure's own liquid setting; vanilla defaults to applying waterlogging when the definition omits it.") + SOURCE, + + @Desc("Places pieces dry: existing water is displaced and waterloggable blocks stay unwaterlogged, leaving air-filled interiors underwater.") + IGNORE_WATERLOGGING, + + @Desc("Re-applies pre-existing water into placed waterloggable blocks and floods from neighboring sources, so underwater pieces come out waterlogged.") + APPLY_WATERLOGGING +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java new file mode 100644 index 000000000..34b79faa5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls the topology used by an Iris jigsaw structure.") +public enum IrisJigsawMode { + @Desc("A cell-aligned planar jigsaw intended for villages, paths, and other two-dimensional layouts.") + PLANAR_JIGSAW, + + @Desc("A freeform spatial connector graph intended for multi-level and three-dimensional structures.") + SPATIAL_JIGSAW +} 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 new file mode 100644 index 000000000..4e2c03202 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java @@ -0,0 +1,94 @@ +/* + * 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 new file mode 100644 index 000000000..c022d4de8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java @@ -0,0 +1,66 @@ +/* + * 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/IrisJigsawPieceRules.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java new file mode 100644 index 000000000..214cc9a4e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java @@ -0,0 +1,52 @@ +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 +@Desc("Deterministic eligibility, placement-count, and terminal-role rules for one jigsaw piece.") +@Data +public class IrisJigsawPieceRules { + @MinNumber(0) + @MaxNumber(30) + @Desc("The shallowest assembly depth at which this piece may be placed. The start piece is depth zero.") + private int minimumDepth = 0; + + @MinNumber(0) + @MaxNumber(30) + @Desc("The deepest assembly depth at which this piece may be placed.") + private int maximumDepth = 30; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The minimum number of placements required for this piece in a completed assembly.") + private int minimumPlacements = 0; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The maximum number of placements allowed for this piece. Zero means unbounded within the structure safety cap.") + private int maximumPlacements = 0; + + @Desc("Whether this piece is a physical terminal cap. A terminal piece may consume a matching connector but must not continue expansion.") + private boolean terminal = false; + + public boolean allowsDepth(int depth) { + return depth >= minimumDepth && depth <= maximumDepth; + } + + public boolean allowsPlacement(int existingPlacements) { + return existingPlacements >= 0 + && (maximumPlacements == 0 || existingPlacements < maximumPlacements); + } + + public boolean requiresMorePlacements(int existingPlacements) { + return existingPlacements >= 0 && existingPlacements < minimumPlacements; + } +} 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 new file mode 100644 index 000000000..f20ae5e0d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java @@ -0,0 +1,63 @@ +/* + * 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/IrisJigsawThemeSet.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java new file mode 100644 index 000000000..c9ea75085 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java @@ -0,0 +1,24 @@ +package art.arcane.iris.engine.object.structure.jigsaw; + +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A weighted structure-wide jigsaw theme. One declared theme is selected for an assembly, and pieces may opt into one or more themes.") +@Data +public class IrisJigsawThemeSet { + @Required + @Desc("The exact theme key referenced by jigsaw pieces.") + private String key = ""; + + @MinNumber(1) + @Desc("The relative weight used when selecting one theme for an assembly.") + private int weight = 1; +} 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 new file mode 100644 index 000000000..e998e142e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java @@ -0,0 +1,40 @@ +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 new file mode 100644 index 000000000..4275be726 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java @@ -0,0 +1,88 @@ +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/structure/jigsaw/JigsawJoint.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java new file mode 100644 index 000000000..851d5a251 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java @@ -0,0 +1,30 @@ +/* + * 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; + +@Desc("How a jigsaw connection may be rotated when matching two pieces together.") +public enum JigsawJoint { + @Desc("The connecting piece may rotate freely around the connection axis. Use this for vertical connectors (floors, ceilings) and any joint where roll does not matter.") + ROLLABLE, + + @Desc("The connecting piece's rotation is locked to face the connector. Use this for horizontal connectors where the attached piece must align to a specific facing (doorways, street ends).") + ALIGNED +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java new file mode 100644 index 000000000..22824b12b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java @@ -0,0 +1,184 @@ +/* + * 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.vanilla; + +import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; +import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.engine.object.structure.IrisStructureYBand; +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.RegistryListVanillaStructure; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Locale; +import java.util.Objects; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension (set as the dimension's 'importedStructures' field). Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris structure list ' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") +@Data +public class IrisImportedStructureControl { + @ArrayType(type = String.class, min = 1) + @RegistryListVanillaStructure(prefixes = true) + @Desc("Structure keys to deny explicitly, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' disables every village variant and 'minecraft:ruined_portal' disables every ruined portal. Every key not matched here remains enabled.") + private KList disabled = new KList<>(); + + @ArrayType(type = String.class, min = 1) + @RegistryListVanillaStructure(prefixes = false) + @Desc("Exact structure keys to deny after trimming and case normalization. Unlike 'disabled', entries never match key families, so 'minecraft:ruined_portal' does not disable 'minecraft:ruined_portal_nether'.") + private KList disabledExact = new KList<>(); + + @MinNumber(-512) + @MaxNumber(512) + @Desc("Vertical block offset applied only to UNDERGROUND vanilla structures (the UNDERGROUND_STRUCTURES, UNDERGROUND_DECORATION, and STRONGHOLDS generation steps: strongholds, trial chambers, mineshafts, ancient cities, etc.). Surface structures (villages, outposts, etc.) are never shifted. Use a negative value to push deep structures lower when your dimension's sea/terrain level differs from vanilla's (e.g. -64 if you lowered the fluid height to 0). 0 = no shift.") + private int undergroundYShift = 0; + + @Desc("Controls whether ingested datapacks may replace minecraft-namespaced structure definitions, sets, pools, and templates. When false, those overrides are stripped from installed datapack copies so vanilla definitions stay intact. Non-minecraft structures from datapacks and mods remain governed by disabled because namespace alone cannot identify their origin. Resolved globally across loaded packs: if any dimension sets this false, minecraft-namespaced overrides are stripped from every installed datapack copy.") + private boolean datapackOverrides = true; + + @ArrayType(type = IrisStructureSetFrequencyOverride.class, min = 1) + @Desc("Exact registered structure-set frequency overrides for native generation. The last entry for a normalized structure-set key wins. These do not convert native structures into Iris placements and affect only newly generated chunks.") + private KList frequencyOverrides = new KList<>(); + + @ArrayType(type = IrisVanillaStructureAdjustment.class, min = 1) + @Desc("Per-structure adjustments applied to vanilla, mod, and datapack structures that still generate natively. Vertical shifts from every matching entry stack. A matching preserveSourceY option disables Iris burial repositioning for that structure. The last matching entry with stilt settings controls foundation columns, and likewise for terrain and yBand settings. A structure suppressed by an Iris placement is unaffected.") + private KList adjustments = new KList<>(); + + public boolean shouldGenerate(String key) { + return key != null && !key.isBlank() + && !matches(disabled, key) + && !matchesExact(disabledExact, key); + } + + public IrisNativeStructureDecision resolve(String key, boolean undergroundStep) { + KList activeAdjustments = Objects.requireNonNull( + adjustments, "importedStructures.adjustments must not be null"); + int y = undergroundStep ? undergroundYShift : 0; + boolean preserveSourceY = false; + IrisStructureStiltSettings stilt = null; + IrisStructureTerrain terrain = null; + IrisStructureYBand yBand = null; + for (IrisVanillaStructureAdjustment adjustment : activeAdjustments) { + if (adjustment != null && adjustment.matches(key)) { + y += adjustment.getYShift(); + preserveSourceY |= adjustment.isPreserveSourceY(); + if (adjustment.getStilt() != null) { + stilt = adjustment.getStilt(); + } + if (adjustment.getTerrain() != null) { + terrain = adjustment.getTerrain(); + } + if (adjustment.getYBand() != null) { + yBand = adjustment.getYBand(); + } + } + } + return new IrisNativeStructureDecision( + generationStatus(key), y, yBand, preserveSourceY, stilt, terrain); + } + + public double frequencyMultiplier(String structureSetKey) { + KList activeOverrides = Objects.requireNonNull( + frequencyOverrides, "importedStructures.frequencyOverrides must not be null"); + String normalizedKey = normalizeKey(structureSetKey); + if (normalizedKey.isEmpty()) { + return 1D; + } + double multiplier = 1D; + for (IrisStructureSetFrequencyOverride override : activeOverrides) { + if (override != null && normalizeKey(override.getStructureSet()).equals(normalizedKey)) { + multiplier = override.getMultiplier(); + } + } + return multiplier; + } + + public boolean hasFrequencyOverrides() { + return !Objects.requireNonNull( + frequencyOverrides, "importedStructures.frequencyOverrides must not be null").isEmpty(); + } + + private NativeStructureGenerationStatus generationStatus(String key) { + if (key == null || key.isBlank()) { + return NativeStructureGenerationStatus.INVALID_REGISTRY_KEY; + } + if (matches(disabled, key) || matchesExact(disabledExact, key)) { + return NativeStructureGenerationStatus.DISABLED_BY_PACK; + } + return NativeStructureGenerationStatus.GENERATE_NATIVE; + } + + private boolean matches(KList list, String key) { + if (key == null) { + return false; + } + KList activeList = Objects.requireNonNull( + list, "importedStructures.disabled must not be null"); + for (String entry : activeList) { + if (matchesKey(entry, key)) { + return true; + } + } + return false; + } + + private boolean matchesExact(KList list, String key) { + KList activeList = Objects.requireNonNull( + list, "importedStructures.disabledExact must not be null"); + String normalizedKey = normalizeKey(key); + for (String entry : activeList) { + String normalizedEntry = normalizeKey(entry); + if (!normalizedEntry.isEmpty() && normalizedEntry.equals(normalizedKey)) { + return true; + } + } + return false; + } + + public static boolean matchesKey(String pattern, String key) { + if (pattern == null || key == null) { + return false; + } + String normalizedPattern = pattern.trim().toLowerCase(Locale.ROOT); + String normalizedKey = key.trim().toLowerCase(Locale.ROOT); + if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { + return false; + } + if (normalizedKey.length() == normalizedPattern.length()) { + return true; + } + char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); + if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { + return true; + } + char boundary = normalizedKey.charAt(normalizedPattern.length()); + return boundary == '/' || boundary == '_'; + } + + private static String normalizeKey(String key) { + return key == null ? "" : key.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java new file mode 100644 index 000000000..f4f4c8fdb --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java @@ -0,0 +1,30 @@ +package art.arcane.iris.engine.object.structure.vanilla; + +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.MinNumber; +import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; +import art.arcane.iris.engine.object.annotations.Required; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Data +@Desc("A live vanilla, datapack, or modded structure generated by Minecraft at an Iris-controlled placement.") +public class IrisNativeStructure { + @Required + @RegistryListVanillaStructure + @Desc("Registered structure key. The source retains its native generator, pieces, templates, processors, entities, markers, and data.") + private String structure = ""; + + @MinNumber(1) + @Desc("Relative selection weight when a placement offers multiple native structure sources.") + private int weight = 1; + + @Desc("Optional jigsaw-only assembly overrides. Null preserves the complete registered structure definition.") + private IrisJigsawConfiguration jigsaw = null; +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java new file mode 100644 index 000000000..cadbd1dc7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java @@ -0,0 +1,40 @@ +/* + * 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.object.structure.vanilla; + +import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; +import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.engine.object.structure.IrisStructureYBand; +public record IrisNativeStructureDecision( + NativeStructureGenerationStatus status, + int yShift, + IrisStructureYBand yBand, + boolean preserveSourceY, + IrisStructureStiltSettings stilt, + IrisStructureTerrain terrain +) { + public boolean generate() { + return status == NativeStructureGenerationStatus.GENERATE_NATIVE; + } + + public IrisNativeStructureDecision withStatus(NativeStructureGenerationStatus replacement) { + return new IrisNativeStructureDecision( + replacement, yShift, yBand, preserveSourceY, stilt, terrain); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java new file mode 100644 index 000000000..516d36d28 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java @@ -0,0 +1,44 @@ +/* + * 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.structure.vanilla; + +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.RegistryListVanillaStructureSet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("An exact registered structure-set frequency multiplier. Iris retains the set's structures, weights, biome eligibility, placement algorithm, salt, exclusion zone, starts, processors, mobs, loot, and locate behavior while scaling only its native placement density.") +@Data +public class IrisStructureSetFrequencyOverride { + @RegistryListVanillaStructureSet + @Desc("Exact registered structure-set key, for example 'minecraft:nether_complexes'. Structure keys such as 'minecraft:fortress' are not valid here.") + private String structureSet = ""; + + @MinNumber(0.01) + @MaxNumber(16) + @Desc("Requested placement-density multiplier. Random-spread sets scale their placement frequency first and then their integer chunk spacing; integer spacing and separation constraints can make the realized increase slightly lower or higher. The default 1 leaves the registered placement unchanged.") + private double multiplier = 1D; +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java new file mode 100644 index 000000000..3104537a5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java @@ -0,0 +1,71 @@ +/* + * 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.vanilla; + +import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; +import art.arcane.iris.engine.object.structure.IrisStructureTerrain; +import art.arcane.iris.engine.object.structure.IrisStructureYBand; +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.RegistryListVanillaStructure; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A per-structure adjustment applied to vanilla, mod, and datapack structures that still generate natively (those NOT suppressed by an Iris 'structures' placement). Vertical shifts move the structure start, pieces, bounds, and jigsaw metadata together before references and placement. Intersecting trees are cleared automatically inside structure piece envelopes; optional postprocessing can build palette-driven foundation columns.") +@Data +public class IrisVanillaStructureAdjustment { + @ArrayType(type = String.class, min = 1) + @RegistryListVanillaStructure(prefixes = true) + @Desc("Structure keys this adjustment applies to, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' adjusts every village variant and 'minecraft:ruined_portal' adjusts every ruined portal. Empty matches nothing.") + private KList match = new KList<>(); + + @MinNumber(-512) + @MaxNumber(512) + @Desc("Vertical block offset. Negative pushes the structure down, positive lifts it. The resolved shift is clamped so the structure remains inside the world's vertical build bounds.") + private int yShift = 0; + + @Desc("Optional absolute world Y band. The structure is relocated so its vertical midpoint lands inside the band, deterministically from its start chunk and clamped to the world's build bounds. Precedence: preserveSourceY wins over yBand, and yBand wins over both yShift and Iris burial repositioning. Structures with a fixed vanilla alignment (ocean monument sea level, desert and jungle pyramid surface fit) ignore it.") + private IrisStructureYBand yBand = null; + + @Desc("When true, skip Iris burial repositioning so the structure keeps the Y its own vanilla placement chose. Underground structures are otherwise pushed below the lowest solid column across their whole footprint, which hides terrain-aware structures such as mineshafts that intentionally breach cliffs and surfaces. Vertical shifts still apply on top of the preserved Y: this dimension's undergroundYShift plus every matching adjustment's yShift.") + private boolean preserveSourceY = false; + + @Desc("Optional foundation columns placed beneath the native structure piece bases after placement.") + private IrisStructureStiltSettings stilt = null; + + @Desc("Optional terrain integration override. VACUUM raises surface terrain from processed solid rigid-template foundations at or below each authored ground plane with a 12-block falloff without lowering existing ground. BORE and FORCE_CARVE clear every intersecting chunk before native pieces are placed, while ENCASE fills it with solid blocks instead. Left unset, SOURCE replays the registered structure's authored terrain adaptation, including surface fitting, burial, and encapsulation.") + private IrisStructureTerrain terrain = null; + + public boolean matches(String key) { + for (String entry : match) { + if (IrisImportedStructureControl.matchesKey(entry, key)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java new file mode 100644 index 000000000..befae80d4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java @@ -0,0 +1,26 @@ +/* + * 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.structure.vanilla; + +public enum NativeStructureGenerationStatus { + GENERATE_NATIVE, + DISABLED_BY_PACK, + REPLACED_BY_IRIS, + INVALID_REGISTRY_KEY +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java new file mode 100644 index 000000000..35051cc68 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java @@ -0,0 +1,12 @@ +package art.arcane.iris.engine.object.structure.vanilla; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls whether an Iris structure placement suppresses its imported native source.") +public enum NativeStructureSuppression { + @Desc("Leaves native generation enabled alongside this Iris structure placement.") + NONE, + + @Desc("Suppresses the structure's vanillaSource when used by a validated dimension-level replacement placement.") + REPLACE_SOURCE +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java new file mode 100644 index 000000000..5a976aaa6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java @@ -0,0 +1,360 @@ +/* + * 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.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisSlopeClip; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +/** + * Layer (block palette) generation for {@link IrisBiome}. IrisBiome is Gson deserialized from pack + * JSON, so its fields stay put and only the behavior lives here. + */ +public final class IrisBiomeLayerGenerator { + private static final class States { + private static final PlatformBlockState BARRIER = B.getState("BARRIER"); + } + + private IrisBiomeLayerGenerator() { + } + + public static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { + if (biome.isLockLayers()) { + return generateLockedLayers(biome, wx, wz, random, maxDepth, height, rdata, complex); + } + + KList data = new KList<>(); + + if (maxDepth <= 0) { + return data; + } + + KList layers = biome.getLayers(); + int layerCount = layers.size(); + + if (layerCount <= 0) { + return data; + } + + KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); + + for (int i = 0; i < layerCount; i++) { + IrisBiomePaletteLayer layer = layers.get(i); + double zoom = layer.getZoom(); + CNG hgen = heightGenerators.get(i); + double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); + + IrisSlopeClip sc = layer.getSlopeCondition(); + + if (!sc.isDefault()) { + if (!sc.isValid(complex.getSlopeStream().get(wx, wz))) { + d = 0; + } + } + + if (d <= 0) { + continue; + } + + for (int j = 0; j < d; j++) { + if (data.size() >= maxDepth) { + break; + } + + try { + data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + if (data.size() >= maxDepth) { + break; + } + + if (dim.isExplodeBiomePalettes()) { + for (int j = 0; j < dim.getExplodeBiomePaletteSize(); j++) { + data.add(States.BARRIER); + + if (data.size() >= maxDepth) { + break; + } + } + } + } + + return data; + } + + public static KList generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { + KList data = new KList<>(); + + if (maxDepth <= 0) { + return data; + } + + KList ceilingLayers = biome.getCaveCeilingLayers(); + int layerCount = ceilingLayers.size(); + + if (layerCount <= 0) { + return data; + } + + KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); + // Ceiling layers reuse the surface-layer height generators, so entries beyond layers.size() have no generator; skip them. + int usableLayers = Math.min(layerCount, heightGenerators.size()); + + for (int i = 0; i < usableLayers; i++) { + IrisBiomePaletteLayer layer = ceilingLayers.get(i); + double zoom = layer.getZoom(); + CNG hgen = heightGenerators.get(i); + double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); + + if (d <= 0) { + continue; + } + + for (int j = 0; j < d; j++) { + if (data.size() >= maxDepth) { + break; + } + + try { + data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + if (data.size() >= maxDepth) { + break; + } + + if (dim.isExplodeBiomePalettes()) { + for (int j = 0; j < dim.getExplodeBiomePaletteSize(); j++) { + data.add(States.BARRIER); + + if (data.size() >= maxDepth) { + break; + } + } + } + } + + return data; + } + + public static KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { + KList data = new KList<>(); + KList real = new KList<>(); + int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax()); + if (maxDepth <= 0) { + return data; + } + + KList layers = biome.getLayers(); + int layerCount = layers.size(); + + if (layerCount > 0) { + KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); + + for (int i = 0; i < layerCount; i++) { + IrisBiomePaletteLayer layer = layers.get(i); + double zoom = layer.getZoom(); + CNG hgen = heightGenerators.get(i); + double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); + + IrisSlopeClip sc = layer.getSlopeCondition(); + + if (!sc.isDefault()) { + if (!sc.isValid(complex.getSlopeStream().get(wx, wz))) { + d = 0; + } + } + + if (d <= 0) { + continue; + } + + for (int j = 0; j < d; j++) { + try { + data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + } + } + + if (data.isEmpty()) { + return real; + } + + for (int i = 0; i < maxDepth; i++) { + int offset = (512 - height) - i; + int index = offset % data.size(); + real.add(data.get(Math.max(index, 0))); + } + + return real; + } + + public static KList generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) { + KList data = new KList<>(); + + KList seaLayers = biome.getSeaLayers(); + int layerCount = seaLayers.size(); + + if (layerCount <= 0) { + return data; + } + + KList heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata); + + for (int i = 0; i < layerCount; i++) { + IrisBiomePaletteLayer layer = seaLayers.get(i); + double zoom = layer.getZoom(); + CNG hgen = heightGenerators.get(i); + int d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); + + if (d < 0) { + continue; + } + + for (int j = 0; j < d; j++) { + if (data.size() >= maxDepth) { + break; + } + + try { + data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + if (data.size() >= maxDepth) { + break; + } + } + + return data; + } + + public static KList getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) { + AtomicCache> cache = biome.getLayerHeightGenerators(); + KList cached = cache.getIfPresent(); + + if (cached != null) { + return cached; + } + + return cache.aquire(() -> + { + KList layerHeightGenerators = new KList<>(); + + int m = 7235; + + for (IrisBiomePaletteLayer i : biome.getLayers()) { + layerHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), rdata)); + } + + return layerHeightGenerators; + }); + } + + public static KList getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) { + AtomicCache> cache = biome.getLayerSeaHeightGenerators(); + KList cached = cache.getIfPresent(); + + if (cached != null) { + return cached; + } + + return cache.aquire(() -> + { + KList layerSeaHeightGenerators = new KList<>(); + + int m = 7735; + + for (IrisBiomePaletteLayer i : biome.getSeaLayers()) { + layerSeaHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), data)); + } + + return layerSeaHeightGenerators; + }); + } + + public static PlatformBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, IrisData idm) { + KList layers = biome.getLayers(); + + if (layers.isEmpty()) { + return B.getState("AIR"); + } + + return layers.get(0).get(rng, x, 0, z, idm); + } + + public static int getMaxHeight(IrisBiome biome, Engine engine) { + return biome.getMaxHeight().aquire(() -> + { + int maxHeight = 0; + + for (IrisBiomeGeneratorLink i : biome.getGenerators()) { + maxHeight += i.getMax(); + } + + return maxHeight; + }); + } + + public static int getMaxWithObjectHeight(IrisBiome biome, IrisData data, Engine engine) { + return biome.getMaxWithObjectHeight().aquire(() -> + { + int maxHeight = 0; + + for (IrisBiomeGeneratorLink i : biome.getGenerators()) { + maxHeight += i.getMax(); + } + + int gg = 0; + + for (IrisObjectPlacement i : biome.getObjects()) { + for (IrisObject j : data.getObjectLoader().loadAll(i.getPlace())) { + gg = Math.max(gg, j.getH()); + } + } + + return maxHeight + gg + 3; + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java new file mode 100644 index 000000000..86e9120a4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java @@ -0,0 +1,165 @@ +/* + * 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.material.IrisBlockData; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.placement.IrisSlopeClip; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +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.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.util.project.noise.CNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Snippet("biome-palette") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("A layer of surface / subsurface material in biomes") +@Data +public class IrisBiomePaletteLayer { + private final transient AtomicCache> blockData = new AtomicCache<>(); + private final transient AtomicCache layerGenerator = new AtomicCache<>(); + private final transient AtomicCache heightGenerator = new AtomicCache<>(); + @Desc("The style of noise") + private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); + @DependsOn({"minHeight", "maxHeight"}) + @MinNumber(0) + @MaxNumber(2032) + + @Desc("The min thickness of this layer") + private int minHeight = 1; + @DependsOn({"minHeight", "maxHeight"}) + @MinNumber(1) + @MaxNumber(2032) + + @Desc("The max thickness of this layer") + private int maxHeight = 1; + @Desc("If set, this layer only shows where the terrain slope is within these bounds; outside them the layer is skipped entirely. Thickness is not scaled by slope.") + private IrisSlopeClip slopeCondition = new IrisSlopeClip(); + @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("GRASS_BLOCK")); + + public CNG getHeightGenerator(RNG rng, IrisData data) { + CNG cached = heightGenerator.getIfPresent(); + + if (cached != null) { + return cached; + } + + return heightGenerator.aquire(() -> CNG.signature(rng.nextParallelRNG(minHeight * maxHeight + getBlockData(data).size()))); + } + + public PlatformBlockState get(RNG rng, double x, double y, double z, IrisData data) { + return get(rng, 0, x, y, z, data); + } + + /** + * Resolves a block for this layer without allocating a child RNG per call. The child RNG is + * only built inside the lazy layer generator initializer, using the exact same seed derivation + * as {@code parent.nextParallelRNG(signature)} followed by the generator signature. + */ + public PlatformBlockState get(RNG parent, int signature, double x, double y, double z, IrisData data) { + KList localBlockData = getBlockData(data); + + if (localBlockData.isEmpty()) { + return null; + } + + if (localBlockData.size() == 1) { + return localBlockData.get(0); + } + + double localZoom = zoom; + double scaledX = x / localZoom; + double scaledY = y / localZoom; + double scaledZ = z / localZoom; + return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ); + } + + public CNG getLayerGenerator(RNG rng, IrisData data) { + return getLayerGenerator(rng, 0, data); + } + + public CNG getLayerGenerator(RNG parent, int signature, IrisData data) { + CNG cached = layerGenerator.getIfPresent(); + + if (cached != null) { + return cached; + } + + return layerGenerator.aquire(() -> + { + RNG rngx = parent.nextParallelRNG(signature).nextParallelRNG(minHeight + maxHeight + getBlockData(data).size()); + return style.create(rngx, data); + }); + } + + public KList add(String b) { + palette.add(new IrisBlockData(b)); + + return palette; + } + + public KList getBlockData(IrisData data) { + KList cached = blockData.getIfPresent(); + + if (cached != null) { + return cached; + } + + return blockData.aquire(() -> + { + KList blockData = new KList<>(); + for (IrisBlockData ix : palette) { + PlatformBlockState bx = ix.getBlockData(data); + if (bx != null) { + for (int i = 0; i < ix.getWeight(); i++) { + blockData.add(bx); + } + } + } + + return blockData; + }); + } + + public IrisBiomePaletteLayer zero() { + palette.clear(); + return this; + } +} 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 new file mode 100644 index 000000000..a1b940df0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java @@ -0,0 +1,258 @@ +/* + * 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.iris.engine.data.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/terrain/carving/CarveResult.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarveResult.java new file mode 100644 index 000000000..3549f586d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarveResult.java @@ -0,0 +1,34 @@ +/* + * 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.carving; + +import lombok.Value; + +@SuppressWarnings("ClassCanBeRecord") +@Value +public class CarveResult { + @SuppressWarnings("RedundantModifiersValueLombok") + private final int surface; + @SuppressWarnings("RedundantModifiersValueLombok") + private final int ceiling; + + public int getHeight() { + return ceiling - surface; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java new file mode 100644 index 000000000..7d5aca7c2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java @@ -0,0 +1,43 @@ +/* + * 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.carving; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Defines if an object is allowed to place in carvings, surfaces or both.") +public enum CarvingMode { + @Desc("Only place this object on surfaces (NOT under carvings)") + SURFACE_ONLY, + + @Desc("Only place this object under carvings (NOT on the surface)") + CARVING_ONLY, + + @Desc("This object can place anywhere") + ANYWHERE; + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean supportsCarving() { + return this.equals(ANYWHERE) || this.equals(CARVING_ONLY); + } + + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean supportsSurface() { + return this.equals(ANYWHERE) || this.equals(SURFACE_ONLY); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java new file mode 100644 index 000000000..ecf7aaac3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveResult.java @@ -0,0 +1,36 @@ +/* + * 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.carving; + +import lombok.Data; + +@Data +public class CaveResult { + private int floor; + private int ceiling; + + public CaveResult(int floor, int ceiling) { + this.floor = floor; + this.ceiling = ceiling; + } + + public boolean isWithin(int v) { + return v > floor || v < ceiling; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java new file mode 100644 index 000000000..a66f57a13 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java @@ -0,0 +1,21 @@ +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Defines which carved-space anchor to target for cave object placement.") +public enum IrisCaveAnchorMode { + @Desc("Use the active cave profile default anchor mode.") + PROFILE_DEFAULT, + + @Desc("Target cave floor anchors where carved space has solid support below.") + FLOOR, + + @Desc("Target cave ceiling anchors where carved space has solid support above.") + CEILING, + + @Desc("Target carved positions with no immediate solid support above or below.") + CENTER, + + @Desc("Target any carved-space anchor.") + ANY +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java new file mode 100644 index 000000000..7c5b700d2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java @@ -0,0 +1,39 @@ +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.value.IrisRange; +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 lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("cave-field-module") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a modular cave-density layer.") +@Data +public class IrisCaveFieldModule { + @Desc("Density style used by this module.") + private IrisGeneratorStyle style = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @MinNumber(0) + @Desc("Layer contribution multiplier.") + private double weight = 1; + + @MinNumber(-1) + @MaxNumber(1) + @Desc("Threshold offset applied to this layer before blending.") + private double threshold = 0; + + @Desc("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private IrisRange verticalRange = new IrisRange(0, 384); + + @Desc("Invert this module before weighting.") + private boolean invert = false; +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java new file mode 100644 index 000000000..4cbd9c7ab --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java @@ -0,0 +1,153 @@ +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.IrisStyledRange; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.value.IrisRange; +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.Snippet; +import art.arcane.volmlib.util.collection.KList; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("cave-profile") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a configurable 3D cave profile.") +@Data +public class IrisCaveProfile { + @Desc("Enable profile-driven cave carving.") + private boolean enabled = false; + + @Desc("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private IrisRange verticalRange = new IrisRange(0, 384); + + @MinNumber(0) + @MaxNumber(128) + @Desc("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.") + private int verticalEdgeFade = 20; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Strength of the vertical edge fade at cave profile min/max bounds.") + private double verticalEdgeFadeStrength = 0.18; + + @Desc("Base density style for cave field generation.") + private IrisGeneratorStyle baseDensityStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @Desc("Detail density style blended into base caves.") + private IrisGeneratorStyle detailDensityStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); + + @Desc("Warp style used to distort cave coordinates.") + private IrisGeneratorStyle warpStyle = new IrisGeneratorStyle(NoiseStyle.FLAT); + + @MinNumber(0) + @Desc("Base cave field multiplier.") + private double baseWeight = 1; + + @MinNumber(0) + @Desc("Detail cave field multiplier.") + private double detailWeight = 0.35; + + @MinNumber(0) + @Desc("Coordinate warp strength for cave fields.") + private double warpStrength = 0; + + @Desc("Threshold range used for carve cutoff decisions.") + private IrisStyledRange densityThreshold = new IrisStyledRange(-0.2, 0.2, NoiseStyle.CELLULAR_IRIS_DOUBLE.style()); + + @MinNumber(0) + @MaxNumber(1) + @Desc("Extra threshold bias subtracted from sampled threshold before carve tests.") + private double thresholdBias = 0.16; + + @MinNumber(1) + @MaxNumber(8) + @Desc("Vertical sample step used while evaluating cave density.") + private int sampleStep = 1; + + @Desc("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.") + private boolean adaptiveSampling = true; + + @MinNumber(2) + @MaxNumber(4) + @Desc("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.") + private int adaptiveSampleStep = 2; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.") + private double adaptiveThresholdMargin = 0.04; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum solid clearance below terrain surface where carving may occur.") + private int surfaceClearance = 4; + + @Desc("Allow profile-driven cave carving to break through terrain surface in selected columns.") + private boolean allowSurfaceBreak = true; + + @Desc("Noise style used to decide where surface-breaking cave columns are allowed.") + private IrisGeneratorStyle surfaceBreakStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.08); + + @MinNumber(-1) + @MaxNumber(1) + @Desc("Minimum signed surface-break noise value required before near-surface carving is allowed.") + private double surfaceBreakNoiseThreshold = 0.62; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Near-surface depth window used for surface-break carve logic.") + private int surfaceBreakDepth = 18; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Additional threshold boost applied while carving in the surface-break depth window.") + private double surfaceBreakThresholdBoost = 0.2; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum depth below terrain surface required for cave-only object anchor placement.") + private int objectMinDepthBelowSurface = 6; + + @ArrayType(type = IrisCaveFieldModule.class, min = 1) + @Desc("Additional layered cave-density modules.") + private KList modules = new KList<>(); + + @Desc("Default cave anchor mode for cave-only object placement.") + private IrisCaveAnchorMode defaultObjectAnchor = IrisCaveAnchorMode.FLOOR; + + @Desc("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.") + private ObjectPlaceMode defaultObjectPlaceMode = null; + + @MinNumber(1) + @MaxNumber(8) + @Desc("Vertical scan step used while searching cave anchors.") + private int anchorScanStep = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("Maximum random column retries while searching a valid cave object anchor in the chunk.") + private int anchorSearchAttempts = 6; + + @Desc("Allow cave fluid placement from the dimension fluid palette below fluid level.") + private boolean allowFluid = true; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum depth below terrain surface required before cave fluid may be placed.") + private int fluidMinDepthBelowSurface = 12; + + @Desc("Require solid floor support below cave fluid to reduce unsupported fluid flows.") + private boolean fluidRequiresFloor = true; + + @Desc("Allow cave lava placement based on lava height.") + private boolean allowLava = true; +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java new file mode 100644 index 000000000..490fa0840 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java @@ -0,0 +1,166 @@ +/* + * 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.carving; + +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; + +public final class IrisCaveProfileSampler { + private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; + + private final IrisData data; + private final IrisCaveProfile profile; + private final CNG baseDensity; + private final CNG detailDensity; + private final CNG warpDensity; + private final RNG thresholdRng; + private final ModuleState[] modules; + private final double inverseNormalization; + private final double baseWeight; + private final double detailWeight; + private final double warpStrength; + private final boolean enabled; + private final boolean hasWarp; + private final boolean hasModules; + + public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) { + this.data = engine.getData(); + this.profile = profile; + List moduleStates = new ArrayList<>(); + RNG baseRng = new RNG(engine.getSeedManager().getCarve()); + this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); + this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); + this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); + this.thresholdRng = baseRng.nextParallelRNG(489_112); + this.baseWeight = profile.getBaseWeight(); + this.detailWeight = profile.getDetailWeight(); + this.warpStrength = profile.getWarpStrength(); + this.hasWarp = warpStrength > 0D; + + double weight = Math.abs(baseWeight) + Math.abs(detailWeight); + int index = 0; + for (IrisCaveFieldModule module : profile.getModules()) { + CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + ModuleState state = new ModuleState(module, moduleDensity); + moduleStates.add(state); + weight += Math.abs(state.weight); + index++; + } + + this.modules = moduleStates.toArray(new ModuleState[0]); + double normalization = weight <= 0 ? 1D : weight; + this.inverseNormalization = 1D / normalization; + this.hasModules = modules.length > 0; + this.enabled = profile.isEnabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); + } + + public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { + if (!enabled) { + return false; + } + + double threshold = profile.getDensityThreshold().get(thresholdRng, x, z, data) - profile.getThresholdBias(); + threshold += floatingThresholdBias(floatingCarveThreshold); + return sampleDensity(x, y, z) <= threshold; + } + + double sampleDensity(int x, int y, int z) { + if (hasWarp) { + return sampleDensityWarped(x, y, z); + } + + return sampleDensityUnwarped(x, y, z); + } + + private double sampleDensityUnwarped(int x, int y, int z) { + double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + if (hasModules) { + for (ModuleState module : modules) { + if (!module.isActive(y)) { + continue; + } + + density += module.sample(x, y, z); + } + } + + return density * inverseNormalization; + } + + private double sampleDensityWarped(int x, int y, int z) { + double warpA = warpDensity.noiseFastSigned3D(x, y, z); + double warpB = warpDensity.noiseFastSigned3D(x + 31.37D, y - 17.21D, z + 23.91D); + double warpedX = x + (warpA * warpStrength); + double warpedY = y + (warpB * warpStrength); + double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); + double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + if (hasModules) { + for (ModuleState module : modules) { + if (!module.isActive(y)) { + continue; + } + + density += module.sample(warpedX, warpedY, warpedZ); + } + } + + return density * inverseNormalization; + } + + private double floatingThresholdBias(double floatingCarveThreshold) { + double clamped = Math.max(0D, Math.min(1D, floatingCarveThreshold)); + return (1D - clamped) * FLOATING_THRESHOLD_BIAS_SCALE; + } + + private static final class ModuleState { + private final CNG density; + private final int minY; + private final int maxY; + private final double weight; + private final double threshold; + private final boolean invert; + + private ModuleState(IrisCaveFieldModule module, CNG density) { + IrisRange range = module.getVerticalRange(); + this.density = density; + this.minY = (int) Math.floor(range.getMin()); + this.maxY = (int) Math.ceil(range.getMax()); + this.weight = module.getWeight(); + this.threshold = module.getThreshold(); + this.invert = module.isInvert(); + } + + private boolean isActive(int y) { + return density != null && y >= minY && y <= maxY; + } + + private double sample(double x, double y, double z) { + double sampled = density.noiseFastSigned3D(x, y, z); + return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java new file mode 100644 index 000000000..6256fc281 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java @@ -0,0 +1,84 @@ +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.DependsOn; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@Snippet("dimension-carving-entry") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Dimension-level cave biome override with absolute world Y bounds.") +@Data +public class IrisDimensionCarvingEntry { + private final transient AtomicCache realBiome = new AtomicCache<>(true); + private final transient Map childGenerators = new ConcurrentHashMap<>(); + + @Desc("Stable id for this carving entry") + private String id = ""; + + @Desc("Enable or disable this carving entry") + private boolean enabled = true; + + @RegistryListResource(IrisBiome.class) + @Desc("Cave biome to apply when world Y falls within worldYRange") + private String biome = ""; + + @Desc("Absolute world Y bounds where this carving entry applies") + private IrisRange worldYRange = new IrisRange(-64, 320); + + @DependsOn({"children"}) + @Desc("If this carving entry has child carving entries, this controls how small those child carving patches are.") + private double childShrinkFactor = 1.5; + + @DependsOn({"children"}) + @Desc("If this carving entry has child carving entries, this controls the shape pattern used to pick them.") + private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @ArrayType(min = 1, type = String.class) + @Desc("Child carving entry ids. Child ids can point back to parent ids to create cycles; recursion is bounded by childRecursionDepth.") + private KList children = new KList<>(); + + @Desc("Maximum recursion depth when resolving child carving entries from this entry.") + private int childRecursionDepth = 3; + + public IrisBiome getRealBiome(IrisData data) { + return realBiome.aquire(() -> { + String biomeKey = getBiome(); + if (biomeKey == null || biomeKey.isBlank()) { + return null; + } + + return data.getBiomeLoader().load(biomeKey.trim()); + }); + } + + public CNG getChildrenGenerator(long seed, IrisData data) { + String entryId = getId(); + long idHash = entryId == null ? 0L : entryId.trim().hashCode(); + long generatorSeed = seed ^ (idHash << 32) ^ 2137L; + return childGenerators.computeIfAbsent(generatorSeed, key -> { + double scale = Math.max(0.0001D, getChildShrinkFactor()); + RNG random = new RNG(key); + return getChildStyle().create(random.nextParallelRNG(2137), data).bake().scale(scale).bake(); + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java new file mode 100644 index 000000000..951b70fe9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java @@ -0,0 +1,375 @@ +package art.arcane.iris.engine.object.terrain.carving; + +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.util.project.interpolation.IrisInterpolation; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.util.project.noise.CNG; + +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +public final class IrisDimensionCarvingResolver { + private static final int MAX_CHILD_DEPTH = 32; + private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; + private static final ThreadLocal> THREAD_STATE = + ThreadLocal.withInitial(() -> new WeakReference<>(null)); + + private IrisDimensionCarvingResolver() { + + } + + public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY) { + return resolveRootEntry(engine, worldY, threadState()); + } + + public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { + State resolvedState = state == null ? threadState() : state; + resolvedState.bind(engine); + if (resolvedState.rootEntriesByWorldY.containsKey(worldY)) { + return resolvedState.rootEntriesByWorldY.get(worldY); + } + + IrisDimension dimension = engine.getDimension(); + List entries = dimension.getCarving(); + if (entries == null || entries.isEmpty()) { + resolvedState.rootEntriesByWorldY.put(worldY, null); + return null; + } + + IrisDimensionCarvingEntry resolved = null; + for (IrisDimensionCarvingEntry entry : entries) { + if (!isRootCandidate(engine, entry, worldY, resolvedState)) { + continue; + } + + resolved = entry; + } + + resolvedState.rootEntriesByWorldY.put(worldY, resolved); + return resolved; + } + + public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldZ) { + return resolveFromRoot(engine, rootEntry, worldX, worldZ, threadState()); + } + + public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldZ, State state) { + State resolvedState = state == null ? threadState() : state; + resolvedState.bind(engine); + if (rootEntry == null) { + return null; + } + + IrisBiome rootBiome = resolveEntryBiome(engine, rootEntry, resolvedState); + if (rootBiome == null) { + return null; + } + + int remainingDepth = clampDepth(rootEntry.getChildRecursionDepth()); + if (remainingDepth <= 0) { + return rootEntry; + } + + Map entryIndex = resolveEntryIndex(engine, resolvedState); + IrisDimensionCarvingEntry current = rootEntry; + int depth = remainingDepth; + while (depth > 0) { + IrisDimensionCarvingEntry selected = selectChild(engine, current, worldX, worldZ, entryIndex, resolvedState); + if (selected == null || selected == current) { + break; + } + + depth--; + int childDepthLimit = clampDepth(selected.getChildRecursionDepth()); + if (childDepthLimit < depth) { + depth = childDepthLimit; + } + current = selected; + } + + return current; + } + + public static IrisBiome resolveEntryBiome(Engine engine, IrisDimensionCarvingEntry entry) { + return resolveEntryBiome(engine, entry, null); + } + + public static IrisBiome resolveEntryBiome(Engine engine, IrisDimensionCarvingEntry entry, State state) { + if (entry == null) { + return null; + } + + if (state == null) { + return entry.getRealBiome(engine.getData()); + } + + state.bind(engine); + if (state.biomeCache.containsKey(entry)) { + return state.biomeCache.get(entry); + } + + IrisBiome biome = entry.getRealBiome(engine.getData()); + state.biomeCache.put(entry, biome); + return biome; + } + + private static boolean isRootCandidate(Engine engine, IrisDimensionCarvingEntry entry, int worldY, State state) { + if (entry == null || !entry.isEnabled()) { + return false; + } + + IrisRange worldYRange = entry.getWorldYRange(); + if (worldYRange != null && !worldYRange.contains(worldY)) { + return false; + } + + return resolveEntryBiome(engine, entry, state) != null; + } + + private static IrisDimensionCarvingEntry selectChild( + Engine engine, + IrisDimensionCarvingEntry parent, + int worldX, + int worldZ, + Map entryIndex, + State state + ) { + KList children = parent.getChildren(); + if (children == null || children.isEmpty()) { + return parent; + } + + IrisBiome parentBiome = resolveEntryBiome(engine, parent, state); + if (parentBiome == null) { + return parent; + } + + ParentSelectionPlan selectionPlan = state.selectionPlans.get(parent); + if (selectionPlan == null) { + selectionPlan = buildSelectionPlan(engine, parent, parentBiome, entryIndex, state); + state.selectionPlans.put(parent, selectionPlan); + } + + if (selectionPlan.parentOnly) { + return parent; + } + + long seed = resolveChildSeed(engine, state); + CNG childGenerator = parent.getChildrenGenerator(seed, engine.getData()); + double sample = childGenerator.noiseFast2D(worldX, worldZ); + int selectedIndex = (int) Math.round(IrisInterpolation.lerp(0, selectionPlan.maxIndex, sample)); + CarvingChoice selected = selectionPlan.get(selectedIndex); + if (selected == null || selected.entry == null) { + return parent; + } + + return selected.entry; + } + + private static ParentSelectionPlan buildSelectionPlan( + Engine engine, + IrisDimensionCarvingEntry parent, + IrisBiome parentBiome, + Map entryIndex, + State state + ) { + List options = new ArrayList<>(); + KList children = parent.getChildren(); + if (children != null) { + for (String childId : children) { + if (childId == null || childId.isBlank()) { + continue; + } + + IrisDimensionCarvingEntry child = entryIndex.get(childId.trim()); + if (child == null || !child.isEnabled()) { + continue; + } + + IrisBiome childBiome = resolveEntryBiome(engine, child, state); + if (childBiome == null) { + continue; + } + + options.add(new CarvingChoice(child, rarity(childBiome))); + } + } + + options.add(new CarvingChoice(parent, rarity(parentBiome))); + if (options.size() <= 1) { + return ParentSelectionPlan.parentOnly(); + } + + CarvingChoice[] mappedChoices = buildRarityMappedChoices(options); + if (mappedChoices.length == 0) { + return ParentSelectionPlan.parentOnly(); + } + + return new ParentSelectionPlan(mappedChoices); + } + + private static CarvingChoice[] buildRarityMappedChoices(List choices) { + int max = 1; + for (CarvingChoice choice : choices) { + if (choice.rarity > max) { + max = choice.rarity; + } + } + + max++; + List mapped = new ArrayList<>(); + boolean flip = false; + for (CarvingChoice choice : choices) { + int count = max - choice.rarity; + for (int index = 0; index < count; index++) { + flip = !flip; + if (flip) { + mapped.add(choice); + } else { + mapped.add(0, choice); + } + } + } + + return mapped.toArray(new CarvingChoice[0]); + } + + private static int rarity(IrisBiome biome) { + if (biome == null) { + return 1; + } + + int rarity = biome.getRarity(); + return Math.max(rarity, 1); + } + + private static int clampDepth(int depth) { + if (depth <= 0) { + return 0; + } + + return Math.min(depth, MAX_CHILD_DEPTH); + } + + private static Map resolveEntryIndex(Engine engine, State state) { + if (state.entryIndex == null) { + state.entryIndex = engine.getDimension().getCarvingEntryIndex(); + } + + return state.entryIndex; + } + + private static long resolveChildSeed(Engine engine, State state) { + if (state.childSeed == null) { + state.childSeed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; + } + + return state.childSeed; + } + + private static State threadState() { + WeakReference reference = THREAD_STATE.get(); + State state = reference.get(); + if (state != null) { + return state; + } + State replacement = new State(); + THREAD_STATE.set(new WeakReference<>(replacement)); + return replacement; + } + + public static final class State { + private final Map rootEntriesByWorldY = new HashMap<>(); + private final Map selectionPlans = new IdentityHashMap<>(); + private final Map biomeCache = new IdentityHashMap<>(); + private WeakReference engineIdentity; + private WeakReference dimensionIdentity; + private WeakReference dataIdentity; + private Map entryIndex; + private Long childSeed; + + private void bind(Engine engine) { + IrisDimension dimension = engine.getDimension(); + IrisData data = engine.getData(); + if (references(engineIdentity, engine) + && references(dimensionIdentity, dimension) + && references(dataIdentity, data)) { + return; + } + engineIdentity = new WeakReference<>(engine); + dimensionIdentity = new WeakReference<>(dimension); + dataIdentity = new WeakReference<>(data); + rootEntriesByWorldY.clear(); + selectionPlans.clear(); + biomeCache.clear(); + entryIndex = null; + childSeed = null; + } + + private static boolean references(WeakReference identity, Object value) { + return identity != null && identity.get() == value; + } + } + + private static final class ParentSelectionPlan { + private final CarvingChoice[] mappedChoices; + private final int maxIndex; + private final boolean parentOnly; + + private ParentSelectionPlan(CarvingChoice[] mappedChoices) { + this.mappedChoices = mappedChoices; + this.maxIndex = mappedChoices.length - 1; + this.parentOnly = false; + } + + private ParentSelectionPlan() { + this.mappedChoices = null; + this.maxIndex = -1; + this.parentOnly = true; + } + + private static ParentSelectionPlan parentOnly() { + return new ParentSelectionPlan(); + } + + private CarvingChoice get(int index) { + if (mappedChoices == null || mappedChoices.length == 0) { + return null; + } + + if (index < 0) { + return mappedChoices[0]; + } + + if (index >= mappedChoices.length) { + return mappedChoices[mappedChoices.length - 1]; + } + + return mappedChoices[index]; + } + } + + private static final class CarvingChoice implements IRare { + private final IrisDimensionCarvingEntry entry; + private final int rarity; + + private CarvingChoice(IrisDimensionCarvingEntry entry, int rarity) { + this.entry = entry; + this.rarity = rarity; + } + + @Override + public int getRarity() { + return rarity; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java new file mode 100644 index 000000000..1473d3b1b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java @@ -0,0 +1,130 @@ +/* + * 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.deposit; + +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +/** + * Ore generation for {@link IrisBiome}. IrisBiome is Gson deserialized from pack JSON, so its + * fields stay put and only the behavior lives here. Note that {@code IrisBiome.setOres(KList)} + * stays on IrisBiome: it is a hand written Lombok setter override that resets these caches. + */ +public final class IrisBiomeOres { + private IrisBiomeOres() { + } + + public static PlatformBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data, boolean surface) { + KList localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome); + return generateOres(localOres, x, y, z, rng, data); + } + + public static PlatformBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) { + return generateOres(getSurfaceOres(biome), x, y, z, rng, data); + } + + public static PlatformBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) { + return generateOres(getUndergroundOres(biome), x, y, z, rng, data); + } + + public static boolean hasSurfaceOres(IrisBiome biome) { + return !getSurfaceOres(biome).isEmpty(); + } + + public static boolean hasUndergroundOres(IrisBiome biome) { + return !getUndergroundOres(biome).isEmpty(); + } + + public static KList getSurfaceOreGenerators(IrisBiome biome) { + return getOres(biome, true); + } + + public static KList getUndergroundOreGenerators(IrisBiome biome) { + return getOres(biome, false); + } + + public static IrisOreGeneratorBounds getSurfaceOreGeneratorBounds(IrisBiome biome) { + // getIfPresent fast path: aquire allocates a capturing lambda even on a hit, and this + // runs per column on the terrain hot path. + IrisOreGeneratorBounds cached = biome.getSurfaceOreBoundsCache().getIfPresent(); + if (cached != null) { + return cached; + } + return biome.getSurfaceOreBoundsCache().aquire(() -> IrisOreGeneratorBounds.of(getSurfaceOres(biome))); + } + + public static IrisOreGeneratorBounds getUndergroundOreGeneratorBounds(IrisBiome biome) { + IrisOreGeneratorBounds cached = biome.getUndergroundOreBoundsCache().getIfPresent(); + if (cached != null) { + return cached; + } + return biome.getUndergroundOreBoundsCache().aquire(() -> IrisOreGeneratorBounds.of(getUndergroundOres(biome))); + } + + private static KList getSurfaceOres(IrisBiome biome) { + return getOres(biome, true); + } + + private static KList getUndergroundOres(IrisBiome biome) { + return getOres(biome, false); + } + + private static KList getOres(IrisBiome biome, boolean surface) { + AtomicCache> oreCache = surface ? biome.getSurfaceOreCache() : biome.getUndergroundOreCache(); + KList cached = oreCache.getIfPresent(); + + if (cached != null) { + return cached; + } + + return oreCache.aquire(() -> { + KList filtered = new KList<>(); + KList localOres = biome.getOres(); + int oreCount = localOres.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = localOres.get(oreIndex); + if (oreGenerator.isGenerateSurface() == surface) { + filtered.add(oreGenerator); + } + } + + return filtered; + }); + } + + private static PlatformBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { + if (localOres.isEmpty()) { + return null; + } + + int oreCount = localOres.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = localOres.get(oreIndex); + PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); + if (ore != null) { + return ore; + } + } + return null; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java new file mode 100644 index 000000000..1f9c6ace1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java @@ -0,0 +1,11 @@ +package art.arcane.iris.engine.object.terrain.deposit; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Selects which biome identity is checked by a deposit's include and exclude filters.") +public enum IrisDepositBiomeScope { + @Desc("Checks the surface biome selected for the deposit column.") + SURFACE, + @Desc("Checks the cave biome selected at the deposit origin.") + CAVE +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java new file mode 100644 index 000000000..c900f3b70 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java @@ -0,0 +1,525 @@ +/* + * 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.deposit; + +import art.arcane.iris.engine.object.material.IrisBlockData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +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.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.collection.KSet; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.RNG; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("deposit") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Creates ore & other block deposits underground") +@Data +public class IrisDepositGenerator { + private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; + private static final long FNV_PRIME = 0x100000001b3L; + + private final transient ConcurrentMap> objects = new ConcurrentHashMap<>(); + private final transient AtomicCache> blockData = new AtomicCache<>(); + private final transient AtomicCache ore = new AtomicCache<>(); + private final transient AtomicCache> replaceableBlockData = new AtomicCache<>(); + private final transient ConcurrentMap> scaledObjects = new ConcurrentHashMap<>(); + @Required + @MinNumber(-8192) + @MaxNumber(8192) + @Desc("The inclusive minimum origin height in engine-local Y, where 0 is the bottom of the dimension. Negative values let an unclipped vanilla distribution taper into the world floor.") + private int minHeight = 1; + @Required + @MinNumber(-8192) + @MaxNumber(8192) + @Desc("The inclusive maximum origin height in engine-local Y, where 0 is the bottom of the dimension.") + private int maxHeight = 75; + @Desc("How origin heights are sampled. CLIPPED_UNIFORM preserves Iris behavior by clipping the band to terrain; UNIFORM and TRIANGLE sample the authored band first and discard cells outside terrain or build height.") + private IrisDepositHeightDistribution heightDistribution = IrisDepositHeightDistribution.CLIPPED_UNIFORM; + @Desc("TERRAIN places below the generated surface. ABOVE_TERRAIN places only in existing solid hosts above it. FULL_HEIGHT permits existing solid hosts anywhere in the dimension.") + private IrisDepositPlacementScope placementScope = IrisDepositPlacementScope.TERRAIN; + @MinNumber(0) + @MaxNumber(256) + @Desc("Solid blocks kept between a deposit and the terrain surface. Vanilla-like deposits use 0; the Iris default remains 7.") + private int surfaceClearance = 7; + @Required + @MinNumber(0) + @MaxNumber(8192) + @Desc("The minimum Iris block count or vanilla configured vein size, selected according to shape.") + private int minSize = 0; + @Required + @MinNumber(0) + @MaxNumber(8192) + @Desc("The maximum Iris block count or vanilla configured vein size, selected according to shape.") + private int maxSize = 128; + @Desc("IRIS places a fixed-count cube clump. VANILLA_ELLIPSOID uses Minecraft's chained ellipsoid geometry. VANILLA_SCATTERED uses Minecraft's sparse candidate offsets.") + private IrisDepositShape shape = IrisDepositShape.IRIS; + @Required + @MinNumber(0) + @MaxNumber(2048) + @Desc("The maximum amount of clumps per chunk") + private int maxPerChunk = 3; + @Required + @MinNumber(0) + @MaxNumber(2048) + @Desc("The minimum amount of clumps per chunk") + private int minPerChunk = 0; + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance of the deposit spawning in a chunk") + private double spawnChance = 1; + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance of each individual clump spawning in a chunk") + private double perClumpSpawnChance = 1; + @MinNumber(0) + @MaxNumber(1) + @Desc("Chance to discard a candidate ore block when it touches air. This matches vanilla ore exposure reduction.") + private double discardChanceOnAirExposure = 0; + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The palette of blocks to be used in this deposit generator. Each entry is picked uniformly; the per-entry weight field is ignored here.") + private KList palette = new KList<>(); + @MinNumber(1) + @MaxNumber(64) + @Desc("Ore varience is how many different objects clumps iris will create") + private int varience = 3; + @ArrayType(min = 1, type = String.class) + @Desc("Optional block ids this deposit may replace. An empty list retains Iris's any-solid behavior.") + private KList replaceableBlocks = new KList<>(); + @Desc("Chooses whether includedBiomes and excludedBiomes inspect the surface biome or the cave biome at the deposit origin.") + private IrisDepositBiomeScope biomeScope = IrisDepositBiomeScope.CAVE; + @ArrayType(min = 1, type = String.class) + @Desc("Optional Iris biome keys or vanilla derivative ids allowed for this deposit.") + private KList includedBiomes = new KList<>(); + @ArrayType(min = 1, type = String.class) + @Desc("Optional Iris biome keys or vanilla derivative ids denied for this deposit.") + private KList excludedBiomes = new KList<>(); + @Desc("If set to true, this deposit will replace bedrock") + private boolean replaceBedrock = false; + + public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) { + if (shape != IrisDepositShape.IRIS) { + return generateConfiguredClumpObject(rng, rdata, minSize, maxSize); + } + + ClumpCacheKey cacheKey = new ClumpCacheKey(engine.getSeedManager().getDeposit(), minSize, maxSize); + KList objects = this.objects.computeIfAbsent(cacheKey, key -> { + RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata)); + KList objectsf = new KList<>(); + + for (int i = 0; i < varience; i++) { + objectsf.add(generateClumpObject( + rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize())); + } + + return objectsf; + }); + return objects.get(rng.i(0, objects.size())); + } + + public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) { + if (sizeMultiplier == 1D) { + return getClump(engine, rng, rdata); + } + + int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier); + int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier); + if (shape != IrisDepositShape.IRIS) { + return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize); + } + + ClumpCacheKey cacheKey = new ClumpCacheKey( + engine.getSeedManager().getDeposit(), scaledMinSize, scaledMaxSize); + KList objects = scaledObjects.computeIfAbsent(cacheKey, key -> { + long sizeSeed = ((long) key.minSize() << 32) ^ (key.maxSize() & 0xffffffffL); + RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata) + sizeSeed); + KList generated = new KList<>(); + + for (int i = 0; i < varience; i++) { + generated.add(generateClumpObject( + rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize())); + } + + return generated; + }); + return objects.get(rng.i(0, objects.size())); + } + + public int getMaxDimension() { + return Math.min(11, (int) Math.ceil(Math.cbrt(maxSize))); + } + + static int scaledDepositSize(int size, double multiplier) { + return Math.max(0, Math.min(8192, (int) Math.round(size * multiplier))); + } + + long stableClumpSalt(IrisData rdata) { + long hash = FNV_OFFSET_BASIS; + hash = mix(hash, minHeight); + hash = mix(hash, maxHeight); + hash = mixEnum(hash, heightDistribution); + hash = mixEnum(hash, placementScope); + hash = mix(hash, surfaceClearance); + hash = mix(hash, minSize); + hash = mix(hash, maxSize); + hash = mixEnum(hash, shape); + hash = mix(hash, maxPerChunk); + hash = mix(hash, minPerChunk); + hash = mix(hash, Double.doubleToLongBits(spawnChance)); + hash = mix(hash, Double.doubleToLongBits(perClumpSpawnChance)); + hash = mix(hash, Double.doubleToLongBits(discardChanceOnAirExposure)); + KList resolvedPalette = getBlockData(rdata); + hash = mix(hash, resolvedPalette.size()); + for (PlatformBlockState block : resolvedPalette) { + hash = mixString(hash, block == null ? null : block.key()); + } + hash = mix(hash, varience); + hash = mixStrings(hash, replaceableBlocks); + hash = mixEnum(hash, biomeScope); + hash = mixStrings(hash, includedBiomes); + hash = mixStrings(hash, excludedBiomes); + return mix(hash, replaceBedrock ? 1L : 0L); + } + + private static long mix(long hash, long value) { + return (hash ^ value) * FNV_PRIME; + } + + private static long mixEnum(long hash, Enum value) { + return mixString(hash, value == null ? null : value.name()); + } + + private static long mixString(long hash, String value) { + if (value == null) { + return mix(hash, -1L); + } + long mixed = mix(hash, value.length()); + for (int i = 0; i < value.length(); i++) { + mixed = mix(mixed, value.charAt(i)); + } + return mixed; + } + + private static long mixStrings(long hash, KList values) { + if (values == null) { + return mix(hash, -1L); + } + long mixed = mix(hash, values.size()); + for (String value : values) { + mixed = mixString(mixed, value); + } + return mixed; + } + + private IrisObject generateConfiguredClumpObject(RNG rng, IrisData rdata, int clumpMinSize, int clumpMaxSize) { + int size = rng.i(clumpMinSize, clumpMaxSize + 1); + return switch (shape) { + case VANILLA_ELLIPSOID -> generateVanillaEllipsoid(rng, rdata, size); + case VANILLA_SCATTERED -> generateVanillaScattered(rng, rdata, size); + case IRIS -> generateClumpObject(rng, rdata, clumpMinSize, clumpMaxSize); + }; + } + + IrisObject generateVanillaEllipsoid(RNG rng, IrisData rdata, int size) { + if (size <= 0) { + return new IrisObject(1, 1, 1); + } + + float angle = rng.nextFloat() * (float) Math.PI; + float reach = size / 8F; + double startX = Math.sin(angle) * reach; + double endX = -Math.sin(angle) * reach; + double startZ = Math.cos(angle) * reach; + double endZ = -Math.cos(angle) * reach; + double startY = rng.nextInt(3) - 2; + double endY = rng.nextInt(3) - 2; + double[] nodes = new double[size * 4]; + + for (int i = 0; i < size; i++) { + float progress = (float) i / size; + double radiusNoise = rng.nextDouble() * size / 16D; + nodes[i * 4] = startX + (endX - startX) * progress; + nodes[i * 4 + 1] = startY + (endY - startY) * progress; + nodes[i * 4 + 2] = startZ + (endZ - startZ) * progress; + nodes[i * 4 + 3] = ((Math.sin(Math.PI * progress) + 1D) * radiusNoise + 1D) / 2D; + } + + for (int i = 0; i < size - 1; i++) { + if (nodes[i * 4 + 3] <= 0D) { + continue; + } + for (int j = i + 1; j < size; j++) { + if (nodes[j * 4 + 3] <= 0D) { + continue; + } + double dx = nodes[i * 4] - nodes[j * 4]; + double dy = nodes[i * 4 + 1] - nodes[j * 4 + 1]; + double dz = nodes[i * 4 + 2] - nodes[j * 4 + 2]; + double dr = nodes[i * 4 + 3] - nodes[j * 4 + 3]; + if (dr * dr <= dx * dx + dy * dy + dz * dz) { + continue; + } + if (dr > 0D) { + nodes[j * 4 + 3] = -1D; + } else { + nodes[i * 4 + 3] = -1D; + } + } + } + + KSet cells = new KSet<>(); + for (int i = 0; i < size; i++) { + double radius = nodes[i * 4 + 3]; + if (radius < 0D) { + continue; + } + double centerX = nodes[i * 4]; + double centerY = nodes[i * 4 + 1]; + double centerZ = nodes[i * 4 + 2]; + int minX = (int) Math.floor(centerX - radius); + int maxX = Math.max((int) Math.floor(centerX + radius), minX); + int minY = (int) Math.floor(centerY - radius); + int maxY = Math.max((int) Math.floor(centerY + radius), minY); + int minZ = (int) Math.floor(centerZ - radius); + int maxZ = Math.max((int) Math.floor(centerZ + radius), minZ); + + for (int x = minX; x <= maxX; x++) { + double nx = (x + 0.5D - centerX) / radius; + if (nx * nx >= 1D) { + continue; + } + for (int y = minY; y <= maxY; y++) { + double ny = (y + 0.5D - centerY) / radius; + if (nx * nx + ny * ny >= 1D) { + continue; + } + for (int z = minZ; z <= maxZ; z++) { + double nz = (z + 0.5D - centerZ) / radius; + if (nx * nx + ny * ny + nz * nz < 1D) { + cells.add(new BlockPosition(x, y, z)); + } + } + } + } + } + + return objectFromCells(cells, rng, rdata); + } + + IrisObject generateVanillaScattered(RNG rng, IrisData rdata, int size) { + KSet cells = new KSet<>(); + int candidates = rng.nextInt(Math.max(0, size) + 1); + for (int i = 0; i < candidates; i++) { + int magnitude = Math.min(i, 7); + cells.add(new BlockPosition( + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude))); + } + return objectFromCells(cells, rng, rdata); + } + + private IrisObject objectFromCells(KSet cells, RNG rng, IrisData rdata) { + if (cells.isEmpty()) { + return new IrisObject(1, 1, 1); + } + + 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 (BlockPosition cell : cells) { + minX = Math.min(minX, cell.getX()); + minY = Math.min(minY, cell.getY()); + minZ = Math.min(minZ, cell.getZ()); + maxX = Math.max(maxX, cell.getX()); + maxY = Math.max(maxY, cell.getY()); + maxZ = Math.max(maxZ, cell.getZ()); + } + + int extentX = Math.max(Math.abs(minX), Math.abs(maxX)); + int extentY = Math.max(Math.abs(minY), Math.abs(maxY)); + int extentZ = Math.max(Math.abs(minZ), Math.abs(maxZ)); + IrisObject object = new IrisObject(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1); + for (BlockPosition cell : cells) { + object.setUnsigned( + cell.getX() + extentX, + cell.getY() + extentY, + cell.getZ() + extentZ, + nextBlock(rng, rdata)); + } + return object; + } + + private IrisObject generateClumpObject(RNG rngv, IrisData rdata, int clumpMinSize, int clumpMaxSize) { + int s = rngv.i(clumpMinSize, clumpMaxSize + 1); + if (s == 1) { + IrisObject o = new IrisObject(1, 1, 1); + Vector3i center = o.getCenter(); + o.getBlocks().put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), nextBlock(rngv, rdata)); + return o; + } + + int dim = Math.min(11, (int) Math.ceil(Math.cbrt(s))); + IrisObject o = new IrisObject(dim, dim, dim); + + int volume = dim * dim * dim; + if (s >= volume) { + int x = 0, y = 0, z = 0; + + while (z < dim) { + o.setUnsigned(x++, y, z, nextBlock(rngv, rdata)); + + if (x == dim) { + x = 0; + y++; + } + + if (y == dim) { + y = 0; + z++; + } + } + return o; + } + + KSet set = new KSet<>(); + while (s > 0) { + BlockPosition ang = new BlockPosition( + rngv.i(0, dim), + rngv.i(0, dim), + rngv.i(0, dim) + ); + if (!set.add(ang)) continue; + + s--; + o.setUnsigned(ang.getX(), ang.getY(), ang.getZ(), nextBlock(rngv, rdata)); + } + + return o; + } + + private PlatformBlockState nextBlock(RNG rngv, IrisData rdata) { + return getBlockData(rdata).get(rngv.i(0, getBlockData(rdata).size())); + } + + public KList getBlockData(IrisData rdata) { + return blockData.aquire(() -> + { + KList blockData = new KList<>(); + + for (IrisBlockData ix : palette) { + PlatformBlockState bx = ix.getBlockData(rdata); + + if (bx != null) { + blockData.add(bx); + } + } + + return blockData; + }); + } + + public boolean isOre(IrisData rdata) { + return ore.aquire(() -> { + for (PlatformBlockState block : getBlockData(rdata)) { + if (block.isOre()) { + return true; + } + } + + return false; + }); + } + + public boolean canReplace(PlatformBlockState state) { + if (replaceableBlocks == null || replaceableBlocks.isEmpty()) { + return true; + } + return replaceableBlockData.aquire(this::resolveReplaceableBlocks) + .contains(IrisProceduralBlocks.materialKey(state)); + } + + public boolean matchesBiome(IrisBiome surfaceBiome, IrisBiome caveBiome) { + IrisBiome selected = biomeScope == IrisDepositBiomeScope.SURFACE ? surfaceBiome : caveBiome; + if (includedBiomes != null && !includedBiomes.isEmpty() && !matchesAnyBiome(selected, includedBiomes)) { + return false; + } + return excludedBiomes == null || excludedBiomes.isEmpty() || !matchesAnyBiome(selected, excludedBiomes); + } + + public boolean usesCaveBiomeFilter() { + return biomeScope == IrisDepositBiomeScope.CAVE + && ((includedBiomes != null && !includedBiomes.isEmpty()) + || (excludedBiomes != null && !excludedBiomes.isEmpty())); + } + + private KSet resolveReplaceableBlocks() { + KSet resolved = new KSet<>(); + for (String key : replaceableBlocks) { + PlatformBlockState state = B.getStateOrNull(key, false); + if (state != null) { + resolved.add(IrisProceduralBlocks.materialKey(state)); + } + } + return resolved; + } + + private boolean matchesAnyBiome(IrisBiome biome, KList configuredBiomes) { + if (biome == null) { + return false; + } + for (String configured : configuredBiomes) { + String namespaced = configured.contains(":") ? configured : "minecraft:" + configured; + if (configured.equals(biome.getLoadKey()) + || namespaced.equals(biome.getDerivativeKey()) + || namespaced.equals(biome.getVanillaDerivativeKey())) { + return true; + } + } + return false; + } + + record ClumpCacheKey(long depositSeed, int minSize, int maxSize) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java new file mode 100644 index 000000000..57d9cf943 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java @@ -0,0 +1,13 @@ +package art.arcane.iris.engine.object.terrain.deposit; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how a deposit chooses its origin height within the configured vertical band.") +public enum IrisDepositHeightDistribution { + @Desc("Samples uniformly after clipping the configured band to the terrain and build-height bounds.") + CLIPPED_UNIFORM, + @Desc("Samples uniformly from the configured band, then rejects origins outside the terrain or build-height bounds.") + UNIFORM, + @Desc("Samples toward the middle of the configured band with a triangular distribution, then rejects invalid origins.") + TRIANGLE +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java new file mode 100644 index 000000000..9fd557476 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java @@ -0,0 +1,13 @@ +package art.arcane.iris.engine.object.terrain.deposit; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls which vertical part of the world may contain a deposit origin.") +public enum IrisDepositPlacementScope { + @Desc("Places in solid terrain below the generated surface while preserving the configured surface clearance.") + TERRAIN, + @Desc("Places only in existing solid hosts above the generated terrain surface.") + ABOVE_TERRAIN, + @Desc("Places in existing solid hosts anywhere within the dimension build height.") + FULL_HEIGHT +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java new file mode 100644 index 000000000..f8d2d1ea2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java @@ -0,0 +1,13 @@ +package art.arcane.iris.engine.object.terrain.deposit; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Selects the geometry used to build each deposit clump.") +public enum IrisDepositShape { + @Desc("Builds the traditional Iris fixed-block-count cube clump.") + IRIS, + @Desc("Builds a chain of overlapping ellipsoids matching Minecraft's ordinary ore-vein geometry.") + VANILLA_ELLIPSOID, + @Desc("Builds sparse candidate offsets matching Minecraft's scattered-ore geometry.") + VANILLA_SCATTERED +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java new file mode 100644 index 000000000..966a751d1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java @@ -0,0 +1,87 @@ +/* + * 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.deposit; + +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.volmlib.util.collection.KMap; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import lombok.experimental.Accessors; + +@Snippet("deposit-variant") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Remaps ore block ids to alternate block ids within a vertical band. Ores declared at dimension, region, and biome scope can be rewritten at placement time (for example, iron_ore -> deepslate_iron_ore inside a deep carving band, or yourmod:iron -> yourmod:moon_iron inside a lunar biome).") +@Data +public class IrisDepositVariant { + private final transient AtomicCache> resolved = new AtomicCache<>(); + + @Required + @MinNumber(-2048) + @MaxNumber(8192) + @Desc("Inclusive minimum world Y this variant applies at.") + private int minHeight = 0; + + @Required + @MinNumber(-2048) + @MaxNumber(8192) + @Desc("Inclusive maximum world Y this variant applies at.") + private int maxHeight = 0; + + @Required + @Desc("Source block id (for example `minecraft:iron_ore`) -> replacement block id (for example `minecraft:deepslate_iron_ore`). Any block id the data loader resolves is accepted, including external/mod blocks. Source match is by material only, so block properties on the source key are ignored.") + private KMap remap = new KMap<>(); + + public PlatformBlockState remapOrNull(PlatformBlockState ore, IrisData rdata) { + if (ore == null || remap == null || remap.isEmpty()) { + return null; + } + + KMap map = resolved.aquire(() -> buildResolved(rdata)); + return map.get(IrisProceduralBlocks.materialKey(ore)); + } + + private KMap buildResolved(IrisData rdata) { + KMap out = new KMap<>(); + + for (java.util.Map.Entry entry : remap.entrySet()) { + PlatformBlockState source = B.getStateOrNull(entry.getKey(), false); + PlatformBlockState target = B.getStateOrNull(entry.getValue(), true); + + if (source == null || target == null) { + continue; + } + + out.put(IrisProceduralBlocks.materialKey(source), target); + } + + return out; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java new file mode 100644 index 000000000..ed5e9502e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java @@ -0,0 +1,81 @@ +/* + * 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.deposit; + +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.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.volmlib.util.math.RNG; +import art.arcane.iris.util.project.noise.CNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import art.arcane.iris.spi.PlatformBlockState; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Scatters single ore blocks through terrain by sampling a noise field at every block in a vertical band. Defined on dimensions, regions, or biomes; the most specific level wins.") +@Data +public class IrisOreGenerator { + @Desc("The ore blocks to place. An empty palette generates nothing, so this must be set for the generator to have any effect.") + private IrisMaterialPalette palette = new IrisMaterialPalette().qclear(); + @Desc("The noise style sampled per block to decide where ore appears. STATIC gives independent random speckle; smoother styles give veiny clusters.") + private IrisGeneratorStyle chanceStyle = new IrisGeneratorStyle(NoiseStyle.STATIC); + @Desc("When true this generator also replaces surface-layer blocks (it runs before layers and fluid); when false it only replaces underground rock.") + private boolean generateSurface = false; + @MinNumber(0) + @MaxNumber(1) + @Desc("Noise cutoff: a block becomes ore when the sampled noise is at or below this value, so higher means more ore. 0 disables, 1 replaces everything in range.") + private double threshold = 0.5; + @Desc("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private IrisRange range = new IrisRange(30, 80); + + private transient AtomicCache chanceCache = new AtomicCache<>(); + + public void warm(RNG rng, IrisData data) { + chanceCache.aquire(() -> chanceStyle.create(rng, data)); + palette.getLayerGenerator(rng, data); + } + + public PlatformBlockState generate(int x, int y, int z, RNG rng, IrisData data) { + if (!range.contains(y)) { + return null; + } + + if (palette.getPalette().isEmpty()) { + return null; + } + + CNG chance = chanceCache.aquire(() -> chanceStyle.create(rng, data)); + + if (chance.noise(x, y, z) > threshold) { + return null; + } + + return palette.get(rng, x, y, z, data); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java new file mode 100644 index 000000000..aea87f2c0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java @@ -0,0 +1,44 @@ +package art.arcane.iris.engine.object.terrain.deposit; + +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.volmlib.util.collection.KList; + +public final class IrisOreGeneratorBounds { + public static final IrisOreGeneratorBounds EMPTY = new IrisOreGeneratorBounds(false, 0D, 0D); + + private final boolean hasOres; + private final double min; + private final double max; + + private IrisOreGeneratorBounds(boolean hasOres, double min, double max) { + this.hasOres = hasOres; + this.min = min; + this.max = max; + } + + public static IrisOreGeneratorBounds of(KList ores) { + if (ores == null || ores.isEmpty()) { + return EMPTY; + } + + double min = Double.POSITIVE_INFINITY; + double max = Double.NEGATIVE_INFINITY; + int oreCount = ores.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = ores.get(oreIndex); + IrisRange range = oreGenerator.getRange(); + min = Math.min(min, range.getMin()); + max = Math.max(max, range.getMax()); + } + + return new IrisOreGeneratorBounds(true, min, max); + } + + public boolean hasOres() { + return hasOres; + } + + public boolean contains(int y) { + return hasOres && y >= min && y <= max; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java new file mode 100644 index 000000000..2a3407e14 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java @@ -0,0 +1,33 @@ +/* + * 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.floating; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how floating-child island underside blocks choose their palette.") +public enum FloatingBottomPaletteMode { + @Desc("Use the normal top-down biome layer depth for the whole island column.") + DEPTH, + + @Desc("Use the target biome's top palette from both the island top and underside, meeting in the middle.") + MIRROR_TOP, + + @Desc("Use bottomPalette near the underside and the target biome's normal palette near the top.") + CUSTOM +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java new file mode 100644 index 000000000..e9d3403b4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java @@ -0,0 +1,596 @@ +/* + * 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.object.terrain.floating; + +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import org.jetbrains.annotations.Nullable; + +import java.util.IdentityHashMap; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +public final class FloatingIslandBoundarySampler { + static final int EDGE_TAPER_WIDTH = FloatingIslandEdgeProfile.DEFAULT_WIDTH; + static final int EDGE_FADE_RADIUS = EDGE_TAPER_WIDTH + 1; + private static final int CHUNK_SIZE = 16; + private static final int MIN_CORE_DISTANCE = 3; + + private final BiomeSampler source; + private final ConcurrentHashMap parentFields; + private final ConcurrentHashMap footprintFields; + private final ConcurrentHashMap ownershipFields; + + public FloatingIslandBoundarySampler(BiomeSampler source) { + this.source = Objects.requireNonNull(source); + this.parentFields = new ConcurrentHashMap<>(); + this.footprintFields = new ConcurrentHashMap<>(); + this.ownershipFields = new ConcurrentHashMap<>(); + } + + public @Nullable IrisBiome parent(int x, int z) { + return parentField(x, z, EDGE_TAPER_WIDTH).parent(x, z); + } + + public double edgeFade(IrisBiome parent, int x, int z) { + return edgeFade(parent, x, z, EDGE_TAPER_WIDTH); + } + + public double edgeFade(IrisBiome parent, int x, int z, int taperWidth) { + int boundaryDistance = edgeDistance(parent, x, z, taperWidth); + return edgeFadeForDistance(boundaryDistance, taperWidth); + } + + public int edgeDistance(IrisBiome parent, int x, int z, int taperWidth) { + if (parent == null) { + return 0; + } + + return parentField(x, z, taperWidth).edgeDistance(parent, x, z); + } + + public FootprintSample footprint(CNG footprint, int x, int z, double signedCut) { + return footprint(footprint, x, z, signedCut, EDGE_TAPER_WIDTH); + } + + public FootprintSample footprint(CNG footprint, int x, int z, double signedCut, int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int chunkX = Math.floorDiv(x, CHUNK_SIZE); + int chunkZ = Math.floorDiv(z, CHUNK_SIZE); + FootprintFieldKey key = new FootprintFieldKey( + footprint, chunkX, chunkZ, Double.doubleToLongBits(signedCut), width); + FootprintField field = footprintFields.computeIfAbsent(key, + ignored -> new FootprintField(footprint, chunkX, chunkZ, signedCut, width)); + return field.sample(x, z); + } + + public OwnershipSample ownership(KList entries, CNG picker, int x, int z) { + return ownership(entries, picker, x, z, EDGE_TAPER_WIDTH); + } + + public OwnershipSample ownership(KList entries, CNG picker, int x, int z, + int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int chunkX = Math.floorDiv(x, CHUNK_SIZE); + int chunkZ = Math.floorDiv(z, CHUNK_SIZE); + OwnershipFieldKey key = new OwnershipFieldKey(entries, picker, chunkX, chunkZ, width); + OwnershipField field = ownershipFields.computeIfAbsent(key, + ignored -> new OwnershipField(entries, picker, chunkX, chunkZ, width)); + return field.sample(x, z); + } + + static double edgeFadeForDistance(int boundaryDistance) { + return edgeFadeForDistance(boundaryDistance, EDGE_TAPER_WIDTH); + } + + static double edgeFadeForDistance(int boundaryDistance, int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + double normalized = Math.max(0.0D, Math.min(1.0D, (boundaryDistance - 1.0D) / width)); + return normalized * normalized * (3.0D - (2.0D * normalized)); + } + + private ParentBoundaryField parentField(int x, int z, int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int chunkX = Math.floorDiv(x, CHUNK_SIZE); + int chunkZ = Math.floorDiv(z, CHUNK_SIZE); + ParentFieldKey key = new ParentFieldKey(Cache.key(chunkX, chunkZ), width); + return parentFields.computeIfAbsent(key, + ignored -> new ParentBoundaryField(source, chunkX, chunkZ, width)); + } + + private static boolean sameBiome(@Nullable IrisBiome expected, @Nullable IrisBiome actual) { + if (actual == expected) { + return true; + } + if (expected == null || actual == null || expected.getLoadKey() == null) { + return false; + } + return expected.getLoadKey().equals(actual.getLoadKey()); + } + + public record FootprintSample(double signed, int cardinalSupport, int diagonalSupport, boolean accepted, + int boundaryDistance, double edgeFade) { + } + + public record OwnershipSample(IrisFloatingChildBiomes owner, int boundaryDistance, double edgeFade) { + } + + private record ParentFieldKey(long chunkKey, int taperWidth) { + } + + private static final class FootprintFieldKey { + private final CNG footprint; + private final int chunkX; + private final int chunkZ; + private final long signedCutBits; + private final int taperWidth; + + private FootprintFieldKey(CNG footprint, int chunkX, int chunkZ, long signedCutBits, int taperWidth) { + this.footprint = footprint; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.signedCutBits = signedCutBits; + this.taperWidth = taperWidth; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof FootprintFieldKey key)) { + return false; + } + return footprint == key.footprint && chunkX == key.chunkX && chunkZ == key.chunkZ + && signedCutBits == key.signedCutBits && taperWidth == key.taperWidth; + } + + @Override + public int hashCode() { + int result = System.identityHashCode(footprint); + result = (31 * result) + chunkX; + result = (31 * result) + chunkZ; + result = (31 * result) + Long.hashCode(signedCutBits); + return (31 * result) + taperWidth; + } + } + + private static final class OwnershipFieldKey { + private final KList entries; + private final CNG picker; + private final int chunkX; + private final int chunkZ; + private final int taperWidth; + + private OwnershipFieldKey(KList entries, CNG picker, int chunkX, int chunkZ, + int taperWidth) { + this.entries = entries; + this.picker = picker; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.taperWidth = taperWidth; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof OwnershipFieldKey key)) { + return false; + } + return entries == key.entries && picker == key.picker && chunkX == key.chunkX && chunkZ == key.chunkZ + && taperWidth == key.taperWidth; + } + + @Override + public int hashCode() { + int result = System.identityHashCode(entries); + result = (31 * result) + System.identityHashCode(picker); + result = (31 * result) + chunkX; + result = (31 * result) + chunkZ; + return (31 * result) + taperWidth; + } + } + + private static final class ParentBoundaryField { + private final FieldGeometry geometry; + private final int minX; + private final int minZ; + private final IrisBiome[] parents; + private final byte[] distance; + private final boolean[] viable; + + private ParentBoundaryField(BiomeSampler source, int chunkX, int chunkZ, int taperWidth) { + this.geometry = FieldGeometry.forWidth(taperWidth); + this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); + this.minZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); + this.parents = new IrisBiome[geometry.area()]; + this.distance = new byte[geometry.area()]; + this.viable = new boolean[geometry.area()]; + build(source); + } + + private @Nullable IrisBiome parent(int x, int z) { + return parents[geometry.index(x - minX, z - minZ)]; + } + + private int edgeDistance(IrisBiome expected, int x, int z) { + int index = geometry.index(x - minX, z - minZ); + if (!sameBiome(expected, parents[index]) || !viable[index]) { + return 0; + } + return Math.min(geometry.maxRenderableDistance(), Byte.toUnsignedInt(distance[index])); + } + + private void build(BiomeSampler source) { + int rawSize = geometry.fieldSize() + 2; + IrisBiome[] raw = new IrisBiome[rawSize * rawSize]; + int rawMinX = minX - 1; + int rawMinZ = minZ - 1; + for (int z = 0; z < rawSize; z++) { + for (int x = 0; x < rawSize; x++) { + raw[rawIndex(x, z, rawSize)] = source.sample(rawMinX + x, rawMinZ + z); + } + } + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + IrisBiome parent = raw[rawIndex(x + 1, z + 1, rawSize)]; + parents[index] = parent; + distance[index] = (byte) (touchesDifferentBiome(raw, parent, x, z, rawSize) + ? 1 + : geometry.maxDistance()); + } + } + propagateDistanceField(distance, geometry); + markLabelCoreSupported(parents, distance, viable, geometry); + } + + private static boolean touchesDifferentBiome(IrisBiome[] raw, @Nullable IrisBiome parent, int x, int z, + int rawSize) { + for (int dz = -1; dz <= 1; dz++) { + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dz == 0) { + continue; + } + if (!sameBiome(parent, raw[rawIndex(x + dx + 1, z + dz + 1, rawSize)])) { + return true; + } + } + } + return false; + } + + private static int rawIndex(int x, int z, int rawSize) { + return (z * rawSize) + x; + } + } + + private static final class FootprintField { + private final FieldGeometry geometry; + private final int occupancyMinX; + private final int occupancyMinZ; + private final double[] signed; + private final byte[] cardinalSupport; + private final byte[] diagonalSupport; + private final boolean[] accepted; + private final byte[] distance; + private final boolean[] viable; + + private FootprintField(CNG footprint, int chunkX, int chunkZ, double signedCut, int taperWidth) { + this.geometry = FieldGeometry.forWidth(taperWidth); + this.occupancyMinX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); + this.occupancyMinZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); + this.signed = new double[geometry.area()]; + this.cardinalSupport = new byte[geometry.area()]; + this.diagonalSupport = new byte[geometry.area()]; + this.accepted = new boolean[geometry.area()]; + this.distance = new byte[geometry.area()]; + this.viable = new boolean[geometry.area()]; + build(footprint, signedCut); + } + + private FootprintSample sample(int x, int z) { + int index = geometry.index(x - occupancyMinX, z - occupancyMinZ); + int inwardDistance = Byte.toUnsignedInt(distance[index]); + boolean renderable = accepted[index] && viable[index] && inwardDistance > 1; + int boundaryDistance = renderable + ? Math.min(geometry.maxRenderableDistance(), inwardDistance) + : 0; + double fade = edgeFadeForDistance(boundaryDistance, geometry.taperWidth()); + return new FootprintSample(signed[index], Byte.toUnsignedInt(cardinalSupport[index]), + Byte.toUnsignedInt(diagonalSupport[index]), renderable, boundaryDistance, fade); + } + + private void build(CNG footprint, double signedCut) { + double[] rawSigned = sampleRawFootprint(footprint); + buildOccupancy(rawSigned, signedCut); + buildDistanceField(); + } + + private double[] sampleRawFootprint(CNG footprint) { + int rawSize = geometry.fieldSize() + 2; + double[] rawSigned = new double[rawSize * rawSize]; + int rawMinX = occupancyMinX - 1; + int rawMinZ = occupancyMinZ - 1; + for (int z = 0; z < rawSize; z++) { + for (int x = 0; x < rawSize; x++) { + rawSigned[rawIndex(x, z, rawSize)] = signedFromUnit(footprint.noise(rawMinX + x, rawMinZ + z)); + } + } + return rawSigned; + } + + private void buildOccupancy(double[] rawSigned, double signedCut) { + int rawSize = geometry.fieldSize() + 2; + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + double value = rawSigned[rawIndex(x + 1, z + 1, rawSize)]; + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + if (rawSigned[rawIndex(x + dx + 1, z + dz + 1, rawSize)] <= signedCut) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + boolean solid = value > signedCut; + FloatingIslandSample.NeighborSupport support = new FloatingIslandSample.NeighborSupport(cardinal, diagonal); + boolean supported = support.hasSolidSupport(); + boolean repairedPinhole = FloatingIslandSample.isFootprintPinholeRepairable(support); + signed[index] = value; + cardinalSupport[index] = (byte) cardinal; + diagonalSupport[index] = (byte) diagonal; + accepted[index] = (solid && supported) || (!solid && repairedPinhole); + } + } + } + + private void buildDistanceField() { + fillDistanceField(accepted, distance, geometry); + markCoreSupported(accepted, distance, viable, geometry); + } + + private static int rawIndex(int x, int z, int rawSize) { + return (z * rawSize) + x; + } + + private static double signedFromUnit(double value) { + return (Math.max(0.0D, Math.min(1.0D, value)) * 2.0D) - 1.0D; + } + } + + private static final class OwnershipField { + private final FieldGeometry geometry; + private final int minX; + private final int minZ; + private final IrisFloatingChildBiomes[] owners; + private final IdentityHashMap distances; + + private OwnershipField(KList entries, CNG picker, int chunkX, int chunkZ, + int taperWidth) { + this.geometry = FieldGeometry.forWidth(taperWidth); + this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); + this.minZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); + this.owners = new IrisFloatingChildBiomes[geometry.area()]; + this.distances = new IdentityHashMap<>(); + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + double value = Math.max(0.0D, Math.min(1.0D, picker.noise(minX + x, minZ + z))); + owners[geometry.index(x, z)] = IRare.pick(entries, value); + } + } + for (IrisFloatingChildBiomes entry : entries) { + if (entry != null && !distances.containsKey(entry)) { + distances.put(entry, buildDistanceField(entry)); + } + } + } + + private OwnershipSample sample(int x, int z) { + int index = geometry.index(x - minX, z - minZ); + IrisFloatingChildBiomes owner = owners[index]; + if (owner == null) { + return new OwnershipSample(null, 0, 0.0D); + } + ComponentDistanceField field = distances.get(owner); + if (field == null) { + return new OwnershipSample(null, 0, 0.0D); + } + int inwardDistance = Byte.toUnsignedInt(field.distance()[index]); + int boundaryDistance = field.viable()[index] + ? Math.min(geometry.maxRenderableDistance(), inwardDistance) + : 0; + double fade = edgeFadeForDistance(boundaryDistance, geometry.taperWidth()); + return new OwnershipSample(owner, boundaryDistance, fade); + } + + private ComponentDistanceField buildDistanceField(IrisFloatingChildBiomes owner) { + boolean[] owned = new boolean[owners.length]; + byte[] distance = new byte[owners.length]; + boolean[] viable = new boolean[owners.length]; + for (int i = 0; i < owners.length; i++) { + owned[i] = owners[i] == owner; + } + fillDistanceField(owned, distance, geometry); + markCoreSupported(owned, distance, viable, geometry); + return new ComponentDistanceField(distance, viable); + } + } + + private record ComponentDistanceField(byte[] distance, boolean[] viable) { + } + + private record FieldGeometry(int taperWidth, int fadeRadius, int fieldSize, int maxDistance) { + private static FieldGeometry forWidth(int taperWidth) { + int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); + int radius = width + 1; + return new FieldGeometry(width, radius, CHUNK_SIZE + (radius * 2), radius + 1); + } + + private int area() { + return fieldSize * fieldSize; + } + + private int maxRenderableDistance() { + return fadeRadius; + } + + private int index(int x, int z) { + return (z * fieldSize) + x; + } + } + + private static void fillDistanceField(boolean[] inside, byte[] distance, FieldGeometry geometry) { + for (int i = 0; i < inside.length; i++) { + distance[i] = (byte) (inside[i] ? geometry.maxDistance() : 0); + } + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + if (!inside[geometry.index(x, z)]) { + continue; + } + setMinimumDistance(distance, x, z, x - 1, z, geometry); + setMinimumDistance(distance, x, z, x, z - 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z - 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z - 1, geometry); + } + } + for (int z = geometry.fieldSize() - 1; z >= 0; z--) { + for (int x = geometry.fieldSize() - 1; x >= 0; x--) { + if (!inside[geometry.index(x, z)]) { + continue; + } + setMinimumDistance(distance, x, z, x + 1, z, geometry); + setMinimumDistance(distance, x, z, x, z + 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z + 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z + 1, geometry); + } + } + } + + private static void propagateDistanceField(byte[] distance, FieldGeometry geometry) { + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + setMinimumDistance(distance, x, z, x - 1, z, geometry); + setMinimumDistance(distance, x, z, x, z - 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z - 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z - 1, geometry); + } + } + for (int z = geometry.fieldSize() - 1; z >= 0; z--) { + for (int x = geometry.fieldSize() - 1; x >= 0; x--) { + setMinimumDistance(distance, x, z, x + 1, z, geometry); + setMinimumDistance(distance, x, z, x, z + 1, geometry); + setMinimumDistance(distance, x, z, x + 1, z + 1, geometry); + setMinimumDistance(distance, x, z, x - 1, z + 1, geometry); + } + } + } + + private static void setMinimumDistance(byte[] distance, int x, int z, int neighborX, int neighborZ, + FieldGeometry geometry) { + if (neighborX < 0 || neighborX >= geometry.fieldSize() + || neighborZ < 0 || neighborZ >= geometry.fieldSize()) { + return; + } + int index = geometry.index(x, z); + int neighborDistance = Byte.toUnsignedInt(distance[geometry.index(neighborX, neighborZ)]); + int currentDistance = Byte.toUnsignedInt(distance[index]); + distance[index] = (byte) Math.min(currentDistance, neighborDistance + 1); + } + + private static void markCoreSupported(boolean[] inside, byte[] distance, boolean[] viable, + FieldGeometry geometry) { + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + if (!inside[index]) { + continue; + } + int inwardDistance = Byte.toUnsignedInt(distance[index]); + viable[index] = inwardDistance >= MIN_CORE_DISTANCE + || inwardDistance == MIN_CORE_DISTANCE - 1 + && hasCoreNeighbor(inside, distance, null, x, z, geometry); + } + } + } + + private static void markLabelCoreSupported(IrisBiome[] labels, byte[] distance, boolean[] viable, + FieldGeometry geometry) { + for (int z = 0; z < geometry.fieldSize(); z++) { + for (int x = 0; x < geometry.fieldSize(); x++) { + int index = geometry.index(x, z); + int inwardDistance = Byte.toUnsignedInt(distance[index]); + viable[index] = inwardDistance >= MIN_CORE_DISTANCE + || inwardDistance == MIN_CORE_DISTANCE - 1 + && hasCoreNeighbor(null, distance, labels, x, z, geometry); + } + } + } + + private static boolean hasCoreNeighbor(@Nullable boolean[] inside, byte[] distance, + @Nullable IrisBiome[] labels, int x, int z, FieldGeometry geometry) { + int index = geometry.index(x, z); + for (int dz = -1; dz <= 1; dz++) { + for (int dx = -1; dx <= 1; dx++) { + if (dx == 0 && dz == 0) { + continue; + } + int neighborX = x + dx; + int neighborZ = z + dz; + if (neighborX < 0 || neighborX >= geometry.fieldSize() + || neighborZ < 0 || neighborZ >= geometry.fieldSize()) { + continue; + } + int neighbor = geometry.index(neighborX, neighborZ); + if (Byte.toUnsignedInt(distance[neighbor]) < MIN_CORE_DISTANCE) { + continue; + } + if (inside != null && !inside[neighbor]) { + continue; + } + if (labels != null && !sameBiome(labels[index], labels[neighbor])) { + continue; + } + return true; + } + } + return false; + } + + @FunctionalInterface + public interface BiomeSampler { + @Nullable IrisBiome sample(int x, int z); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java new file mode 100644 index 000000000..62e8ccdca --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java @@ -0,0 +1,91 @@ +/* + * 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.object.terrain.floating; + +import art.arcane.iris.util.project.noise.CNG; + +public final class FloatingIslandEdgeProfile { + public static final int DEFAULT_WIDTH = 10; + public static final int MIN_WIDTH = 2; + public static final int MAX_WIDTH = 32; + public static final double DEFAULT_EXPONENT = 1.0D; + public static final double MIN_EXPONENT = 0.25D; + public static final double MAX_EXPONENT = 4.0D; + public static final double MAX_VARIATION_AMPLITUDE = 8.0D; + public static final FloatingIslandEdgeProfile DEFAULT = new FloatingIslandEdgeProfile( + DEFAULT_WIDTH, DEFAULT_EXPONENT, 0.0D, null); + + private final int width; + private final double exponent; + private final double variationAmplitude; + private final CNG variation; + + public FloatingIslandEdgeProfile(int width, double exponent, double variationAmplitude, CNG variation) { + this.width = clampWidth(width); + this.exponent = clampExponent(exponent); + this.variationAmplitude = clampVariationAmplitude(variationAmplitude, this.width); + this.variation = variation; + } + + public int width() { + return width; + } + + public double exponent() { + return exponent; + } + + public double variationAmplitude() { + return variationAmplitude; + } + + public int fieldWidth() { + return Math.min(MAX_WIDTH, (int) Math.ceil(width + variationAmplitude)); + } + + public double fade(int boundaryDistance, int x, int z) { + if (boundaryDistance <= 1) { + return 0.0D; + } + double localWidth = width; + if (variation != null && variationAmplitude > 0.0D) { + double noise = Math.max(0.0D, Math.min(1.0D, variation.noise(x, z))); + double signedNoise = (noise * 2.0D) - 1.0D; + localWidth += signedNoise * variationAmplitude; + } + + double position = Math.max(0.0D, Math.min(1.0D, (boundaryDistance - 1.0D) / localWidth)); + double smooth = position * position * (3.0D - (2.0D * position)); + return exponent == DEFAULT_EXPONENT ? smooth : Math.pow(smooth, exponent); + } + + public static int clampWidth(int width) { + return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, width)); + } + + public static double clampExponent(double exponent) { + return Math.max(MIN_EXPONENT, Math.min(MAX_EXPONENT, exponent)); + } + + public static double clampVariationAmplitude(double amplitude, int width) { + int clampedWidth = clampWidth(width); + double widthLimit = Math.min(clampedWidth - MIN_WIDTH, MAX_WIDTH - clampedWidth); + return Math.max(0.0D, Math.min(Math.min(MAX_VARIATION_AMPLITUDE, widthLimit), amplitude)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java new file mode 100644 index 000000000..abbaa1257 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -0,0 +1,802 @@ +/* + * 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.floating; + +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +public final class FloatingIslandSample { + public static final int REJECT_NONE = 0; + public static final int REJECT_NO_ENTRIES = 1; + public static final int REJECT_NO_SEED = 2; + public static final int REJECT_NO_PICK = 3; + public static final int REJECT_ABOVE_HEIGHT = 4; + public static final int REJECT_NO_THICKNESS = 5; + public static final int REJECT_NO_SOLID = 6; + public static final int REJECT_COUNT = 7; + public static final int REJECT_CLUSTER = REJECT_NO_SEED; + + private static final int PINHOLE_CARDINAL_FILL = 3; + private static final int PINHOLE_TOTAL_FILL = 7; + private static final int CARVE_CARDINAL_SUPPORT = 2; + private static final int CARVE_TOTAL_SUPPORT = 4; + private static final double CARVE_SHELL_FRACTION = 0.14D; + private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D; + private static final ThreadLocal LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]); + private static final ThreadLocal LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]); + private static final ThreadLocal> CHUNK_MEMO = ThreadLocal.withInitial(HashMap::new); + private static final ThreadLocal> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new); + private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false); + + public static int getLastReject() { + return LAST_REJECT.get()[0]; + } + + public static double getLastClusterValue() { + return LAST_DENSITY.get()[0]; + } + + public static double getLastClusterThreshold() { + return LAST_DENSITY.get()[1]; + } + + public static void clearThreadCaches() { + } + + public static void clearChunkMemo() { + CHUNK_MEMO.get().clear(); + FOOTPRINT_MEMO.get().clear(); + } + + public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { + long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL); + HashMap memo = CHUNK_MEMO.get(); + if (memo.containsKey(key)) { + return memo.get(key); + } + FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); + memo.put(key, result); + return result; + } + + private static FloatingIslandSample reject(int code) { + LAST_REJECT.get()[0] = code; + return null; + } + + private static void warnNullCng(String styleField, IrisBiome parent) { + if (NULL_CNG_WARNED.compareAndSet(false, true)) { + String biomeKey = parent == null ? "" : parent.getLoadKey(); + IrisLogging.warn("Floating child biome on " + biomeKey + " has a null CNG for " + styleField + + " (style factory returned null or AtomicCache swallowed an exception); skipping floating sampling until pack is fixed"); + } + } + + public final IrisFloatingChildBiomes entry; + public final int islandBaseY; + public final int thickness; + public final int topIdx; + public final int solidCount; + public final boolean[] solidMask; + private final IrisFloatingChildBiomes[] entryMask; + private transient int cachedBottomIdx = -2; + + private FloatingIslandSample(IrisFloatingChildBiomes entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask) { + this(entry, islandBaseY, thickness, topIdx, solidCount, solidMask, null); + } + + private FloatingIslandSample(IrisFloatingChildBiomes entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, IrisFloatingChildBiomes[] entryMask) { + this.entry = entry; + this.islandBaseY = islandBaseY; + this.thickness = thickness; + this.topIdx = topIdx; + this.solidCount = solidCount; + this.solidMask = solidMask; + this.entryMask = entryMask; + } + + static FloatingIslandSample constructForTest(int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask) { + return new FloatingIslandSample(null, islandBaseY, thickness, topIdx, solidCount, solidMask); + } + + static FloatingIslandSample constructForTest(IrisFloatingChildBiomes entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, IrisFloatingChildBiomes[] entryMask) { + return new FloatingIslandSample(entry, islandBaseY, thickness, topIdx, solidCount, solidMask, entryMask); + } + + public int topY() { + return islandBaseY + topIdx; + } + + public int bottomY() { + if (cachedBottomIdx == -2) { + cachedBottomIdx = -1; + for (int i = 0; i < solidMask.length; i++) { + if (solidMask[i]) { + cachedBottomIdx = i; + break; + } + } + } + return cachedBottomIdx == -1 ? -1 : islandBaseY + cachedBottomIdx; + } + + public IrisFloatingChildBiomes entryAt(int maskIndex) { + if (entryMask != null && maskIndex >= 0 && maskIndex < entryMask.length && entryMask[maskIndex] != null) { + return entryMask[maskIndex]; + } + + return entry; + } + + public IrisFloatingChildBiomes bottomEntry() { + int bottomY = bottomY(); + if (bottomY < 0) { + return entry; + } + + return entryAt(bottomY - islandBaseY); + } + + public boolean hasMergedEntries() { + return entryMask != null; + } + + public static long columnSeed(long baseSeed, int wx, int wz) { + return baseSeed ^ ((long) wx * 341873128712L) ^ ((long) wz * 132897987541L); + } + + private static int maximumEdgeFieldWidth(KList entries, long baseSeed, + IrisData data, IrisBiome parent) { + int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH; + for (IrisFloatingChildBiomes entry : entries) { + FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent); + maximumWidth = Math.max(maximumWidth, profile.fieldWidth()); + } + return maximumWidth; + } + + private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed, + IrisData data, IrisBiome parent) { + FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data); + if (profile != null) { + return profile; + } + warnNullCng("edgeTaperVariationStyle", parent); + return FloatingIslandEdgeProfile.DEFAULT; + } + + public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { + KList entries = parent.getFloatingChildBiomes(); + if (entries == null || entries.isEmpty()) { + return reject(REJECT_NO_ENTRIES); + } + + int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent); + int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); + + if (parent.isMergeFloatingChildBiomes()) { + return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, + parentBoundaryDistance, boundaryFieldWidth); + } + + IrisFloatingChildBiomes entry; + int ownershipBoundaryDistance = boundaryFieldWidth + 1; + if (entries.size() == 1) { + entry = entries.getFirst(); + } else { + IrisFloatingChildBiomes reference = entries.getFirst(); + CNG picker = reference.getPickerCng(baseSeed, data); + if (picker == null) { + warnNullCng("pickerStyle", parent); + return reject(REJECT_NO_PICK); + } + FloatingIslandBoundarySampler.OwnershipSample ownership = boundarySampler.ownership( + entries, picker, wx, wz, boundaryFieldWidth); + entry = ownership.owner(); + if (entry == null) { + return reject(REJECT_NO_PICK); + } + ownershipBoundaryDistance = ownership.boundaryDistance(); + } + + return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, + parentBoundaryDistance, ownershipBoundaryDistance); + } + + private static FloatingIslandSample sampleMerged(IrisBiome parent, KList entries, + int wx, int wz, int chunkHeight, long baseSeed, IrisData data, + Engine engine, FloatingIslandBoundarySampler boundarySampler, + int parentBoundaryDistance, int boundaryFieldWidth) { + KList samples = new KList<>(); + int minY = Integer.MAX_VALUE; + int maxY = Integer.MIN_VALUE; + + for (IrisFloatingChildBiomes entry : entries) { + FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, + boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1); + if (sample == null) { + continue; + } + + int bottomY = sample.bottomY(); + if (bottomY < 0) { + continue; + } + + samples.add(sample); + if (bottomY < minY) { + minY = bottomY; + } + int topY = sample.topY(); + if (topY > maxY) { + maxY = topY; + } + } + + if (samples.isEmpty() || minY > maxY) { + return reject(REJECT_NO_SEED); + } + + int thickness = maxY - minY + 1; + boolean[] solidMask = new boolean[thickness]; + IrisFloatingChildBiomes[] entryMask = new IrisFloatingChildBiomes[thickness]; + int[] entryTopY = new int[thickness]; + Arrays.fill(entryTopY, Integer.MIN_VALUE); + int solidCount = 0; + + for (FloatingIslandSample sample : samples) { + int sampleTopY = sample.topY(); + for (int i = 0; i < sample.solidMask.length; i++) { + if (!sample.solidMask[i]) { + continue; + } + + int y = sample.islandBaseY + i; + int mergedIndex = y - minY; + if (!solidMask[mergedIndex]) { + solidMask[mergedIndex] = true; + solidCount++; + } + if (sampleTopY >= entryTopY[mergedIndex]) { + entryTopY[mergedIndex] = sampleTopY; + entryMask[mergedIndex] = sample.entryAt(i); + } + } + } + + int topIdx = highestSolidIndex(solidMask); + if (solidCount == 0 || topIdx < 0) { + return reject(REJECT_NO_SOLID); + } + + IrisFloatingChildBiomes topEntry = entryMask[topIdx] == null ? samples.getFirst().entry : entryMask[topIdx]; + LAST_REJECT.get()[0] = REJECT_NONE; + return new FloatingIslandSample(topEntry, minY, thickness, topIdx, solidCount, solidMask, entryMask); + } + + private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz, + int chunkHeight, long baseSeed, IrisData data, Engine engine, + FloatingIslandBoundarySampler boundarySampler, + int parentBoundaryDistance, int ownershipBoundaryDistance) { + FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent); + CNG footprintCng = entry.getFootprintCng(baseSeed, data); + if (footprintCng == null) { + warnNullCng("footprintStyle", parent); + return reject(REJECT_NO_SEED); + } + double threshold = Math.max(0, Math.min(1, entry.getFootprintThreshold())); + double signedCut = (threshold * 2.0) - 1.0; + FloatingIslandBoundarySampler.FootprintSample footprint = boundarySampler.footprint( + footprintCng, wx, wz, signedCut, edgeProfile.fieldWidth()); + double signed = footprint.signed(); + + double[] diag = LAST_DENSITY.get(); + diag[0] = signed; + diag[1] = signedCut; + + NeighborSupport footprintSupport = new NeighborSupport(footprint.cardinalSupport(), footprint.diagonalSupport()); + if (!footprint.accepted()) { + return reject(REJECT_NO_SEED); + } + int boundaryDistance = Math.min(footprint.boundaryDistance(), + Math.min(parentBoundaryDistance, ownershipBoundaryDistance)); + double edgeFade = edgeProfile.fade(boundaryDistance, wx, wz); + if (edgeFade <= 0.0D) { + return reject(REJECT_NO_THICKNESS); + } + + CNG altitudeCng = entry.getAltitudeCng(baseSeed, data); + if (altitudeCng == null) { + warnNullCng("altitudeStyle", parent); + return reject(REJECT_NO_SEED); + } + double altNoise = altitudeCng.noise(wx, wz); + double altClamped = Math.max(0, Math.min(1, altNoise)); + int worldMin = engine.getWorld().minHeight(); + int minAlt = Math.max(0, entry.getMinHeightAboveSurface() - worldMin); + int maxAlt = Math.max(minAlt, entry.getMaxHeightAboveSurface() - worldMin); + int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); + + IrisBiome target = entry.getRealBiome(parent, data); + int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data); + int topH = roundedEdgeHeight(fullTopHeight, edgeFade); + + CNG bottomCng = entry.getBottomCng(baseSeed, data); + if (bottomCng == null) { + warnNullCng("bottomStyle", parent); + return reject(REJECT_NO_SEED); + } + double bottomNoise = bottomCng.noise(wx, wz); + double bottomClamped = Math.max(0, Math.min(1, bottomNoise)); + double bottomShaped = Math.pow(bottomClamped, Math.max(0.1, entry.getBottomExponent())); + int minDepth = Math.max(0, entry.getBottomDepthMin()); + int maxDepth = Math.max(minDepth, entry.getBottomDepthMax()); + int depth = roundedEdgeDepth(minDepth, maxDepth, bottomShaped, edgeFade); + if (topH == 0 && depth == 0) { + double fullDepth = minDepth + (bottomShaped * (maxDepth - minDepth)); + if (fullDepth > 0.0D) { + depth = 1; + } else if (fullTopHeight > 0) { + topH = 1; + } else { + return reject(REJECT_NO_THICKNESS); + } + } + int topY = baseY + topH; + int botY = baseY - depth; + + Integer minAbsoluteY = entry.getMinAbsoluteY(); + if (minAbsoluteY != null && botY < minAbsoluteY - worldMin) { + botY = minAbsoluteY - worldMin; + } + Integer maxAbsoluteY = entry.getMaxAbsoluteY(); + if (maxAbsoluteY != null && topY > maxAbsoluteY - worldMin) { + topY = maxAbsoluteY - worldMin; + } + + if (botY < 0) { + botY = 0; + } + if (topY >= chunkHeight) { + topY = chunkHeight - 1; + } + if (topY < botY) { + return reject(REJECT_ABOVE_HEIGHT); + } + + int thickness = topY - botY + 1; + int maxThickness = Math.max(1, entry.getMaxThickness()); + if (thickness > maxThickness) { + botY = topY - maxThickness + 1; + if (botY < 0) { + botY = 0; + } + thickness = topY - botY + 1; + } + if (thickness <= 0) { + return reject(REJECT_NO_THICKNESS); + } + + boolean[] solidMask = new boolean[thickness]; + CNG wallWarp = entry.getWallWarpCng(baseSeed, data); + double warpAmp = Math.max(0, entry.getWallWarpAmplitude()); + double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); + IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); + CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; + double carveThreshold = entry.getCarveThreshold(); + boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; + boolean useProfileCarve = carvingProfileSampler != null; + boolean useCarve = directCarveEnabled(entry, carvingProfileSampler, carve, carveThreshold); + boolean[] lateralCarveMask = useProfileCarve || useCarve ? new boolean[thickness] : null; + boolean baseCarveInterior = lateralCarveMask != null && canCarveLaterally(edgeFade, footprintSupport); + + if (useWarp) { + for (int k = 0; k < thickness; k++) { + int wy = botY + k; + boolean layerSolid = layerFootprintSolid(footprintCng, wallWarp, true, effectiveWarpAmp, wx, wy, wz, signedCut); + NeighborSupport layerSupport = layerNeighborSupport(footprintCng, wallWarp, true, effectiveWarpAmp, wx, wy, wz, signedCut); + if (layerSolid && !layerSupport.hasSolidSupport()) { + continue; + } + if (!layerSolid && !layerSupport.canFillPinhole()) { + continue; + } + solidMask[k] = true; + if (lateralCarveMask != null) { + lateralCarveMask[k] = baseCarveInterior && layerSolid && layerSupport.isFullySurrounded(); + } + } + } else { + Arrays.fill(solidMask, true); + if (baseCarveInterior) { + Arrays.fill(lateralCarveMask, true); + } + } + + int solidCount = solidifyUncarvedInterior(solidMask); + if (useProfileCarve) { + solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carvingProfileSampler, carveThreshold); + } else if (useCarve) { + solidCount = carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, carve, carveThreshold); + } + int highestSolidIdx = highestSolidIndex(solidMask); + + if (solidCount == 0 || highestSolidIdx < 0) { + return reject(REJECT_NO_SOLID); + } + + int topIdx = highestSolidIdx; + + LAST_REJECT.get()[0] = REJECT_NONE; + return new FloatingIslandSample(entry, botY, thickness, topIdx, solidCount, solidMask); + } + + static int roundedEdgeHeight(int topHeight, double edgeFade) { + return Math.max(0, (int) Math.round(Math.max(0, topHeight) * Math.max(0, Math.min(1, edgeFade)))); + } + + static int roundedEdgeDepth(int minDepth, int maxDepth, double bottomShaped, double edgeFade) { + int min = Math.max(0, minDepth); + int max = Math.max(min, maxDepth); + double shaped = Math.max(0, Math.min(1, bottomShaped)); + double fade = Math.max(0, Math.min(1, edgeFade)); + double fullDepth = min + shaped * (max - min); + return (int) Math.round(fullDepth * fade); + } + + static double effectiveWallWarpAmplitude(double wallWarpAmplitude, double edgeFade) { + double amplitude = Math.max(0, wallWarpAmplitude); + double fade = Math.max(0, Math.min(1, edgeFade)); + return amplitude * fade; + } + + static boolean directCarveEnabled(IrisFloatingChildBiomes entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { + return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; + } + + static boolean canCarveLaterally(double edgeFade, NeighborSupport support) { + return edgeFade >= 1.0 && support.isFullySurrounded(); + } + + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CNG carve, double carveThreshold) { + return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> { + double carveNoise = carve.noise(x, y, z); + double carveClamped = Math.max(0, Math.min(1, carveNoise)); + return carveClamped > carveThreshold; + }); + } + + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, IrisCaveProfileSampler carve, double carveThreshold) { + return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold)); + } + + private static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CarveSampler carve) { + int firstSolid = -1; + int lastSolid = -1; + for (int i = 0; i < solidMask.length; i++) { + if (!solidMask[i]) { + continue; + } + if (firstSolid < 0) { + firstSolid = i; + } + lastSolid = i; + } + if (firstSolid < 0) { + return 0; + } + int span = lastSolid - firstSolid + 1; + int shell = carveShellThickness(span); + int carveStart = firstSolid + shell; + int carveEnd = lastSolid - shell; + boolean[] carveMask = new boolean[solidMask.length]; + if (carveStart <= carveEnd) { + for (int i = carveStart; i <= carveEnd; i++) { + if (!solidMask[i] || !lateralCarveMask[i]) { + continue; + } + + int y = botY + i; + if (carve.shouldCarve(wx, y, wz) && hasCarveClusterSupport(carve, wx, y, wz)) { + carveMask[i] = true; + } + } + clampVerticalCarveRuns(carveMask, carveStart, carveEnd, maxVerticalCarveRun(span)); + for (int i = carveStart; i <= carveEnd; i++) { + if (carveMask[i]) { + solidMask[i] = false; + } + } + } + int count = 0; + for (boolean solid : solidMask) { + if (solid) { + count++; + } + } + return count; + } + + static int carveShellThickness(int solidSpan) { + if (solidSpan <= 4) { + return 1; + } + + int proportional = (int) Math.ceil(solidSpan * CARVE_SHELL_FRACTION); + return Math.max(2, Math.min(5, proportional)); + } + + static int maxVerticalCarveRun(int solidSpan) { + int proportional = (int) Math.round(solidSpan * CARVE_MAX_VERTICAL_RUN_FRACTION); + return Math.max(2, Math.min(6, proportional)); + } + + static void clampVerticalCarveRuns(boolean[] carveMask, int start, int end, int maxRun) { + int i = start; + while (i <= end) { + if (!carveMask[i]) { + i++; + continue; + } + + int runStart = i; + while (i <= end && carveMask[i]) { + i++; + } + int runEnd = i - 1; + int runLength = runEnd - runStart + 1; + if (runLength <= maxRun) { + continue; + } + + int keepStart = runStart + ((runLength - maxRun) / 2); + int keepEnd = keepStart + maxRun - 1; + for (int j = runStart; j <= runEnd; j++) { + carveMask[j] = j >= keepStart && j <= keepEnd; + } + } + } + + private static boolean hasCarveClusterSupport(CarveSampler carve, int wx, int wy, int wz) { + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + if (!carve.shouldCarve(wx + dx, wy, wz + dz)) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + return cardinal >= CARVE_CARDINAL_SUPPORT && cardinal + diagonal >= CARVE_TOTAL_SUPPORT; + } + + static boolean hasFootprintNeighborSupport(CNG footprintCng, int wx, int wz, double signedCut) { + return footprintNeighborSupport(footprintCng, wx, wz, signedCut).hasSolidSupport(); + } + + static boolean isFootprintPinholeRepairable(NeighborSupport support) { + return support.canFillPinhole(); + } + + static NeighborSupport footprintNeighborSupport(CNG footprintCng, int wx, int wz, double signedCut) { + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + double signed = footprintSigned(footprintCng, wx + dx, wz + dz); + if (signed <= signedCut) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + return new NeighborSupport(cardinal, diagonal); + } + + static NeighborSupport layerNeighborSupport(CNG footprintCng, CNG wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { + int cardinal = 0; + int diagonal = 0; + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + if (dx == 0 && dz == 0) { + continue; + } + if (!layerFootprintSolid(footprintCng, wallWarp, useWarp, warpAmp, wx + dx, wy, wz + dz, signedCut)) { + continue; + } + if (Math.abs(dx) + Math.abs(dz) == 1) { + cardinal++; + } else { + diagonal++; + } + } + } + return new NeighborSupport(cardinal, diagonal); + } + + static boolean layerFootprintSolid(CNG footprintCng, CNG wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { + double sx = wx; + double sz = wz; + if (useWarp) { + double wnX = wallWarp.noise(wx, wy, wz); + double signedWarpX = signedFromUnit(wnX); + sx = wx + signedWarpX * warpAmp; + double wnZ = wallWarp.noise(wx + 1987.3, wy, wz + 2341.1); + double signedWarpZ = signedFromUnit(wnZ); + sz = wz + signedWarpZ * warpAmp; + } + double layerFoot = footprintCng.noise(sx, sz); + return signedFromUnit(layerFoot) > signedCut; + } + + private static double footprintSigned(CNG footprintCng, int wx, int wz) { + IdentityHashMap memoByCng = FOOTPRINT_MEMO.get(); + Long2DoubleOpenHashMap memo = memoByCng.get(footprintCng); + if (memo == null) { + memo = new Long2DoubleOpenHashMap(512); + memo.defaultReturnValue(Double.NaN); + memoByCng.put(footprintCng, memo); + } + + long key = columnKey(wx, wz); + double cached = memo.get(key); + if (!Double.isNaN(cached)) { + return cached; + } + + double signed = signedFromUnit(footprintCng.noise(wx, wz)); + memo.put(key, signed); + return signed; + } + + private static long columnKey(int wx, int wz) { + return ((long) wx << 32) ^ (wz & 0xFFFFFFFFL); + } + + private static double signedFromUnit(double value) { + return (Math.max(0, Math.min(1, value)) * 2.0) - 1.0; + } + + static int solidifyUncarvedInterior(boolean[] solidMask) { + int firstSolid = -1; + int lastSolid = -1; + for (int i = 0; i < solidMask.length; i++) { + if (!solidMask[i]) { + continue; + } + if (firstSolid < 0) { + firstSolid = i; + } + lastSolid = i; + } + if (firstSolid < 0) { + return 0; + } + for (int i = firstSolid; i <= lastSolid; i++) { + solidMask[i] = true; + } + return lastSolid - firstSolid + 1; + } + + private static int highestSolidIndex(boolean[] solidMask) { + for (int i = solidMask.length - 1; i >= 0; i--) { + if (solidMask[i]) { + return i; + } + } + return -1; + } + + @FunctionalInterface + private interface CarveSampler { + boolean shouldCarve(int x, int y, int z); + } + + static final class NeighborSupport { + private final int cardinal; + private final int diagonal; + + NeighborSupport(int cardinal, int diagonal) { + this.cardinal = cardinal; + this.diagonal = diagonal; + } + + int cardinal() { + return cardinal; + } + + int diagonal() { + return diagonal; + } + + int total() { + return cardinal + diagonal; + } + + boolean hasSolidSupport() { + return cardinal > 0 || diagonal >= 2; + } + + boolean canFillPinhole() { + return cardinal >= PINHOLE_CARDINAL_FILL && total() >= PINHOLE_TOTAL_FILL; + } + + boolean isFullySurrounded() { + return cardinal == 4 && diagonal == 4; + } + } + + private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) { + int maxTopHeight = Math.max(0, entry.getMaxTopHeight()); + if (maxTopHeight == 0) { + return 0; + } + return switch (entry.getTopShapeMode()) { + case FLAT -> maxTopHeight; + case NOISE -> { + CNG topCng = entry.getTopShapeCng(baseSeed, data); + if (topCng == null) { + warnNullCng("topShapeStyle", null); + yield maxTopHeight / 2; + } + double n = topCng.noise(wx, wz); + double clamped = Math.max(0, Math.min(1, n)); + double amp = Math.max(0, Math.min(1, entry.getTopShapeAmp())); + yield (int) Math.round(clamped * amp * maxTopHeight); + } + case BIOME -> { + if (target == null) { + yield maxTopHeight / 2; + } + double h = target.getHeight(engine, wx, wz, baseSeed); + int rounded = (int) Math.round(h); + if (rounded < 0) { + yield 0; + } + yield Math.min(maxTopHeight, rounded); + } + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java new file mode 100644 index 000000000..d24c188f0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java @@ -0,0 +1,376 @@ +/* + * 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.floating; + +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.iris.engine.object.prefab.IrisObjectScale; +import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +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.RegistryListBlockType; +import art.arcane.iris.engine.object.annotations.RegistryListResource; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("floating-child-biome") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode +@Desc("Declares a floating biome layer above this biome's terrain. A 2D footprint noise decides which columns are part of the island (threshold + style control blankets, swirls, scattered blobs). The top profile is driven by the target biome's own terrain generators (so a mountains biome produces real peaks, desert produces real dunes). The bottom tail hanging below is a separately configurable noise (pick VASCULAR for drippy roots, FRACTAL_RM_SIMPLEX for crystalline spikes, PERLIN for smooth rounded bowls).") +@Data +public class IrisFloatingChildBiomes implements IRare { + private final transient AtomicCache resolvedBiome = new AtomicCache<>(); + private final transient AtomicCache footprintCache = new AtomicCache<>(); + private final transient AtomicCache edgeTaperProfileCache = new AtomicCache<>(); + private final transient AtomicCache pickerCache = new AtomicCache<>(); + private final transient AtomicCache altitudeCache = new AtomicCache<>(); + private final transient AtomicCache topShapeCache = new AtomicCache<>(); + private final transient AtomicCache bottomCache = new AtomicCache<>(); + private final transient AtomicCache wallWarpCache = new AtomicCache<>(); + private final transient AtomicCache carveCache = new AtomicCache<>(); + private final transient AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); + private final transient AtomicCache shrinkScaleCache = new AtomicCache<>(); + + public CNG getFootprintCng(long baseSeed, IrisData data) { + return footprintCache.aquire(() -> getFootprintStyle().create(new RNG(baseSeed ^ 0xF007B17DL), data)); + } + + public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) { + return edgeTaperProfileCache.aquire(() -> { + int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth()); + double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude( + getEdgeTaperVariationAmplitude(), width); + IrisGeneratorStyle style = getEdgeTaperVariationStyle(); + CNG variation = amplitude > 0.0D && style != null + ? style.create(new RNG(baseSeed ^ 0xED6E7A9E5L), data) + : null; + return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation); + }); + } + + public CNG getPickerCng(long baseSeed, IrisData data) { + return pickerCache.aquire(() -> getPickerStyle().create(new RNG(baseSeed ^ 0x91C4E72DL), data)); + } + + public CNG getAltitudeCng(long baseSeed, IrisData data) { + return altitudeCache.aquire(() -> getAltitudeStyle().create(new RNG(baseSeed ^ 0xA17DEBBL), data)); + } + + public CNG getTopShapeCng(long baseSeed, IrisData data) { + return topShapeCache.aquire(() -> getTopShapeStyle().create(new RNG(baseSeed ^ 0x70970601DEFL), data)); + } + + public CNG getBottomCng(long baseSeed, IrisData data) { + return bottomCache.aquire(() -> getBottomStyle().create(new RNG(baseSeed ^ 0xB0770075CAFEL), data)); + } + + public CNG getWallWarpCng(long baseSeed, IrisData data) { + IrisGeneratorStyle style = getWallWarpStyle(); + if (style == null) { + return null; + } + return wallWarpCache.aquire(() -> style.create(new RNG(baseSeed ^ 0xA117BA17E0FL), data)); + } + + public CNG getCarveCng(long baseSeed, IrisData data) { + IrisGeneratorStyle style = getCarveStyle(); + if (style == null) { + return null; + } + return carveCache.aquire(() -> style.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); + } + + public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { + if (!hasCarvingReference()) { + return null; + } + + return carvingProfileSamplerCache.aquire(() -> { + IrisBiome resolved = resolveCarvingBiome(carving, engine, data); + if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) { + return null; + } + + return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); + }); + } + + public boolean hasCarvingReference() { + return carving != null && !carving.isBlank(); + } + + static IrisBiome resolveCarvingBiome(String carving, Engine engine, IrisData data) { + if (carving == null || carving.isBlank() || engine == null || data == null) { + return null; + } + + IrisDimension dimension = engine.getDimension(); + if (dimension != null && dimension.getCarvingEntryIndex() != null) { + IrisDimensionCarvingEntry entry = dimension.getCarvingEntryIndex().get(carving); + if (entry != null) { + return IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry); + } + } + + if (data.getBiomeLoader() == null) { + return null; + } + + return data.getBiomeLoader().load(carving); + } + + @RegistryListResource(IrisBiome.class) + @Desc("The target biome whose visual design (layers, palette, decorators, surface objects, derivative, and — when topShapeMode=BIOME — generator profile) drives the floating island. Leave empty to reuse the parent biome (self).") + private String biome = ""; + + @MinNumber(1) + @MaxNumber(512) + @Desc("Selection rarity when multiple floating child entries are defined on one parent biome. Lower is more common.") + private int rarity = 1; + + @Desc("2D noise that decides which columns are part of this island. Set feature size via the style's own zoom field (e.g. {\"style\":\"CELLULAR\",\"zoom\":0.3} for ~30-block shards, {\"style\":\"SIMPLEX\",\"zoom\":1.0} for ~100-block blobs). Pick SIMPLEX for smooth blobs, CELLULAR for angular shards, VASCULAR for vein/branch strips, FRACTAL_FBM_SIMPLEX for large irregular blanket regions. Fracture (domain warp) this to get swirly silhouettes.") + private IrisGeneratorStyle footprintStyle = NoiseStyle.SIMPLEX.style(); + + @MinNumber(0) + @MaxNumber(1) + @Desc("Coverage threshold (0..1). Roughly the fraction of the world that is NOT island: 0.0 = every column becomes island, 0.5 ≈ 50% of columns, 0.8 ≈ sparse scattered ~20% coverage, 1.0 = no islands at all. Values near 0.5 feel most natural.") + private double footprintThreshold = 0.5; + + @MinNumber(2) + @MaxNumber(32) + @Desc("Width in blocks of the rounded transition from the floating island contour to its full thickness. Smaller values make a tighter edge; larger values make a broader rounded underside.") + private int edgeTaperWidth = FloatingIslandEdgeProfile.DEFAULT_WIDTH; + + @MinNumber(0.25) + @MaxNumber(4) + @Desc("Shape exponent for the rounded edge. Values below 1 fill into a softer, fuller curve; values above 1 keep the rim thinner before rising into the island interior.") + private double edgeTaperExponent = FloatingIslandEdgeProfile.DEFAULT_EXPONENT; + + @Desc("Broad 2D noise that organically varies the rounded edge without changing the island footprint. Low-frequency SIMPLEX or PERLIN styles give coherent natural contours; high-frequency or cellular styles can look speckled.") + private IrisGeneratorStyle edgeTaperVariationStyle = NoiseStyle.SIMPLEX.style().zoomed(0.18D); + + @MinNumber(0) + @MaxNumber(8) + @Desc("Maximum number of blocks by which edgeTaperVariationStyle locally widens or narrows the rounded transition. 0 disables variation. Runtime keeps the resulting local width between 2 and 32 blocks so every protected rim column remains connected.") + private double edgeTaperVariationAmplitude = 0.0D; + + @Desc("Picker noise used when multiple floating child entries exist. Samples once per column to deterministically choose which entry's footprint is tested there. Use a large style zoom (e.g. zoom: 4 for ~400-block regions) so each entry owns broad coherent areas.") + private IrisGeneratorStyle pickerStyle = NoiseStyle.SIMPLEX.style(); + + @Desc("Altitude noise — varies the base platform Y across one island so it isn't a flat plane. Use a large style zoom (e.g. zoom: 2 for ~200-block altitude patches) so an island sits at roughly one altitude.") + private IrisGeneratorStyle altitudeStyle = NoiseStyle.SIMPLEX.style(); + + @MinNumber(0) + @MaxNumber(2032) + @Desc("Minimum absolute world Y where the island base can sit. Island altitude is independent of the parent biome's terrain height; altitudeStyle noise varies the base between min and max per column.") + private int minHeightAboveSurface = 160; + + @MinNumber(0) + @MaxNumber(2032) + @Desc("Maximum absolute world Y where the island base can sit. Island altitude is independent of the parent biome's terrain height; altitudeStyle noise varies the base between min and max per column.") + private int maxHeightAboveSurface = 210; + + @Desc("Optional absolute minimum world Y for the island base. When set, baseY is clamped upward so the tail bottom stays above this value.") + private Integer minAbsoluteY = null; + + @Desc("Optional absolute maximum world Y for the island top. When set, the top is clamped downward.") + private Integer maxAbsoluteY = null; + + @Desc("How the top profile of the island is shaped. BIOME = evaluate target biome's own generators (mountains biome -> real mountains). NOISE = use topShapeStyle as a user-controlled heightmap. FLAT = constant maxTopHeight slab.") + private TopShapeMode topShapeMode = TopShapeMode.BIOME; + + @MinNumber(0) + @MaxNumber(512) + @Desc("Maximum top profile height in blocks above the island base. Caps how tall the biome terrain can grow on top.") + private int maxTopHeight = 40; + + @Desc("Used only when topShapeMode=NOISE. 2D noise driving the top heightmap. Set feature scale via the style's zoom field (small zoom = rugged peaks, large zoom = broad rolling shapes).") + private IrisGeneratorStyle topShapeStyle = NoiseStyle.SIMPLEX.style(); + + @MinNumber(0) + @MaxNumber(1) + @Desc("Amplitude multiplier applied to the NOISE top profile. 0 = no top (flat at base), 1 = full maxTopHeight range.") + private double topShapeAmp = 1.0; + + @Desc("2D noise driving the bottom tail hanging below the island base. VASCULAR = drippy organic roots. FRACTAL_RM_SIMPLEX = crystalline spikes. CELLULAR = jagged chunks. PERLIN = smooth rounded bowl. SIMPLEX = gentle lobes. Set feature scale via the style's zoom field.") + private IrisGeneratorStyle bottomStyle = NoiseStyle.SIMPLEX.style(); + + @MinNumber(0) + @MaxNumber(512) + @Desc("Minimum blocks below the base where the tail extends.") + private int bottomDepthMin = 4; + + @MinNumber(0) + @MaxNumber(512) + @Desc("Maximum blocks below the base where the tail extends.") + private int bottomDepthMax = 20; + + @MinNumber(0.1) + @MaxNumber(8) + @Desc("Power curve applied to the bottom noise before mapping to depth. >1 = most columns shallow with occasional deeper spikes (sparse roots). <1 = most columns deep with occasional shallow spots (dense curtains). 1.0 = linear.") + private double bottomExponent = 1.0; + + @Desc("Controls the material palette near the island underside. DEPTH keeps the old top-down depth behavior. MIRROR_TOP uses the target biome's shallow/top palette from the underside upward. CUSTOM uses bottomPalette near the underside while keeping the target biome palette near the top.") + private FloatingBottomPaletteMode bottomPaletteMode = FloatingBottomPaletteMode.DEPTH; + + @ArrayType(min = 1, type = IrisBiomePaletteLayer.class) + @Desc("Custom palette layers used near the underside when bottomPaletteMode=CUSTOM. The layer format is the same as normal biome layers.") + private KList bottomPalette = new KList<>(); + + @MinNumber(1) + @MaxNumber(512) + @Desc("Hard cap on the total Y-extent (top minus bottom) of a single island column. Safety limit.") + private int maxThickness = 96; + + @Desc("Optional 3D noise that shifts the footprint's XZ sample position per Y layer — naturalizes the walls so they stop looking like a straight extrusion of the 2D footprint. Leave null to disable and keep straight vertical walls. Good defaults: {\"style\":\"SIMPLEX\",\"zoom\":0.25} for gentle undulation, {\"style\":\"FRACTAL_FBM_SIMPLEX\",\"zoom\":0.4} for craggier walls.") + private IrisGeneratorStyle wallWarpStyle = null; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Amplitude in blocks of the per-layer XZ shift applied when wallWarpStyle is set. 0 = no warp (straight walls). 4..8 = gentle naturalization. 16+ = heavily meandering walls. Ignored when wallWarpStyle is null.") + private double wallWarpAmplitude = 6.0; + + @Desc("Optional 3D noise that swiss-cheeses the island interior by marking individual blocks as air when the noise exceeds carveThreshold. Leave null to keep the island solid. Good defaults: {\"style\":\"CELLULAR\",\"zoom\":0.3} for bubble pockets, {\"style\":\"VASCULAR\",\"zoom\":0.25} for wormy tunnels.") + private IrisGeneratorStyle carveStyle = null; + + @Desc("Optional carving biome key or dimension carving entry id whose caveProfile drives floating-island internal air pockets. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. When set, this overrides carveStyle while carveThreshold remains a final tuning bias.") + private String carving = ""; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Threshold (0..1) above which carveStyle noise carves air pockets. 1.0 = no direct-noise carving. 0.75 = sparse pockets. 0.55 = heavy swiss-cheese. 0.4 = shredded lattice. When carving is set, lower values add a final positive threshold bias to the referenced caveProfile.") + private double carveThreshold = 1.0; + + @Desc("Optional water surface height above the island base, in blocks. null = no internal water. Positive = water fills any dip in the top profile up to baseY + localFluidHeight (forms lakes/ponds in concavities of the biome-top heightmap).") + private Integer localFluidHeight = null; + + @Desc("Block used for the internal water pool when localFluidHeight is positive.") + @RegistryListBlockType + private String fluidBlock = "minecraft:water"; + + @Desc("When true, the target biome's decorators apply to the island's top surface.") + private boolean inheritDecorators = true; + + @Desc("When true, the target biome's surface objects are placed on the island's top surface instead of the parent terrain.") + private boolean inheritObjects = true; + + @MinNumber(0.01) + @MaxNumber(1) + @Desc("Uniform shrink factor applied to every object placed on this floating island (inherited, extra, and free-floating). 1.0 = native size, 0.5 = half size, 0.25 = quarter. Useful for making small floating biomes feel believable.") + private double objectShrinkFactor = 1.0; + + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @Desc("Additional object placements anchored to the island top.") + private KList extraObjects = new KList<>(); + + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @Desc("Additional object placements that float freely in air, independent of the island. Forced to ObjectPlaceMode.FLOATING.") + private KList floatingObjects = new KList<>(); + + @Desc("Visualization color for this floating child in Iris Studio.") + private String color = null; + + @Desc("Controls how topObjectOverrides are combined with the inherited surface objects from the target biome. INHERIT_ONLY (default) = behaves identically to before this field was added. MERGE = appends overrides after inherited objects. REPLACE = uses only overrides, ignoring all inherited objects.") + private OverrideMode topObjectMode = OverrideMode.INHERIT_ONLY; + + @Desc("Controls how bottomObjectOverrides are combined. INHERIT_ONLY (default) = no bottom objects placed (there is no inherited bottom set). MERGE = same as REPLACE for bottom (no inherited source). REPLACE = uses bottomObjectOverrides list only.") + private OverrideMode bottomObjectMode = OverrideMode.INHERIT_ONLY; + + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @Desc("Object placements that override or supplement the inherited surface objects on the island TOP. Behaviour depends on topObjectMode. INHERIT_ONLY = this list is ignored. MERGE = appended after inherited. REPLACE = used instead of inherited.") + private KList topObjectOverrides = new KList<>(); + + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @Desc("Object placements anchored to the island BOTTOM face. Each entry is auto-inverted 180 degrees around the X axis and placed flush against the lowest solid face of the island, so objects appear to hang upside-down from the underside. WARNING: directional blocks (stairs, doors, slabs) will not render correctly when flipped — use non-directional content (logs, leaves, stone, mycelium, ice, glass) for bottom placements.") + private KList bottomObjectOverrides = new KList<>(); + + public KList resolveTopObjects(IrisBiome target) { + KList surfaceObjects = (inheritObjects && target != null) ? target.getSurfaceObjects() : new KList<>(); + return resolveTopObjectsFromSurface(surfaceObjects); + } + + KList resolveTopObjectsFromSurface(KList surfaceObjects) { + return switch (topObjectMode) { + case REPLACE -> new KList<>(topObjectOverrides); + case MERGE -> { + KList merged = new KList<>(); + merged.addAll(surfaceObjects); + merged.addAll(topObjectOverrides); + yield merged; + } + case INHERIT_ONLY -> surfaceObjects; + }; + } + + public KList resolveBottomObjects(IrisBiome target) { + return switch (bottomObjectMode) { + case INHERIT_ONLY -> new KList<>(); + case MERGE, REPLACE -> bottomObjectOverrides; + }; + } + + public boolean hasObjectShrink() { + return objectShrinkFactor > 0 && objectShrinkFactor < 1.0; + } + + public IrisObjectScale getShrinkScale() { + return shrinkScaleCache.aquire(() -> { + IrisObjectScale s = new IrisObjectScale(); + s.setSize(Math.max(0.01, Math.min(1.0, objectShrinkFactor))); + return s; + }); + } + + public IrisBiome getRealBiome(IrisBiome parent, IrisData data) { + return resolvedBiome.aquire(() -> { + if (biome == null || biome.isBlank() || biome.equals(parent.getLoadKey())) { + return parent; + } + + IrisBiome loaded = data.getBiomeLoader().load(biome); + if (loaded == null) { + return parent; + } + + return loaded; + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java new file mode 100644 index 000000000..866821177 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java @@ -0,0 +1,33 @@ +/* + * 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.floating; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Controls how an override list is combined with the inherited object set from the target biome.") +public enum OverrideMode { + @Desc("Ignore the override list entirely. Use only the inherited objects from the target biome (subject to inheritObjects).") + INHERIT_ONLY, + + @Desc("Append override list entries after the inherited objects from the target biome. Both sets are placed.") + MERGE, + + @Desc("Use only the override list. The inherited objects from the target biome are discarded regardless of inheritObjects.") + REPLACE +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java new file mode 100644 index 000000000..f6151c6e3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java @@ -0,0 +1,33 @@ +/* + * 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.floating; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("How the top profile of a floating-child island is shaped.") +public enum TopShapeMode { + @Desc("Evaluate the target biome's own terrain generators to build the island top. Mountains biome produces real peaks, desert produces dunes, plains is flat. Recommended default.") + BIOME, + + @Desc("Drive the top profile from topShapeStyle noise, independent of the target biome's generators. Amplitude controlled by topShapeAmp.") + NOISE, + + @Desc("Flat slab on top, topHeight blocks above the base. Ignores noise and biome generators.") + FLAT +} 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 new file mode 100644 index 000000000..04f8a27ba --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IRare.java @@ -0,0 +1,115 @@ +/* + * 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; + } + + /** + * Expands a candidate list into a rarity-weighted list: each entry appears totalRarity/rarity + * times, so picking uniformly from the result applies rarity exactly once. Both the Bukkit and + * modded entity spawners select through this expansion; rarity must never be applied a second + * time per spawn position. + */ + static KList expandWeighted(List possibilities) { + KList rarityTypes = new KList<>(); + int totalRarity = 0; + for (T i : possibilities) { + totalRarity += get(i); + } + for (T i : possibilities) { + rarityTypes.addMultiple(i, totalRarity / get(i)); + } + return rarityTypes; + } + + 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 new file mode 100644 index 000000000..46687bc67 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisColor.java @@ -0,0 +1,111 @@ +/* + * 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.data.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 new file mode 100644 index 000000000..c386de231 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java @@ -0,0 +1,392 @@ +/* + * 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/value/IrisDuration.java b/src/main/java/art/arcane/iris/engine/object/value/IrisDuration.java new file mode 100644 index 000000000..822bd6962 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisDuration.java @@ -0,0 +1,78 @@ +/* + * 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.iris.engine.object.annotations.Snippet; +import art.arcane.volmlib.util.format.Form; +import lombok.Data; + +import java.util.concurrent.TimeUnit; + +@Snippet("duration") +@Data +@Desc("Represents a combined duration. Fill each property to add time into a single duration") +public class IrisDuration { + @Desc("Milliseconds (1000ms = 1 second)") + private int milliseconds = 0; + + @Desc("Minecraft Ticks (20 minecraft ticks = 1 second)") + private int minecraftTicks = 0; + + @Desc("Seconds (60 seconds = 1 minute)") + private int seconds = 0; + + @Desc("Minutes (60 minutes = 1 hour)") + private int minutes = 0; + + @Desc("Minecraft Hours (about 50 real seconds)") + private int minecraftHours = 0; + + @Desc("Hours (24 hours = 1 day)") + private int hours = 0; + + @Desc("Minecraft Days (1 minecraft day = 20 real minutes)") + private int minecraftDays = 0; + + @Desc("Minecraft Weeks (7 minecraft days = 2 real hours and 20 real minutes)") + private int minecraftWeeks = 0; + + @Desc("Minecraft Lunar Cycles (8 minecraft days = 2 real hours and 40 real minutes)") + private int minecraftLunarCycles = 0; + + @Desc("REAL (not minecraft) Days") + private int days = 0; + + public String toString() { + return Form.duration((double) toMilliseconds(), 2); + } + + public long toMilliseconds() { + return getMilliseconds() + + TimeUnit.SECONDS.toMillis(getSeconds()) + + TimeUnit.MINUTES.toMillis(getMinutes()) + + TimeUnit.HOURS.toMillis(getHours()) + + TimeUnit.DAYS.toMillis(getDays()) + + (getMinecraftTicks() * 50L) + + (getMinecraftHours() * 50000L) + + (getMinecraftDays() * 1_200_000L) + + (getMinecraftWeeks() * 8_400_000L) + + (getMinecraftLunarCycles() * 9_600_000L); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java b/src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java new file mode 100644 index 000000000..c660b9ed1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisPosition.java @@ -0,0 +1,69 @@ +/* + * 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.iris.engine.object.annotations.Snippet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("position-3d") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a position") +@Data +public class IrisPosition { + @Desc("The x position") + private int x = 0; + + @Desc("The y position") + private int y = 0; + + @Desc("The z position") + private int z = 0; + + public IrisPosition(double x, double y, double z) { + this((int) x, (int) y, (int) z); + } + + + public IrisPosition add(IrisPosition relativePosition) { + return new IrisPosition(relativePosition.x + x, relativePosition.y + y, relativePosition.z + z); + } + + public IrisPosition sub(IrisPosition relativePosition) { + return new IrisPosition(x - relativePosition.x, y - relativePosition.y, z - relativePosition.z); + } + + public IrisPosition copy() { + return new IrisPosition(x, y, z); + } + + @Override + public String toString() { + return "[" + getX() + "," + getY() + "," + getZ() + "]"; + } + + public boolean isLongerThan(IrisPosition s, int maxLength) { + return Math.abs(Math.pow(s.x - x, 2) + Math.pow(s.y - y, 2) + Math.pow(s.z - z, 2)) > maxLength * maxLength; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisRange.java b/src/main/java/art/arcane/iris/engine/object/value/IrisRange.java new file mode 100644 index 000000000..9b2a2921e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisRange.java @@ -0,0 +1,59 @@ +/* + * 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.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("range") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a range") +@Data +public class IrisRange { + @Desc("The minimum value") + private double min = 16; + + @Desc("The maximum value") + private double max = 32; + + public double get(RNG rng) { + if (min == max) { + return min; + } + + return rng.d(min, max); + } + + public boolean contains(int v) { + return v >= min && v <= max; + } + + public IrisRange merge(IrisRange other) { + min = Math.min(min, other.min); + max = Math.max(max, other.max); + return this; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisRate.java b/src/main/java/art/arcane/iris/engine/object/value/IrisRate.java new file mode 100644 index 000000000..f347b6085 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisRate.java @@ -0,0 +1,57 @@ +/* + * 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.iris.engine.object.annotations.Snippet; +import art.arcane.volmlib.util.format.Form; +import art.arcane.volmlib.util.scheduling.ChronoLatch; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Snippet("rate") +@NoArgsConstructor +@AllArgsConstructor +@Data +@Desc("Represents a count of something per time duration") +public class IrisRate { + @Desc("The amount of things. Leave 0 for infinite (meaning always spawn whenever)") + private int amount = 0; + + @Desc("The time interval. Leave blank for infinite 0 (meaning always spawn all the time)") + private IrisDuration per = new IrisDuration(); + + public String toString() { + return Form.f(amount) + "/" + per; + } + + public long getInterval() { + long t = per.toMilliseconds() / (amount == 0 ? 1 : amount); + return Math.abs(t <= 0 ? 1 : t); + } + + public ChronoLatch toChronoLatch() { + return new ChronoLatch(getInterval()); + } + + public boolean isInfinite() { + return per.toMilliseconds() == 0; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java b/src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java new file mode 100644 index 000000000..3ec4976cd --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java @@ -0,0 +1,36 @@ +/* + * 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.object.world; + +import art.arcane.iris.engine.object.annotations.Desc; + +@Desc("Represents a world environment") +public enum IrisEnvironment { + @Desc("The overworld environment") + NORMAL, + + @Desc("The nether environment") + NETHER, + + @Desc("The end environment") + THE_END, + + @Desc("A custom environment") + CUSTOM +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java b/src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java new file mode 100644 index 000000000..b4035203c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java @@ -0,0 +1,51 @@ +/* + * 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.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.Snippet; +import art.arcane.iris.spi.PlatformWorld; +import lombok.Data; + +@Snippet("time-block") +@Data +@Desc("Represents a time of day (24h time, not 12h am/pm). Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") +public class IrisTimeBlock { + @Desc("The beginning hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") + private double startHour = 0; + + @Desc("The ending hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") + private double endHour = 0; + + public boolean isWithin(PlatformWorld world) { + return isWithin(((world.getTime() / 1000D) + 6) % 24); + } + + public boolean isWithin(double hour) { + if (startHour == endHour) { + return endHour != -1; + } + + if (startHour > endHour) { + return hour >= startHour || hour <= endHour; + } + + return hour >= startHour && hour <= endHour; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java b/src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java new file mode 100644 index 000000000..db242e502 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java @@ -0,0 +1,46 @@ +/* + * 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.engine.object.annotations.Desc; +import art.arcane.iris.spi.PlatformWorld; + +@Desc("Represents a weather type") +public enum IrisWeather { + @Desc("Represents when weather is not causing downfall") + NONE, + + @Desc("Represents rain or snow") + DOWNFALL, + + @Desc("Represents rain or snow with thunder") + DOWNFALL_WITH_THUNDER, + + @Desc("Any weather") + ANY; + + public boolean is(PlatformWorld world) { + return switch (this) { + case NONE -> !world.isStorming() && !world.isThundering(); + case DOWNFALL -> world.isStorming(); + case DOWNFALL_WITH_THUNDER -> world.isStorming() && world.isThundering(); + case ANY -> true; + }; + } +} 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 new file mode 100644 index 000000000..625e6d15f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/IrisWorld.java @@ -0,0 +1,65 @@ +/* + * 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/IrisWorldBoundary.java b/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java new file mode 100644 index 000000000..d63855e08 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java @@ -0,0 +1,91 @@ +package art.arcane.iris.engine.object.world; + +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.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +import java.util.Objects; + +@Accessors(chain = true) +@NoArgsConstructor +@Desc("The native Minecraft world border applied to worlds using this dimension") +@Data +public class IrisWorldBoundary { + public static final double DEFAULT_DAMAGE_AMOUNT = 0.2D; + public static final double DEFAULT_DAMAGE_BUFFER = 5D; + public static final double MAXIMUM_CENTER = 29_999_984D; + public static final double MAXIMUM_SIZE = 59_999_968D; + + @Desc("The center of the boundary") + private IrisWorldBoundaryCenter center = new IrisWorldBoundaryCenter(); + + @MinNumber(1) + @MaxNumber(59_999_968) + @Desc("The full border diameter in blocks, matching Minecraft world-border terminology") + private double size = 16_384D; + + @MinNumber(0) + @MaxNumber(Integer.MAX_VALUE) + @Desc("Distance from the border at which the client warning begins") + private int warningDistance = 16; + + @MinNumber(0) + @Desc("Safe distance outside the border before damage begins") + private double damageBuffer = DEFAULT_DAMAGE_BUFFER; + + @MinNumber(0) + @Desc("Damage per block beyond damageBuffer") + private double damageAmount = DEFAULT_DAMAGE_AMOUNT; + + public static IrisWorldBoundary snapshot(IrisWorldBoundary configured) { + IrisWorldBoundary source = Objects.requireNonNull(configured, "Configured worldBoundary"); + source.validate(); + return new IrisWorldBoundary() + .setCenter(new IrisWorldBoundaryCenter(source.getCenter().getX(), source.getCenter().getZ())) + .setSize(source.getSize()) + .setWarningDistance(source.getWarningDistance()) + .setDamageBuffer(source.getDamageBuffer()) + .setDamageAmount(source.getDamageAmount()); + } + + public void validate() { + if (center == null) { + throw new IllegalArgumentException("worldBoundary.center is required"); + } + if (!Double.isFinite(center.getX()) || Math.abs(center.getX()) > MAXIMUM_CENTER + || !Double.isFinite(center.getZ()) || Math.abs(center.getZ()) > MAXIMUM_CENTER) { + throw new IllegalArgumentException("worldBoundary.center must be finite and within +/-" + MAXIMUM_CENTER); + } + if (!Double.isFinite(size) || size < 1D || size > MAXIMUM_SIZE) { + throw new IllegalArgumentException("worldBoundary.size must be between 1 and " + MAXIMUM_SIZE); + } + if (warningDistance < 0) { + throw new IllegalArgumentException("worldBoundary.warningDistance cannot be negative"); + } + if (!Double.isFinite(damageBuffer) || damageBuffer < 0D) { + throw new IllegalArgumentException("worldBoundary.damageBuffer must be finite and non-negative"); + } + if (!Double.isFinite(damageAmount) || damageAmount < 0D) { + throw new IllegalArgumentException("worldBoundary.damageAmount must be finite and non-negative"); + } + } + + public double minimumX() { + return center.getX() - size / 2D; + } + + public double maximumX() { + return center.getX() + size / 2D; + } + + public double minimumZ() { + return center.getZ() - size / 2D; + } + + public double maximumZ() { + return center.getZ() + size / 2D; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java b/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java new file mode 100644 index 000000000..a860a437d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java @@ -0,0 +1,29 @@ +package art.arcane.iris.engine.object.world; + +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.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Accessors(chain = true) +@NoArgsConstructor +@Desc("The world-border center in block coordinates") +@Data +public class IrisWorldBoundaryCenter { + @MinNumber(-29_999_984) + @MaxNumber(29_999_984) + @Desc("The world-border center X coordinate") + private double x = 0D; + + @MinNumber(-29_999_984) + @MaxNumber(29_999_984) + @Desc("The world-border center Z coordinate") + private double z = 0D; + + public IrisWorldBoundaryCenter(double x, double z) { + this.x = x; + this.z = z; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java b/src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java new file mode 100644 index 000000000..8256e91e4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java @@ -0,0 +1,36 @@ +/* + * 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.annotations.Desc; + +@Desc("Represents a biome type") +public enum InferredType { + @Desc("Represents any shore biome type") + SHORE, + + @Desc("Represents any land biome type") + LAND, + + @Desc("Represents any sea biome type") + SEA, + + @Desc("Represents any cave biome type") + CAVE +} 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 new file mode 100644 index 000000000..f2bab53ca --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java @@ -0,0 +1,672 @@ +/* + * 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.decoration.IrisDecorationPart; +import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.engine.object.entity.IrisEffect; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.loot.IrisBlockDrops; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.terrain.IrisBiomeLayerGenerator; +import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; +import art.arcane.iris.engine.object.terrain.deposit.IrisBiomeOres; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; +import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; +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.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.data.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 IrisBiomeLayerGenerator}, {@link IrisBiomeDerivatives}, {@link IrisBiomeOres}, + * {@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> surfaceObjectsCache = new AtomicCache<>(); + private final transient AtomicCache> carveObjectsCache = 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 maxHeight = new AtomicCache<>(); + private final transient AtomicCache maxWithObjectHeight = new AtomicCache<>(); + private final transient AtomicCache realCarveBiome = new AtomicCache<>(); + private final transient AtomicCache> realChildren = new AtomicCache<>(); + private final transient AtomicCache> layerHeightGenerators = new AtomicCache<>(); + private final transient AtomicCache> layerSeaHeightGenerators = new AtomicCache<>(); + private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); + private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); + private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); + private final transient AtomicCache undergroundOreBoundsCache = new AtomicCache<>(); + private final transient AtomicCache> decoratorBuckets = 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<>(); + private static final IrisDecorator[] EMPTY_BUCKET = new IrisDecorator[0]; + @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; + @Desc("Spawn Entities in this area over time. Iris will continually replenish these mobs just like vanilla does.") + @ArrayType(min = 1, type = String.class) + @RegistryListResource(IrisSpawner.class) + private KList entitySpawners = new KList<>(); + @ArrayType(min = 1, type = IrisEffect.class) + @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play around the player even if where the effect was played is no longer in the biome the player is in.") + private KList effects = new KList<>(); + @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) + @Desc("This changes the dispersion of the biome colors if multiple derivatives are chosen.") + private IrisGeneratorStyle biomeStyle = NoiseStyle.SIMPLEX.style(); + @ArrayType(min = 1, type = IrisBlockDrops.class) + @Desc("Define custom block drops for this biome") + private KList blockDrops = new KList<>(); + @Desc("Reference loot tables in this area") + private IrisLootReference loot = new IrisLootReference(); + @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") + private boolean lockLayers = false; + @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") + private int lockLayersMax = 7; + @Desc("Profile-driven 3D cave configuration") + private IrisCaveProfile caveProfile = new IrisCaveProfile(); + @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<>(); + @RegistryListResource(IrisBiome.class) + @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") + private String carvingBiome = ""; + @MinNumber(0) + @MaxNumber(256) + @Desc("Minimum depth below terrain surface required before this cave biome can be selected.") + private int caveMinDepthBelowSurface = 0; + @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") + private IrisBiomePaletteLayer slab = new IrisBiomePaletteLayer().zero(); + @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") + private IrisBiomePaletteLayer wall = new IrisBiomePaletteLayer().zero(); + @Required + @ArrayType(type = IrisBiomePaletteLayer.class) + @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") + private KList layers = new KList().qadd(new IrisBiomePaletteLayer()); + @ArrayType(type = IrisBiomePaletteLayer.class) + @Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") + private KList caveCeilingLayers = new KList<>(); + @ArrayType(type = IrisBiomePaletteLayer.class) + @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") + private KList seaLayers = new KList<>(); + @ArrayType(min = 1, type = IrisDecorator.class) + @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") + private KList decorators = new KList<>(); + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @Desc("Objects define what schematics (iob files) iris will place in this biome") + private KList objects = new KList<>(); + @Desc("Procedural objects (such as trees) iris generates from scratch and places in this biome, instead of loading them from iob files") + private IrisProceduralObjects proceduralObjects = new IrisProceduralObjects(); + @ArrayType(min = 1, type = IrisStructurePlacement.class) + @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this biome") + private KList structures = new KList<>(); + @ArrayType(min = 1, type = IrisFloatingChildBiomes.class) + @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") + private KList floatingChildBiomes = new KList<>(); + @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") + private boolean mergeFloatingChildBiomes = false; + @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()); + @ArrayType(min = 1, type = IrisDepositGenerator.class) + @Desc("Define biome deposit generators that add onto the existing regional and global deposit generators") + private KList deposits = new KList<>(); + @MinNumber(0) + @MaxNumber(1) + @Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") + private double oreDepositFrequencyMultiplier = 1D; + @MinNumber(0.01) + @MaxNumber(16) + @Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") + private double oreDepositSizeMultiplier = 1D; + @ArrayType(min = 1, type = IrisDepositVariant.class) + @Desc("Deposit ore remap rules scoped to this biome. Each entry declares a vertical band and a source->replacement block id map. Applied before regional and dimension rules; first matching biome rule wins.") + private KList depositVariants = new KList<>(); + private transient volatile InferredType inferredType; + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + private final transient EnumMap inferredVariants = new EnumMap<>(InferredType.class); + @Desc("Collection of ores to be generated") + @ArrayType(type = IrisOreGenerator.class, min = 1) + private KList ores = new KList<>(); + + public PlatformBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { + return IrisBiomeOres.generateOres(this, x, y, z, rng, data, surface); + } + + public PlatformBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { + return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data); + } + + public PlatformBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { + return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, data); + } + + public boolean hasSurfaceOres() { + return IrisBiomeOres.hasSurfaceOres(this); + } + + public boolean hasUndergroundOres() { + return IrisBiomeOres.hasUndergroundOres(this); + } + + 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.inferredType = type; + inferredVariants.put(type, variant); + return variant; + } + + /** + * Hand written override of the Lombok setter. It must stay here because it invalidates the ore + * caches that {@link IrisBiomeOres} reads. + */ + public void setOres(KList ores) { + this.ores = ores == null ? new KList<>() : ores; + surfaceOreCache.reset(); + undergroundOreCache.reset(); + surfaceOreBoundsCache.reset(); + undergroundOreBoundsCache.reset(); + } + + public KList getSurfaceOreGenerators() { + return IrisBiomeOres.getSurfaceOreGenerators(this); + } + + public KList getUndergroundOreGenerators() { + return IrisBiomeOres.getUndergroundOreGenerators(this); + } + + public IrisOreGeneratorBounds getSurfaceOreGeneratorBounds() { + return IrisBiomeOres.getSurfaceOreGeneratorBounds(this); + } + + public IrisOreGeneratorBounds getUndergroundOreGeneratorBounds() { + return IrisBiomeOres.getUndergroundOreGeneratorBounds(this); + } + + 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 IrisBiome getRealCarvingBiome(IrisData data) { + return realCarveBiome.aquire(() -> + { + IrisBiome biome = data.getBiomeLoader().load(getCarvingBiome()); + + if (biome == null) { + biome = this; + } + + return biome; + }); + } + + public KList getSurfaceObjects() { + return getSurfaceObjectsCache().aquire(() -> + { + KList o = getObjects().copy(); + + for (IrisObjectPlacement i : o.copy()) { + if (!i.getCarvingSupport().supportsSurface()) { + o.remove(i); + } + } + + return o; + }); + } + + public KList getCarvingObjects() { + return getCarveObjectsCache().aquire(() -> + { + KList o = getObjects().copy(); + + for (IrisObjectPlacement i : o.copy()) { + if (!i.getCarvingSupport().supportsCarving()) { + o.remove(i); + } + } + + return o; + }); + } + + 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 KList generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { + return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex); + } + + public KList generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { + return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex); + } + + public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { + return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, rdata, complex); + } + + public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) { + return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata); + } + + /** + * Note the arity split: {@code getMaxHeight()} is the Lombok getter for the height cache field, + * {@code getMaxHeight(Engine)} is the resolved biome height. + */ + public int getMaxHeight(Engine engine) { + return IrisBiomeLayerGenerator.getMaxHeight(this, engine); + } + + public int getMaxWithObjectHeight(IrisData data, Engine engine) { + return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine); + } + + public KList getLayerHeightGenerators(RNG rng, IrisData rdata) { + return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata); + } + + public KList getLayerSeaHeightGenerators(RNG rng, IrisData data) { + return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data); + } + + public PlatformBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) { + return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm); + } + + 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 IrisDecorator[] getDecoratorBucket(IrisDecorationPart part) { + return decoratorBuckets.aquire(this::buildDecoratorBuckets).getOrDefault(part, EMPTY_BUCKET); + } + + private EnumMap buildDecoratorBuckets() { + EnumMap> staging = new EnumMap<>(IrisDecorationPart.class); + for (IrisDecorator d : decorators) { + staging.computeIfAbsent(d.getPartOf(), k -> new KList<>()).add(d); + } + EnumMap result = new EnumMap<>(IrisDecorationPart.class); + for (IrisDecorationPart part : IrisDecorationPart.values()) { + KList list = staging.get(part); + result.put(part, list == null ? EMPTY_BUCKET : list.toArray(EMPTY_BUCKET)); + } + return result; + } + + 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 new file mode 100644 index 000000000..ec1bdcb93 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeColorRenderer.java @@ -0,0 +1,95 @@ +/* + * 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.decoration.IrisDecorator; +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 : biome.getObjects()) { + density += i.getDensity() * i.getChance(); + } + + return Color.getHSBColor(0.225f, (float) (density / engine.getMaxBiomeObjectDensity()), 1f); + }); + } + case DECORATOR_LOAD -> { + return biome.getCacheColorDecoratorLoad().aquire(() -> { + double density = 0; + + for (IrisDecorator i : biome.getDecorators()) { + density += i.getChance() * Math.min(1, i.getStackMax()) * 256; + } + + return Color.getHSBColor(0.41f, (float) (density / engine.getMaxBiomeDecoratorDensity()), 1f); + }); + } + case LAYER_LOAD -> { + return biome.getCacheColorLayerLoad().aquire(() -> Color.getHSBColor(0.625f, (float) (biome.getLayers().size() / engine.getMaxBiomeLayerDensity()), 1f)); + } + } + + return Color.black; + } +} 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 new file mode 100644 index 000000000..5813c9475 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java @@ -0,0 +1,153 @@ +/* + * 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 new file mode 100644 index 000000000..054ce6671 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGenLinks.java @@ -0,0 +1,137 @@ +/* + * 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.data.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 new file mode 100644 index 000000000..f7df46944 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGeneratorLink.java @@ -0,0 +1,90 @@ +/* + * 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.iris.engine.data.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 new file mode 100644 index 000000000..ebd3ae383 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustom.java @@ -0,0 +1,234 @@ +/* + * 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/IrisBiomeCustomCategory.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java new file mode 100644 index 000000000..a9727d366 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java @@ -0,0 +1,75 @@ +/* + * 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.engine.object.annotations.Desc; + +@Desc("The custom biome category. Vanilla asks for this, basically what represents your biome closest?") +public enum IrisBiomeCustomCategory { + @Desc("Tags the generated datapack biome as vanilla category 'beach' (shoreline biomes).") + beach, + + @Desc("Tags the generated datapack biome as vanilla category 'desert' (hot, dry sand biomes).") + desert, + + @Desc("Tags the generated datapack biome as vanilla category 'extreme_hills' (mountain biomes).") + extreme_hills, + + @Desc("Tags the generated datapack biome as vanilla category 'forest' (tree-dense temperate biomes).") + forest, + + @Desc("Tags the generated datapack biome as vanilla category 'icy' (snow and ice biomes).") + icy, + + @Desc("Tags the generated datapack biome as vanilla category 'jungle'.") + jungle, + + @Desc("Tags the generated datapack biome as vanilla category 'mesa' (badlands).") + mesa, + + @Desc("Tags the generated datapack biome as vanilla category 'mushroom' (mushroom fields).") + mushroom, + + @Desc("Tags the generated datapack biome as vanilla category 'nether'.") + nether, + + @Desc("Tags the generated datapack biome as vanilla category 'none' (no classification).") + none, + + @Desc("Tags the generated datapack biome as vanilla category 'ocean'.") + ocean, + + @Desc("Tags the generated datapack biome as vanilla category 'plains'. This is the default when category is omitted.") + plains, + + @Desc("Tags the generated datapack biome as vanilla category 'river'.") + river, + + @Desc("Tags the generated datapack biome as vanilla category 'savanna'.") + savanna, + + @Desc("Tags the generated datapack biome as vanilla category 'swamp'.") + swamp, + + @Desc("Tags the generated datapack biome as vanilla category 'taiga'.") + taiga, + + @Desc("Tags the generated datapack biome as vanilla category 'the_end'.") + the_end +} 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 new file mode 100644 index 000000000..8d29d8d4f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java @@ -0,0 +1,69 @@ +/* + * 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.engine.data.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/IrisBiomeCustomPrecipType.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java new file mode 100644 index 000000000..d54a7e1fe --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java @@ -0,0 +1,33 @@ +/* + * 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.engine.object.annotations.Desc; + +@Desc("Snow, rain, or nothing") +public enum IrisBiomeCustomPrecipType { + @Desc("No downfall") + none, + + @Desc("Rain downfall") + rain, + + @Desc("Snow downfall") + snow +} 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 new file mode 100644 index 000000000..64a95d57c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java @@ -0,0 +1,85 @@ +/* + * 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.engine.data.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/biome/custom/IrisBiomeCustomSpawnType.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java new file mode 100644 index 000000000..afeb577ea --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java @@ -0,0 +1,48 @@ +/* + * 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.engine.object.annotations.Desc; + +@Desc("The mob spawn group") +public enum IrisBiomeCustomSpawnType { + @Desc("Typical monsters that spawn at night, like zombies and skeletons") + MONSTER, + + @Desc("Typical creatures like sheep, pigs, cows") + CREATURE, + + @Desc("Eg bats") + AMBIENT, + + @Desc("Axolotls") + AXOLOTLS, + + @Desc("Odd spawn group but ok") + UNDERGROUND_WATER_CREATURE, + + @Desc("Water mobs like squid, dolphins") + WATER_CREATURE, + + @Desc("Fish") + WATER_AMBIENT, + + @Desc("Unknown") + MISC +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java new file mode 100644 index 000000000..40eb0ea02 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java @@ -0,0 +1,185 @@ +/* + * 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.biome.custom; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * Direct vanilla biome tag membership, generated from the MC 26.2 built-in datapack + * (data/minecraft/tags/worldgen/biome). Used to give Iris custom biomes the tag membership of the vanilla + * biome they derive from, so tag selectors written by vanilla and by mods (#minecraft:is_overworld and + * friends) resolve against Iris terrain. + * + *

Only DIRECT membership is listed. Vanilla's derived tags reference other tags rather than repeating + * biomes (#minecraft:is_ocean includes #minecraft:is_deep_ocean, water_on_map_outlines includes + * #minecraft:is_river, and so on), so adding a custom biome to the direct tags carries it into the derived + * tags for free. + * + *

The has_structure/* tags are deliberately absent. Iris resolves native structure placement through the + * biome's structure derivative, never through the custom biome, so injecting custom biomes there would place + * a structure twice. + * + *

{@code stronghold_biased_to} is absent for the same reason, even though it is not a has_structure tag. + * It is a structure-placement input: {@code worldgen/structure_set/strongholds.json} reads it as + * {@code preferred_biomes} when it rings strongholds around spawn. Inheriting it would enter every Iris biome + * derived from a tagged vanilla biome into that ring - which is the entire overworld surface of a typical pack - + * and let vanilla place strongholds where the pack's own structure configuration did not ask for them. + * + *

An unknown key (a mod biome, a datapack biome, or a vanilla biome added after 26.2) contributes nothing; + * the pack author's explicit tags still apply. + */ +public final class IrisVanillaBiomeTags { + private static final String TAG_NAMESPACE = "minecraft:"; + private static final Map> DIRECT_TAGS = new HashMap<>(96); + + private IrisVanillaBiomeTags() { + } + + /** + * Tags the given vanilla biome key belongs to directly. Never null; empty for unknown keys. Keys are + * returned fully namespaced and lowercase. + */ + public static List tagsFor(String biomeKey) { + if (biomeKey == null || biomeKey.isBlank()) { + return List.of(); + } + String normalized = biomeKey.trim().toLowerCase(Locale.ROOT); + if (normalized.indexOf(':') < 0) { + normalized = TAG_NAMESPACE + normalized; + } + List tags = DIRECT_TAGS.get(normalized); + return tags == null ? List.of() : tags; + } + + static int knownBiomeCount() { + return DIRECT_TAGS.size(); + } + + private static void put(String biomeKey, String... tagPaths) { + String[] namespaced = new String[tagPaths.length]; + for (int i = 0; i < tagPaths.length; i++) { + namespaced[i] = TAG_NAMESPACE + tagPaths[i]; + } + DIRECT_TAGS.put(biomeKey, List.of(namespaced)); + } + + static { + put("minecraft:badlands", "is_badlands", "is_overworld"); + put("minecraft:bamboo_jungle", "is_jungle", "is_overworld"); + put("minecraft:basalt_deltas", "is_nether"); + put("minecraft:beach", "is_beach", "is_overworld"); + put("minecraft:birch_forest", "is_forest", "is_overworld"); + put("minecraft:cherry_grove", "is_mountain", "is_overworld"); + put("minecraft:cold_ocean", "is_ocean", "is_overworld", "spawns_cold_variant_farm_animals"); + put("minecraft:crimson_forest", "is_nether"); + put("minecraft:dark_forest", "is_forest", "is_overworld"); + put("minecraft:deep_cold_ocean", "is_deep_ocean", "is_overworld", "spawns_cold_variant_farm_animals"); + put("minecraft:deep_dark", + "is_overworld", "mineshaft_blocking", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs"); + put("minecraft:deep_frozen_ocean", + "is_deep_ocean", "is_overworld", "polar_bears_spawn_on_alternate_blocks", "spawns_cold_variant_farm_animals", + "spawns_cold_variant_frogs"); + put("minecraft:deep_lukewarm_ocean", "is_deep_ocean", "is_overworld", "spawns_warm_variant_farm_animals"); + put("minecraft:deep_ocean", "is_deep_ocean", "is_overworld"); + put("minecraft:desert", + "is_overworld", "spawns_gold_rabbits", "spawns_warm_variant_farm_animals", "spawns_warm_variant_frogs"); + put("minecraft:dripstone_caves", "is_overworld"); + put("minecraft:end_barrens", "is_end"); + put("minecraft:end_highlands", "is_end"); + put("minecraft:end_midlands", "is_end"); + put("minecraft:eroded_badlands", "is_badlands", "is_overworld"); + put("minecraft:flower_forest", "is_forest", "is_overworld"); + put("minecraft:forest", "is_forest", "is_overworld"); + put("minecraft:frozen_ocean", + "is_ocean", "is_overworld", "polar_bears_spawn_on_alternate_blocks", "spawns_cold_variant_farm_animals", + "spawns_cold_variant_frogs", "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:frozen_peaks", + "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:frozen_river", + "is_overworld", "is_river", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:grove", + "is_forest", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:ice_spikes", + "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", "spawns_snow_foxes", + "spawns_white_rabbits"); + put("minecraft:jagged_peaks", + "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:jungle", "is_jungle", "is_overworld"); + put("minecraft:lukewarm_ocean", "is_ocean", "is_overworld", "spawns_warm_variant_farm_animals"); + put("minecraft:lush_caves", "allows_tropical_fish_spawns_at_any_height", "is_overworld"); + put("minecraft:mangrove_swamp", + "allows_surface_slime_spawns", "is_overworld", "spawns_warm_variant_farm_animals", + "spawns_warm_variant_frogs", "water_on_map_outlines"); + put("minecraft:meadow", "is_mountain", "is_overworld"); + put("minecraft:mushroom_fields", "is_overworld", "without_zombie_sieges"); + put("minecraft:nether_wastes", "is_nether"); + put("minecraft:ocean", "is_ocean", "is_overworld"); + put("minecraft:old_growth_birch_forest", "is_forest", "is_overworld"); + put("minecraft:old_growth_pine_taiga", + "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals"); + put("minecraft:old_growth_spruce_taiga", + "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals"); + put("minecraft:pale_garden", "is_forest", "is_overworld"); + put("minecraft:plains", "is_overworld"); + put("minecraft:river", "is_overworld", "is_river"); + put("minecraft:savanna", "is_overworld", "is_savanna"); + put("minecraft:savanna_plateau", "is_overworld", "is_savanna"); + put("minecraft:small_end_islands", "is_end"); + put("minecraft:snowy_beach", + "is_beach", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:snowy_plains", + "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", "spawns_snow_foxes", + "spawns_white_rabbits"); + put("minecraft:snowy_slopes", + "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:snowy_taiga", + "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", + "spawns_snow_foxes", "spawns_white_rabbits"); + put("minecraft:soul_sand_valley", "is_nether"); + put("minecraft:sparse_jungle", "is_jungle", "is_overworld"); + put("minecraft:stony_peaks", "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals"); + put("minecraft:stony_shore", "is_overworld"); + put("minecraft:sulfur_caves", "is_overworld"); + put("minecraft:sunflower_plains", "is_overworld"); + put("minecraft:swamp", "allows_surface_slime_spawns", "is_overworld", "water_on_map_outlines"); + put("minecraft:taiga", "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals"); + put("minecraft:the_end", "is_end"); + put("minecraft:the_void", "without_wandering_trader_spawns"); + put("minecraft:warm_ocean", + "is_ocean", "is_overworld", "produces_corals_from_bonemeal", "spawns_coral_variant_zombie_nautilus", + "spawns_warm_variant_farm_animals", "spawns_warm_variant_frogs"); + put("minecraft:warped_forest", "is_nether"); + put("minecraft:windswept_forest", + "is_hill", "is_overworld", "spawns_cold_variant_farm_animals"); + put("minecraft:windswept_gravelly_hills", + "is_hill", "is_overworld", "spawns_cold_variant_farm_animals"); + put("minecraft:windswept_hills", "is_hill", "is_overworld", "spawns_cold_variant_farm_animals"); + put("minecraft:windswept_savanna", "is_overworld", "is_savanna"); + put("minecraft:wooded_badlands", "is_badlands", "is_overworld"); + } +} 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 new file mode 100644 index 000000000..899ccc241 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java @@ -0,0 +1,957 @@ +/* + * 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.decoration.IrisImportedFeatureControl; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +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.loot.IrisBlockDrops; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.material.IrisMaterialPalette; +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.procedural.tree.IrisTreeSettings; +import art.arcane.iris.engine.object.runtime.StudioMode; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; +import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; +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.spi.PlatformBlockState; +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.iris.engine.data.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.mantle.flag.MantleFlag; +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.HashMap; +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<>(); + private final transient AtomicCache> carvingEntryIndex = new AtomicCache<>(); + private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); + private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); + private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); + private final transient AtomicCache undergroundOreBoundsCache = 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("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") + private boolean explodeBiomePalettes = false; + @Desc("Studio Mode for testing different parts of the world") + private StudioMode studioMode = StudioMode.NORMAL; + @MinNumber(1) + @MaxNumber(16) + @Desc("Customize the palette height explosion") + private int explodeBiomePaletteSize = 3; + @MinNumber(2) + @MaxNumber(16) + @Desc("Every X/Z % debugCrossSectionsMod == 0 cuts the chunk") + private int debugCrossSectionsMod = 3; + @Desc("Tree growth override settings") + private IrisTreeSettings treeSettings = new IrisTreeSettings(); + @Desc("Spawn Entities in this dimension over time. Iris will continually replenish these mobs just like vanilla does.") + @ArrayType(min = 1, type = String.class) + @RegistryListResource(IrisSpawner.class) + private KList entitySpawners = new KList<>(); + @Desc("Reference loot tables in this area") + private IrisLootReference loot = new IrisLootReference(); + @MinNumber(0) + @Desc("The version of this dimension. Changing this will stop users from accidentally upgrading (and breaking their worlds).") + private int version = 1; + @ArrayType(min = 1, type = IrisBlockDrops.class) + @Desc("Define custom block drops for this dimension") + private KList blockDrops = new KList<>(); + @Desc("Should bedrock be generated or not.") + private boolean bedrock = true; + @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("Generate decorations or not") + private boolean decorate = true; + @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") + private boolean hideOresForHiddenOre = false; + @Desc("Use post processing or not") + private boolean postProcessing = true; + @Desc("Add slabs in post processing") + private boolean postProcessingSlabs = true; + @Desc("Add painted walls in post processing") + private boolean postProcessingWalls = true; + @Desc("Enable or disable all carving for this dimension") + private boolean carvingEnabled = true; + @ArrayType(type = IrisDimensionCarvingEntry.class, min = 1) + @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") + private KList carving = new KList<>(); + @Desc("Profile-driven 3D cave configuration") + private IrisCaveProfile caveProfile = new IrisCaveProfile(); + @Desc("Refuse to place surface objects and trees over carved surface openings.") + private boolean requireObjectSurfaceSupport = true; + @MinNumber(0) + @MaxNumber(16) + @Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") + private int objectSurfaceSupportBuffer = 2; + @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; + @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") + private boolean upperDimensionCarving = false; + @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") + private boolean upperDimensionObjects = false; + @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") + private boolean upperObjectsForcePlace = false; + @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; + @Required + @Desc("Define the mode of this dimension (required!)") + private IrisDimensionMode mode = new IrisDimensionMode(); + @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 = IrisDepositGenerator.class) + @Desc("Define global deposit generators") + private KList deposits = new KList<>(); + @ArrayType(min = 1, type = IrisDepositVariant.class) + @Desc("Dimension-wide deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied after biome and region rules; first matching dimension rule wins.") + private KList depositVariants = new KList<>(); + @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) + @Desc("Overlay additional noise on top of the interoplated terrain.") + private KList overlayNoise = new KList<>(); + @Desc("The palette of blocks for 'stone'") + private IrisMaterialPalette rockPalette = new IrisMaterialPalette().qclear().qadd("stone"); + @Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") + private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("water"); + @Desc("Collection of ores to be generated") + @ArrayType(type = IrisOreGenerator.class, min = 1) + private KList ores = new KList<>(); + @Desc("Dimension-wide Iris structure placements, independent of biome/region placements") + @ArrayType(type = IrisStructurePlacement.class, min = 1) + private KList structures = new KList<>(); + @Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure is enabled by default; 'disabled' is the sole generation deny list and autocompletes live structure keys.") + private IrisImportedStructureControl importedStructures = new IrisImportedStructureControl(); + @Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation (ores, trees, plants, springs, geodes) for this dimension. Disabled by default: leaving this out generates exactly the terrain Iris always has. Set 'enabled' true to run the vanilla decoration feature pass over Iris terrain. Carvers are never imported.") + private IrisImportedFeatureControl importedFeatures = new IrisImportedFeatureControl(); + @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<>(); + @MinNumber(0) + @MaxNumber(318) + @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") + private int caveLavaHeight = 8; + @RegistryListFunction(ComponentFlagFunction.class) + @ArrayType(type = String.class) + @Desc("Collection of disabled components") + private KList disabledComponents = new KList<>(); + + public int getMaxHeight() { + return (int) getDimensionHeight().getMax(); + } + + public int getMinHeight() { + return (int) getDimensionHeight().getMin(); + } + + public Map getCarvingEntryIndex() { + return carvingEntryIndex.aquire(() -> { + Map index = new HashMap<>(); + KList entries = getCarving(); + if (entries == null || entries.isEmpty()) { + return index; + } + + for (IrisDimensionCarvingEntry entry : entries) { + if (entry == null) { + continue; + } + + String entryId = entry.getId(); + if (entryId == null || entryId.isBlank()) { + continue; + } + + index.put(entryId.trim(), entry); + } + + return index; + }); + } + + public void setCarving(KList carving) { + this.carving = carving == null ? new KList<>() : carving; + carvingEntryIndex.reset(); + } + + public PlatformBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { + KList localOres = surface ? getSurfaceOres() : getUndergroundOres(); + return generateOres(localOres, x, y, z, rng, data); + } + + public PlatformBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { + return generateOres(getSurfaceOres(), x, y, z, rng, data); + } + + public PlatformBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { + return generateOres(getUndergroundOres(), x, y, z, rng, data); + } + + public boolean hasSurfaceOres() { + return !getSurfaceOres().isEmpty(); + } + + public boolean hasUndergroundOres() { + return !getUndergroundOres().isEmpty(); + } + + private PlatformBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { + if (localOres.isEmpty()) { + return null; + } + + int oreCount = localOres.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = localOres.get(oreIndex); + PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); + if (ore != null) { + return ore; + } + } + return null; + } + + public void setOres(KList ores) { + this.ores = ores == null ? new KList<>() : ores; + surfaceOreCache.reset(); + undergroundOreCache.reset(); + surfaceOreBoundsCache.reset(); + undergroundOreBoundsCache.reset(); + } + + public KList getSurfaceOreGenerators() { + return getOres(true); + } + + public KList getUndergroundOreGenerators() { + return getOres(false); + } + + public IrisOreGeneratorBounds getSurfaceOreGeneratorBounds() { + return surfaceOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getSurfaceOres())); + } + + public IrisOreGeneratorBounds getUndergroundOreGeneratorBounds() { + return undergroundOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getUndergroundOres())); + } + + private KList getSurfaceOres() { + return getOres(true); + } + + private KList getUndergroundOres() { + return getOres(false); + } + + private KList getOres(boolean surface) { + AtomicCache> oreCache = surface ? surfaceOreCache : undergroundOreCache; + return oreCache.aquire(() -> { + KList filtered = new KList<>(); + KList localOres = ores; + int oreCount = localOres.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = localOres.get(oreIndex); + if (oreGenerator.isGenerateSurface() == surface) { + filtered.add(oreGenerator); + } + } + + return filtered; + }); + } + + 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)); + } + } + + KList carvingEntries = getCarving(); + if (carvingEntries != null) { + for (IrisDimensionCarvingEntry entry : carvingEntries) { + if (entry != null && entry.isEnabled()) { + addReachableBiomeKey(pending, entry.getBiome()); + } + } + } + + Set visited = new HashSet<>(); + Map carvingEntryIndex = getCarvingEntryIndex(); + 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()); + addReachableBiomeKey(pending, biome.getCarvingBiome()); + KList floatingChildren = biome.getFloatingChildBiomes(); + if (floatingChildren == null) { + continue; + } + for (IrisFloatingChildBiomes floatingChild : floatingChildren) { + if (floatingChild != null) { + addReachableBiomeKey(pending, floatingChild.getBiome()); + String carvingReference = floatingChild.getCarving(); + IrisDimensionCarvingEntry carvingEntry = carvingEntryIndex.get(carvingReference); + addReachableBiomeKey(pending, + carvingEntry == null ? carvingReference : carvingEntry.getBiome()); + } + } + } + + 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/IrisDimensionContractException.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java new file mode 100644 index 000000000..d23bd3d54 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java @@ -0,0 +1,25 @@ +/* + * 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; + +public final class IrisDimensionContractException extends IllegalStateException { + public IrisDimensionContractException(String message) { + super(message); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java new file mode 100644 index 000000000..fc2f39358 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java @@ -0,0 +1,43 @@ +/* + * 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.framework.Engine; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.object.annotations.Desc; +import art.arcane.iris.engine.object.annotations.Snippet; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; + +@Snippet("dimension-mode") +@Accessors(chain = true) +@NoArgsConstructor +@AllArgsConstructor +@Desc("Represents a dimensional mode") +@Data +public class IrisDimensionMode { + @Desc("The dimension type") + private IrisDimensionModeType type = IrisDimensionModeType.OVERWORLD; + + public EngineMode create(Engine engine) { + return type.create(engine); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java new file mode 100644 index 000000000..c2a248b3c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java @@ -0,0 +1,54 @@ +/* + * 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.framework.Engine; +import art.arcane.iris.engine.framework.EngineMode; +import art.arcane.iris.engine.mode.ModeEnclosure; +import art.arcane.iris.engine.mode.ModeIslands; +import art.arcane.iris.engine.mode.ModeOverworld; +import art.arcane.iris.engine.mode.ModeSuperFlat; +import art.arcane.iris.engine.object.annotations.Desc; + +import java.util.function.Function; + +@Desc("The type of dimension this is") +public enum IrisDimensionModeType { + @Desc("Typical dimensions. Has a fluid height, and all features of a biome based world") + OVERWORLD(ModeOverworld::new), + + @Desc("Ultra fast, but very limited in features. Only supports terrain & biomes. No decorations, mobs, objects, or anything of the sort!") + SUPERFLAT(ModeSuperFlat::new), + + @Desc("Like the nether, a ceiling & floor carved out") + ENCLOSURE(ModeEnclosure::new), + + @Desc("Floating islands of terrain") + ISLANDS(ModeIslands::new), + ; + private final Function factory; + + IrisDimensionModeType(Function factory) { + this.factory = factory; + } + + public EngineMode create(Engine e) { + return factory.apply(e); + } +} 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 new file mode 100644 index 000000000..6b52da104 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionRuntimeContract.java @@ -0,0 +1,133 @@ +/* + * 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 new file mode 100644 index 000000000..468eec2ac --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionType.java @@ -0,0 +1,104 @@ +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 new file mode 100644 index 000000000..875d5efa0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionTypeOptions.java @@ -0,0 +1,324 @@ +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 new file mode 100644 index 000000000..59a08e80c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java @@ -0,0 +1,478 @@ +/* + * 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.entity.IrisEffect; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.loot.IrisBlockDrops; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; +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.spi.PlatformBlockState; +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.engine.data.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> surfaceObjectsCache = new AtomicCache<>(); + private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(); + 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<>(); + private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); + private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); + private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); + private final transient AtomicCache undergroundOreBoundsCache = new AtomicCache<>(); + @MinNumber(2) + @Required + @Desc("The name of the region") + private String name = "A Region"; + @ArrayType(min = 1, type = IrisEffect.class) + @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") + private KList effects = new KList<>(); + @Desc("Spawn Entities in this region over time. Iris will continually replenish these mobs just like vanilla does.") + @ArrayType(min = 1, type = String.class) + @RegistryListResource(IrisSpawner.class) + private KList entitySpawners = new KList<>(); + @MinNumber(1) + @MaxNumber(128) + @Desc("The rarity of the region") + private int rarity = 1; + @ArrayType(min = 1, type = IrisBlockDrops.class) + @Desc("Define custom block drops for this region") + private KList blockDrops = new KList<>(); + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @Desc("Objects define what schematics (iob files) iris will place in this region") + private KList objects = new KList<>(); + @Desc("Procedural objects (trees, ruins, formations, coral, fungi, crystals) iris generates from scratch and places across this region") + private IrisProceduralObjects proceduralObjects = new IrisProceduralObjects(); + @ArrayType(min = 1, type = IrisStructurePlacement.class) + @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this region") + private KList structures = new KList<>(); + @MinNumber(0) + @Desc("The min shore height") + private double shoreHeightMin = 1.2; + @Desc("Reference loot tables in this area") + private IrisLootReference loot = new IrisLootReference(); + @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; + @Desc("Profile-driven 3D cave configuration") + private IrisCaveProfile caveProfile = new IrisCaveProfile(); + @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<>(); + @ArrayType(min = 1, type = IrisDepositGenerator.class) + @Desc("Define regional deposit generators that add onto the global deposit generators") + private KList deposits = new KList<>(); + @ArrayType(min = 1, type = IrisDepositVariant.class) + @Desc("Deposit ore remap rules scoped to this region. Each entry declares a vertical band and a source->replacement block id map. Applied after biome rules but before dimension rules; first matching region rule wins.") + private KList depositVariants = 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; + @Desc("Collection of ores to be generated") + @ArrayType(type = IrisOreGenerator.class, min = 1) + private KList ores = new KList<>(); + + public PlatformBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { + KList localOres = surface ? getSurfaceOres() : getUndergroundOres(); + return generateOres(localOres, x, y, z, rng, data); + } + + public PlatformBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { + return generateOres(getSurfaceOres(), x, y, z, rng, data); + } + + public PlatformBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { + return generateOres(getUndergroundOres(), x, y, z, rng, data); + } + + public boolean hasSurfaceOres() { + return !getSurfaceOres().isEmpty(); + } + + public boolean hasUndergroundOres() { + return !getUndergroundOres().isEmpty(); + } + + private PlatformBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { + if (localOres.isEmpty()) { + return null; + } + + int oreCount = localOres.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = localOres.get(oreIndex); + PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); + if (ore != null) { + return ore; + } + } + return null; + } + + public void setOres(KList ores) { + this.ores = ores == null ? new KList<>() : ores; + surfaceOreCache.reset(); + undergroundOreCache.reset(); + surfaceOreBoundsCache.reset(); + undergroundOreBoundsCache.reset(); + } + + public KList getSurfaceOreGenerators() { + return getOres(true); + } + + public KList getUndergroundOreGenerators() { + return getOres(false); + } + + public IrisOreGeneratorBounds getSurfaceOreGeneratorBounds() { + return surfaceOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getSurfaceOres())); + } + + public IrisOreGeneratorBounds getUndergroundOreGeneratorBounds() { + return undergroundOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getUndergroundOres())); + } + + private KList getSurfaceOres() { + return getOres(true); + } + + private KList getUndergroundOres() { + return getOres(false); + } + + private KList getOres(boolean surface) { + AtomicCache> oreCache = surface ? surfaceOreCache : undergroundOreCache; + return oreCache.aquire(() -> { + KList filtered = new KList<>(); + KList localOres = ores; + int oreCount = localOres.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = localOres.get(oreIndex); + if (oreGenerator.isGenerateSurface() == surface) { + filtered.add(oreGenerator); + } + } + + return filtered; + }); + } + + public String getName() { + return name; + } + + public KList getSurfaceObjects() { + return getSurfaceObjectsCache().aquire(() -> + { + KList o = getObjects().copy(); + + for (IrisObjectPlacement i : o.copy()) { + if (!i.getCarvingSupport().supportsSurface()) { + o.remove(i); + } + } + + return o; + }); + } + + public KList getCarvingObjects() { + return getCarveObjectsCache().aquire(() -> + { + KList o = getObjects().copy(); + + for (IrisObjectPlacement i : o.copy()) { + if (!i.getCarvingSupport().supportsCarving()) { + o.remove(i); + } + } + + return o; + }); + } + + 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.add(biome.getCarvingBiome()); + 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.add(biome.getCarvingBiome()); + 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"; + } +} From 72cc04e20fcc42261b7186ae022b84e54d902ab2 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 6 Oct 2026 14:17:54 +0200 Subject: [PATCH 002/139] Apply Iris's Lombok settings to these sources Lombok looks for lombok.config upward from each source file and never reaches ../Iris, so these classes were compiled with getter-based equals/hashCode/toString. IrisBiome's then linked against org.bukkit and failed the Bukkit purity gate once it was recompiled. --- lombok.config | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 lombok.config diff --git a/lombok.config b/lombok.config new file mode 100644 index 000000000..5e8c64b0e --- /dev/null +++ b/lombok.config @@ -0,0 +1,6 @@ +# 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. +config.stopBubbling = true +lombok.equalsAndHashCode.doNotUseGetters = true +lombok.toString.doNotUseGetters = true From 522a9c85b69cfbabd8f5927b2d3e1725693391c5 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 08:33:42 +0200 Subject: [PATCH 003/139] Port object placement onto IrisApi modules and delete the lifecycle - The built-in placement is now eight IrisApi modules: iris:prepare, iris:anchor, iris:validate, iris:bore, iris:blocks, iris:stilt, iris:vacuum and iris:snow. Their stage constants and output types live in art.arcane.iris.builtin, which packs see, the stage bodies beside the placement settings they read. - The modes stay in ObjectPlaceMode, which now names how each mode samples its height and which stilt it grows; one graph serves them all. - The block stages share one pass: the object's blocks are written and the stilt layers found together. Snow and the vacuum bend read the written blocks from the write stage's output. - PlacementLifecycle, its builder, plans, stages and state, the PlacementModule classes, ObjectBlockPass, IrisObjectPlacementRunner and ObjectMarkerPlacement are deleted. - IrisObject caches its geometry as IrisApi blocks and forgets it with its other derived shapes whenever its blocks change. - IrisObjectPlacement carries the module settings decoded with it. - The vacuum radius is capped at the 128 blocks its settings allow, the reach the vacuum stage declares. --- source-patterns.txt | 1 + .../iris/builtin/anchor/AnchorHeight.java | 23 ++ .../iris/builtin/anchor/AnchorStages.java | 33 ++ .../iris/builtin/blocks/BlocksStages.java | 36 ++ .../iris/builtin/blocks/ObjectMarkers.java | 54 +++ .../iris/builtin/blocks/WrittenBlocks.java | 42 +++ .../arcane/iris/builtin/bore/BoreStages.java | 30 ++ .../art/arcane/iris/builtin/package-info.java | 34 ++ .../iris/builtin/prepare/PrepareStages.java | 35 ++ .../arcane/iris/builtin/snow/SnowStages.java | 30 ++ .../iris/builtin/stilt/StiltLayers.java | 74 ++++ .../iris/builtin/stilt/StiltStages.java | 34 ++ .../iris/builtin/vacuum/VacuumStages.java | 30 ++ .../iris/builtin/validate/ValidateStages.java | 37 ++ .../object/marker/ObjectMarkerPlacement.java | 108 ------ .../engine/object/placement/AnchorModule.java | 163 +++++++++ .../object/placement/AnchorSampling.java | 39 +++ .../engine/object/placement/BlocksModule.java | 247 ++++++++++++++ .../engine/object/placement/BoreModule.java | 63 ++++ .../object/placement/IrisObjectPlacement.java | 4 + .../placement/IrisObjectPlacementRunner.java | 43 --- .../object/placement/IrisObjectVacuum.java | 4 +- .../object/placement/ObjectBlockPass.java | 259 -------------- .../engine/object/placement/ObjectEdits.java | 73 ++++ .../placement/ObjectModuleCeilingHang.java | 11 - .../object/placement/ObjectPlaceMode.java | 89 ++--- .../object/placement/PlacementBlock.java | 9 - .../object/placement/PlacementBlockWrite.java | 6 - .../object/placement/PlacementContext.java | 45 --- .../object/placement/PlacementFunction.java | 6 - .../object/placement/PlacementLifecycle.java | 35 -- .../placement/PlacementLifecycleBuilder.java | 84 ----- .../PlacementLifecycleDependency.java | 13 - .../object/placement/PlacementLifecycles.java | 43 --- .../object/placement/PlacementModule.java | 9 - .../placement/PlacementModuleAnchor.java | 43 --- .../placement/PlacementModuleBlocks.java | 18 - .../object/placement/PlacementModuleBore.java | 25 -- .../placement/PlacementModuleBounds.java | 43 --- .../PlacementModuleCenterHeight.java | 18 - .../placement/PlacementModuleCollision.java | 41 --- .../placement/PlacementModuleFloating.java | 10 - .../placement/PlacementModuleHeight.java | 57 ---- .../placement/PlacementModuleLimits.java | 34 -- ...cementModuleNativeStructureProtection.java | 113 ------- .../placement/PlacementModulePaint.java | 18 - .../placement/PlacementModulePreparation.java | 98 ------ .../placement/PlacementModuleSlope.java | 72 ---- .../object/placement/PlacementModuleSnow.java | 45 --- .../placement/PlacementModuleStilt.java | 317 ------------------ .../PlacementModuleSurfaceSupport.java | 67 ---- .../placement/PlacementModuleVacuum.java | 90 ----- .../object/placement/PlacementModules.java | 36 ++ .../object/placement/PlacementStage.java | 38 --- .../object/placement/PlacementState.java | 67 ---- .../object/placement/PlacementWorld.java | 64 ++++ .../object/placement/PrepareModule.java | 176 ++++++++++ .../object/placement/PreparedPlacement.java | 146 ++++++++ .../engine/object/placement/SnowModule.java | 88 +++++ .../engine/object/placement/StiltModule.java | 269 +++++++++++++++ .../engine/object/placement/StiltShape.java | 32 ++ .../object/placement/TransformedBounds.java | 23 ++ .../engine/object/placement/VacuumModule.java | 173 ++++++++++ .../object/placement/ValidateModule.java | 254 ++++++++++++++ .../engine/object/placement/WorldVolume.java | 55 +++ .../iris/engine/object/prefab/IrisObject.java | 30 +- .../engine/object/prefab/IrisObjectIO.java | 6 +- .../object/prefab/IrisObjectShaping.java | 7 +- 68 files changed, 2464 insertions(+), 1955 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java create mode 100644 src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java create mode 100644 src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java create mode 100644 src/main/java/art/arcane/iris/builtin/bore/BoreStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/package-info.java create mode 100644 src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/snow/SnowStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java create mode 100644 src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java diff --git a/source-patterns.txt b/source-patterns.txt index 149aa02d1..6e0d633f7 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -16,3 +16,4 @@ art/arcane/iris/engine/framework/StructurePlacementMarker.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/** diff --git a/src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java b/src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java new file mode 100644 index 000000000..0b2806875 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/anchor/AnchorHeight.java @@ -0,0 +1,23 @@ +/* + * 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.builtin.anchor; + +/** The height an object's anchor is placed at. */ +public record AnchorHeight(int y) { +} diff --git a/src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java b/src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java new file mode 100644 index 000000000..06a08a51a --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java @@ -0,0 +1,33 @@ +/* + * 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.builtin.anchor; + +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:anchor}: the height an object is placed at. */ +public final class AnchorStages { + /** The requested or sampled height the checks judge. Rejects {@code carving-anchor}. */ + public static final PlacementStage HEIGHT = Stage.placement("iris:anchor/height", AnchorHeight.class); + /** The height the object's blocks are written at: the checked height plus the random offset. */ + public static final PlacementStage FINAL = Stage.placement("iris:anchor/final", AnchorHeight.class); + + private AnchorStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java b/src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java new file mode 100644 index 000000000..615043113 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java @@ -0,0 +1,36 @@ +/* + * 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.builtin.blocks; + +import com.volmit.stage.BlockStage; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:blocks}: writing the object's blocks. */ +public final class BlocksStages { + /** Writes each object block where the placement puts it. */ + public static final BlockStage WRITE = Stage.placementBlock("iris:blocks/write", WrittenBlocks.class); + /** Marks some written blocks with the placement's markers. */ + public static final PlacementStage MARKERS = Stage.placement("iris:blocks/markers"); + /** Milestone: stages requiring it run after the object and its markers are written. */ + public static final PlacementStage COMPLETE = Stage.placement("iris:blocks/complete"); + + private BlocksStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java new file mode 100644 index 000000000..624e1f3b8 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java @@ -0,0 +1,54 @@ +/* + * 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.builtin.blocks; + +import com.volmit.placement.PlacedMarker; +import com.volmit.resource.ResourceId; +import com.volmit.world.BlockPosition; + +import java.util.Map; + +/** + * Iris markers as IrisApi placement markers: type {@code iris:marker}, naming the pack's marker under the + * {@code marker} attribute. Iris stores markers of this type only. + */ +public final class ObjectMarkers { + public static final ResourceId TYPE = ResourceId.parse("iris:marker"); + public static final String MARKER_ATTRIBUTE = "marker"; + + private ObjectMarkers() { + } + + /** {@code markerKey} is the pack's marker, such as {@code spawn/zombie}. */ + public static PlacedMarker of(BlockPosition position, String markerKey) { + return new PlacedMarker(position, TYPE, Map.of(MARKER_ATTRIBUTE, markerKey)); + } + + public static String markerKey(PlacedMarker marker) { + requireIrisMarker(marker); + return marker.attributes().get(MARKER_ATTRIBUTE); + } + + public static void requireIrisMarker(PlacedMarker marker) { + if (!marker.type().equals(TYPE) || !marker.attributes().containsKey(MARKER_ATTRIBUTE)) { + throw new IllegalArgumentException("Iris stores markers of type " + TYPE + " with a \"" + MARKER_ATTRIBUTE + + "\" attribute only, not " + marker.type() + " " + marker.attributes()); + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java b/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java new file mode 100644 index 000000000..df0c6d515 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java @@ -0,0 +1,42 @@ +/* + * 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.builtin.blocks; + +import com.volmit.placement.PlacedBlock; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** The object's own blocks a placement wrote, in world positions, in the order they were written. */ +public final class WrittenBlocks { + private final List blocks = new ArrayList<>(); + + public void add(PlacedBlock block) { + blocks.add(block); + } + + public List blocks() { + return Collections.unmodifiableList(blocks); + } + + public boolean isEmpty() { + return blocks.isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/bore/BoreStages.java b/src/main/java/art/arcane/iris/builtin/bore/BoreStages.java new file mode 100644 index 000000000..3d7357387 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/bore/BoreStages.java @@ -0,0 +1,30 @@ +/* + * 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.builtin.bore; + +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:bore}: clearing the object's volume before its blocks are written. */ +public final class BoreStages { + public static final PlacementStage CLEAR = Stage.placement("iris:bore/clear"); + + private BoreStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java new file mode 100644 index 000000000..a21ac18f4 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -0,0 +1,34 @@ +/* + * 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 . + */ + +/** + * The public face of Iris's built-in modules: their stage constants and the settings and output types + * of those stages. {@link art.arcane.iris.core.modules.IrisModuleHost} exposes this package, with its + * subpackages, to pack modules, so a pack jar can {@code requires(...)} a built-in stage and read its + * output. Everything here is part of what packs compile against. + *

+ * Keep implementation out of it: stage bodies and anything that uses Iris internals live in the + * built-in module classes outside this package, which packs cannot see. One subpackage per built-in + * module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} for + * {@code iris:deposit}. + *

+ * Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A + * pack module can require such a stage to run after it, but cannot read its output: the pack load rejects + * a pack class that uses a type Iris hides. + */ +package art.arcane.iris.builtin; diff --git a/src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java b/src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java new file mode 100644 index 000000000..47a67271d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java @@ -0,0 +1,35 @@ +/* + * 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.builtin.prepare; + +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.PreparedPlacement; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ +public final class PrepareStages { + /** The settings the placement uses: the requested ones, turned downhill when they ask to face the slope. Rejects {@code slope}. */ + public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", IrisObjectPlacement.class); + /** The random rotation, translation and height offset, chosen once per placement. */ + public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); + + private PrepareStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/snow/SnowStages.java b/src/main/java/art/arcane/iris/builtin/snow/SnowStages.java new file mode 100644 index 000000000..2a51efd05 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/snow/SnowStages.java @@ -0,0 +1,30 @@ +/* + * 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.builtin.snow; + +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:snow}: snow on the object, after its stilt or terrain bend. */ +public final class SnowStages { + public static final PlacementStage COVER = Stage.placement("iris:snow/cover"); + + private SnowStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java b/src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java new file mode 100644 index 000000000..5ad22327e --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/stilt/StiltLayers.java @@ -0,0 +1,74 @@ +/* + * 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.builtin.stilt; + +import com.volmit.object.ObjectBlock; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The bottom and top layers of the blocks a stilt can repeat, with their positions already transformed + * around the anchor. Each layer keeps the blocks at its lowest or highest height seen so far. + */ +public final class StiltLayers { + private final List bottom = new ArrayList<>(); + private final List top = new ArrayList<>(); + private int bottomY = Integer.MAX_VALUE; + private int topY = Integer.MIN_VALUE; + + public void include(ObjectBlock transformed) { + int y = transformed.position().y(); + if (y < bottomY) { + bottomY = y; + bottom.clear(); + } + if (y == bottomY) { + bottom.add(transformed); + } + if (y > topY) { + topY = y; + top.clear(); + } + if (y == topY) { + top.add(transformed); + } + } + + public boolean isEmpty() { + return bottom.isEmpty(); + } + + public List bottom() { + return Collections.unmodifiableList(bottom); + } + + public List top() { + return Collections.unmodifiableList(top); + } + + public int bottomY() { + return bottomY; + } + + public int topY() { + return topY; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java b/src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java new file mode 100644 index 000000000..a3f9a78f8 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java @@ -0,0 +1,34 @@ +/* + * 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.builtin.stilt; + +import com.volmit.stage.BlockStage; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:stilt}: the stilts of the stilt and ceiling placement modes. */ +public final class StiltStages { + /** Finds the layers to repeat. */ + public static final BlockStage LAYERS = Stage.placementBlock("iris:stilt/layers", StiltLayers.class); + /** Grows the stilt once the object is written. */ + public static final PlacementStage FILL = Stage.placement("iris:stilt/fill"); + + private StiltStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java new file mode 100644 index 000000000..2c23b4b73 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java @@ -0,0 +1,30 @@ +/* + * 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.builtin.vacuum; + +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:vacuum}: bending the terrain to meet objects of the vacuum placement modes. */ +public final class VacuumStages { + public static final PlacementStage TERRAIN = Stage.placement("iris:vacuum/terrain"); + + private VacuumStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java b/src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java new file mode 100644 index 000000000..3446c39bc --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java @@ -0,0 +1,37 @@ +/* + * 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.builtin.validate; + +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:validate}: the checks that reject a placement before anything is written, in this order. */ +public final class ValidateStages { + /** Rejects {@code bedrock-anchor} and {@code surface-support}. */ + public static final PlacementStage SURFACE = Stage.placement("iris:validate/surface"); + /** Rejects {@code underwater-anchor}, {@code cave-clearance}, {@code fluid-height} and {@code height-clamp}. */ + public static final PlacementStage LIMITS = Stage.placement("iris:validate/limits"); + /** Rejects {@code native-structure}, even for placements that force their way past the other checks. */ + public static final PlacementStage STRUCTURES = Stage.placement("iris:validate/structures"); + /** Rejects {@code object-collision}. */ + public static final PlacementStage COLLISIONS = Stage.placement("iris:validate/collisions"); + + private ValidateStages() { + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java b/src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java deleted file mode 100644 index 44f27a422..000000000 --- a/src/main/java/art/arcane/iris/engine/object/marker/ObjectMarkerPlacement.java +++ /dev/null @@ -1,108 +0,0 @@ -package art.arcane.iris.engine.object.marker; - -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.PlacementContext; -import art.arcane.iris.engine.object.placement.PlacementState; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterMarker; - -import java.util.ArrayList; -import java.util.List; - -public class ObjectMarkerPlacement { - - private IrisObjectPlacement config; - private PlacementContext context; - private final IObjectPlacer placer; - private RNG markerRng; - List placements; - - public ObjectMarkerPlacement(PlacementContext context, PlacementState state) { - this.config = state.getConfig(); - this.placer = state.getPlacer(); - this.context = context; - this.markerRng = context.getRng().nextParallelRNG(((((long) context.getX()) << 32) | (context.getZ() & 0xFFFFFFFFL)) * 31L + context.getYv()); - this.placements = new ArrayList<>(); - } - - public void loadPossibleMarkers() { - // Marker selection persists into the mantle, so it must be seed-deterministic. - // Derive a side stream keyed on the placement position instead of consuming the - // caller's rng: consuming draws there would shift every later placement in the - // chunk and invalidate existing worlds/goldenhashes. - int index = 0; - for (IrisObjectMarker markerConfig : config.getMarkers()) { - IrisMarker marker = context.getSelf().getLoader().getMarkerLoader().load(markerConfig.getMarker()); - int markerSalt = index++; - if (marker != null) { - placements.add(new ObjectMarkerPlacement.MarkerPlacement(markerConfig, marker, - markerConfig.getMark(context.getRdata()), markerSalt)); - } - } - } - - public List matchMarkers(PlatformBlockState state) { - List matching = new ArrayList<>(); - for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : placements) { - if (markerPlacement.matches(state)) { - matching.add(markerPlacement); - } - } - return matching; - } - - public void placeMarkers() { - for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : placements) { - int max = markerPlacement.config.getMaximumMarkers(); - for (BlockPosition position : markerPlacement.candidates - .shuffleCopy(markerRng.nextParallelRNG(markerPlacement.salt))) { - if (max <= 0) { - break; - } - - boolean firstAboveAir = B.isAir(placer.get(position.getX(), position.getY() + 1, position.getZ())); - boolean secondAboveAir = B.isAir(placer.get(position.getX(), position.getY() + 2, position.getZ())); - if (!markerPlacement.marker.isEmptyAbove() || (firstAboveAir && secondAboveAir)) { - placer.setData(position.getX(), position.getY(), position.getZ(), - new MatterMarker(markerPlacement.config.getMarker())); - max--; - } - } - } - - } - - public static final class MarkerPlacement { - public final IrisObjectMarker config; - public final IrisMarker marker; - public final Iterable targets; - public final int salt; - public final KList candidates = new KList<>(); - - public MarkerPlacement(IrisObjectMarker config, IrisMarker marker, - Iterable targets, int salt) { - this.config = config; - this.marker = marker; - this.targets = targets; - this.salt = salt; - } - - public boolean matches(PlatformBlockState state) { - for (PlatformBlockState target : targets) { - if (config.isExact() - ? target.matches(state) - : IrisObjectShaping.materialKey(target).equals(IrisObjectShaping.materialKey(state))) { - return true; - } - } - return false; - } - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java new file mode 100644 index 000000000..4f48b0b8d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -0,0 +1,163 @@ +/* + * 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.anchor.AnchorHeight; +import art.arcane.iris.builtin.anchor.AnchorStages; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.validate.ValidateStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:anchor}: the height an object is placed at, requested by the caller, counted from the + * bottom of the world, or sampled from the terrain the way the placement mode says. A surface-anchored + * placement rejects a height its carving support forbids. + */ +public final class AnchorModule implements IrisModule { + private static final String CARVING_ANCHOR = "carving-anchor"; + private static final int CARVING_CLEARANCE_BLOCKS = 4; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:anchor", "Placement anchor", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(AnchorStages.HEIGHT) + .requires(PrepareStages.TRANSFORMS) + .produce(AnchorModule::height); + graph.define(AnchorStages.FINAL) + .requires(AnchorStages.HEIGHT, ValidateStages.COLLISIONS) + .produce(AnchorModule::finalHeight); + } + + private static AnchorHeight height(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + boolean structurePiece = prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE; + if (!config.isFromBottom() && placement.requestedY() < 0) { + return new AnchorHeight(sampled(context, placement, prepared)); + } + IrisObject object = placement.object(); + int y = config.isFromBottom() ? object.getH() + 1 + prepared.rotatedCenterY() : placement.requestedY(); + if (!config.isForcePlace() && !structurePiece && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { + context.reject(CARVING_ANCHOR); + return new AnchorHeight(y); + } + if (placement.requestedY() < 0 || !config.isBottom() || structurePiece) { + return new AnchorHeight(y); + } + y += Math.floorDiv(object.h, 2); + if (!config.isForcePlace() && config.getCarvingSupport() != CarvingMode.CARVING_ONLY + && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { + context.reject(CARVING_ANCHOR); + } + return new AnchorHeight(y); + } + + private static AnchorHeight finalHeight(PlacementStageContext context) { + int y = context.output(AnchorStages.HEIGHT).y() + context.output(PrepareStages.TRANSFORMS).randomY(); + IrisPlacement.current().anchoredAt(y); + return new AnchorHeight(y); + } + + private static int sampled(PlacementStageContext context, IrisPlacement placement, PreparedPlacement prepared) { + return switch (prepared.mode().anchor()) { + case CENTER -> checked(context, prepared, placement.x(), centerSurface(placement, prepared), placement.z()); + case SURFACE -> checked(context, prepared, placement.x(), surface(placement, prepared, placement.x(), placement.z()), placement.z()); + case HIGHEST -> extremeSurface(context, placement, prepared, true, false); + case HIGHEST_CORNER -> extremeSurface(context, placement, prepared, true, true); + case LOWEST -> extremeSurface(context, placement, prepared, false, false); + case LOWEST_CORNER -> extremeSurface(context, placement, prepared, false, true); + case TRANSLATION -> prepared.rotatedCenterY(); + case REQUESTED -> placement.requestedY(); + }; + } + + /** The floor of the cave the object is placed in, otherwise the surface at its center. */ + private static int centerSurface(IrisPlacement placement, PreparedPlacement prepared) { + if (placement.cave() != null) { + return placement.cave().getSurface() + prepared.rotatedCenterY(); + } + return surface(placement, prepared, placement.x(), placement.z()); + } + + private static int surface(IrisPlacement placement, PreparedPlacement prepared, int x, int z) { + return prepared.terrain().getHighest(x, z, placement.object().getLoader(), prepared.config().isUnderwater()) + + prepared.rotatedCenterY(); + } + + private static int checked(PlacementStageContext context, PreparedPlacement prepared, int x, int y, int z) { + if (!prepared.config().isForcePlace() && rejectsCarvingAnchor(prepared, x, y, z)) { + context.reject(CARVING_ANCHOR); + } + return y; + } + + /** The highest or lowest surface under the object's columns, or under its four corners only. */ + private static int extremeSurface(PlacementStageContext context, IrisPlacement placement, PreparedPlacement prepared, + boolean highest, boolean cornersOnly) { + TransformedBounds bounds = prepared.bounds(); + int minX = placement.x() + bounds.minX(); + int maxX = placement.x() + bounds.maxX(); + int minZ = placement.z() + bounds.minZ(); + int maxZ = placement.z() + bounds.maxZ(); + int xStep = cornersOnly ? Math.max(0, (maxX - minX) / 2) + 1 : 1; + int zStep = cornersOnly ? Math.max(0, (maxZ - minZ) / 2) + 1 : 1; + int y = highest ? -1 : Integer.MAX_VALUE; + for (int x = minX; x <= maxX; x += xStep) { + for (int z = minZ; z <= maxZ; z += zStep) { + int column = surface(placement, prepared, x, z); + if (!prepared.config().isForcePlace() && rejectsCarvingAnchor(prepared, x, column, z)) { + context.reject(CARVING_ANCHOR); + return y; + } + y = highest ? Math.max(y, column) : Math.min(y, column); + } + } + return y; + } + + /** Whether the placement's carving support forbids anchoring at this block. */ + private static boolean rejectsCarvingAnchor(PreparedPlacement prepared, int x, int y, int z) { + IObjectPlacer terrain = prepared.terrain(); + return switch (prepared.config().getCarvingSupport()) { + case SURFACE_ONLY -> terrain.isCarved(x, y, z); + case CARVING_ONLY -> !carvedWithin(terrain, x, y, z); + case ANYWHERE -> false; + }; + } + + private static boolean carvedWithin(IObjectPlacer terrain, int x, int y, int z) { + for (int depth = 0; depth < CARVING_CLEARANCE_BLOCKS; depth++) { + if (terrain.isCarved(x, y - depth, z)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java new file mode 100644 index 000000000..5f7b7d572 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java @@ -0,0 +1,39 @@ +/* + * 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; + +/** How a placement mode finds the height of an object placed without a requested height. */ +enum AnchorSampling { + /** The surface at the object's center, or the floor of the cave it is placed in. */ + CENTER, + /** The highest surface under any column of the object. */ + HIGHEST, + /** The highest surface under the object's four corners. */ + HIGHEST_CORNER, + /** The lowest surface under any column of the object. */ + LOWEST, + /** The lowest surface under the object's four corners. */ + LOWEST_CORNER, + /** The surface at the object's center, ignoring caves; each block then follows its own column. */ + SURFACE, + /** The translation alone, in open air. */ + TRANSLATION, + /** The requested height, even when negative. */ + REQUESTED +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java new file mode 100644 index 000000000..2a87834b2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -0,0 +1,247 @@ +/* + * 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.anchor.AnchorStages; +import art.arcane.iris.builtin.blocks.BlocksStages; +import art.arcane.iris.builtin.blocks.ObjectMarkers; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.bore.BoreStages; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.engine.object.marker.IrisObjectMarker; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.object.ObjectBlock; +import com.volmit.placement.PlacedBlock; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; +import com.volmit.world.BlockPosition; + +import java.util.Set; + +/** + * Module {@code iris:blocks}: writes the object's blocks where the placement puts them, then its markers. + * Each block is turned with the object, edited, warped, painted onto its column when the mode paints, + * waterlogged in water and attached to the faces vines can hang from. Air is not written, except by + * structure pieces, and neither is a vine into a solid block or a melded block into open space. + */ +public final class BlocksModule implements IrisModule { + private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + private static final String DISTANCE = "distance"; + private static final String PERSISTENT = "persistent"; + private static final String WATERLOGGED = "waterlogged"; + private static final String TRUE = "true"; + private static final String FALSE = "false"; + private static final int MARKER_HEADROOM_BLOCKS = 2; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:blocks", "Object blocks", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(BlocksStages.WRITE) + .requires(PrepareStages.TRANSFORMS, AnchorStages.FINAL, BoreStages.CLEAR) + .accumulate(WrittenBlocks::new, BlocksModule::write); + graph.define(BlocksStages.MARKERS) + .requires(BlocksStages.WRITE, PrepareStages.TRANSFORMS) + .run(BlocksModule::placeMarkers); + graph.define(BlocksStages.COMPLETE) + .requires(BlocksStages.WRITE, BlocksStages.MARKERS) + .run(context -> { + }); + } + + private static void write(BlockStageContext context, WrittenBlocks written) { + IrisPlacement placement = IrisPlacement.current(); + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + PlacementWorld world = new PlacementWorld(context.access(), placement.states()); + ObjectBlock block = context.block(); + BlockPosition offset = prepared.transform(block.position()); + int anchorY = context.output(AnchorStages.FINAL).y(); + PlatformBlockState data = sourceState(block, placement, prepared); + TileData tile = block.blockEntity().map(BlockEntities::tileOf).orElse(null); + if (!config.getEdit().isEmpty()) { + ObjectEdits.Edited edited = ObjectEdits.apply(config, data, tile, new RNG(context.random().nextLong()), + offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z(), placement.data()); + data = edited.data(); + tile = edited.tile(); + } + data = prepared.rotate(data); + int x = placement.x() + offset.x(); + int y = anchorY + offset.y(); + int z = placement.z() + offset.z(); + if (prepared.isWarped()) { + x += prepared.warpOffset(offset.x() + placement.x(), y, offset.z() + placement.z()); + z += prepared.warpOffset(offset.z() + placement.z(), y, offset.x() + placement.x()); + } + if (WorldVolume.isPainted(placement, prepared) && !B.isVineBlock(data)) { + y = offset.y() + Math.floorDiv(placement.object().h, 2) + + prepared.terrain().getHighest(x, z, placement.object().getLoader(), config.isUnderwater()); + } + boolean structurePiece = prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE; + if (config.isMeld() && !structurePiece && !world.isSolid(x, y, z)) { + return; + } + if (IrisProceduralBlocks.hasProperty(data, WATERLOGGED) && shouldWaterlog(world, config, placement.requestedY(), x, y, z)) { + data = data.withProperty(WATERLOGGED, TRUE); + } + if (B.isVineBlock(data)) { + data = attachVineFaces(world, data, x, y, z); + } + if (!shouldWrite(world, data, x, y, z, structurePiece)) { + return; + } + PlacedBlock placed = world.set(x, y, z, data, tile); + placement.objectBlockWritten(placed.position()); + written.add(placed); + } + + /** The object block as Iris places it: debug air shows where smart boring bored, and leaves never decay where the placer prevents it. */ + private static PlatformBlockState sourceState(ObjectBlock block, IrisPlacement placement, PreparedPlacement prepared) { + PlatformBlockState data = placement.states().toPlatform(block.state()); + IObjectPlacer terrain = prepared.terrain(); + if (terrain.isDebugSmartBore() && data.matches(IrisObject.States.VAIR)) { + data = IrisObject.States.VAIR_DEBUG; + } + if (terrain.isPreventingDecay() && IrisProceduralBlocks.hasProperty(data, DISTANCE) + && FALSE.equals(IrisProceduralBlocks.propertyValue(data, PERSISTENT))) { + data = data.withProperty(PERSISTENT, TRUE); + } + return data; + } + + private static boolean shouldWrite(PlacementWorld world, PlatformBlockState data, int x, int y, int z, boolean structurePiece) { + if (data.isCustom()) { + return true; + } + boolean vineIntoSolid = B.isVineBlock(data) && world.isSolid(x, y, z); + return shouldPlaceObjectBlock(structurePiece, AIR_MATERIALS.contains(IrisObjectShaping.materialKey(data)), vineIntoSolid); + } + + /** Air is written only by structure pieces, and a vine never replaces a solid block. */ + static boolean shouldPlaceObjectBlock(boolean structurePiece, boolean air, boolean vineIntoSolid) { + return !vineIntoSolid && (structurePiece || !air); + } + + /** Whether a waterloggable block lands in water a waterloggable or underwater placement keeps. */ + static boolean shouldWaterlog(PlacementWorld world, IrisObjectPlacement config, int requestedY, int x, int y, int z) { + if (!(config.isWaterloggable() || config.isUnderwater())) { + return false; + } + if (requestedY >= 0 && config.getCarvingSupport() == CarvingMode.CARVING_ONLY) { + return false; + } + PlatformBlockState existing = world.get(x, y, z); + return B.isWater(existing) || B.isWaterLogged(existing); + } + + /** {@code vine} hanging from each neighboring solid block it has a face property for. */ + static PlatformBlockState attachVineFaces(PlacementWorld world, PlatformBlockState vine, int x, int y, int z) { + PlatformBlockState attached = vine; + for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { + if (!IrisProceduralBlocks.hasProperty(vine, face)) { + continue; + } + int[] offset = IrisProceduralBlocks.faceOffset(face); + PlatformBlockState facing = world.get(x + offset[0], y + offset[1], z + offset[2]); + if (B.isSolid(facing) && !B.isVineBlock(facing)) { + attached = attached.withProperty(face, TRUE); + } + } + return attached; + } + + /** + * Each marker of the placement marks up to its maximum of the written blocks it targets, picked at random, + * where the marker either allows anything above or finds two blocks of air. + */ + private static void placeMarkers(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + if (config.getMarkers().isEmpty() || prepared.terrain().getEngine() == null) { + return; + } + WrittenBlocks written = context.output(BlocksStages.WRITE); + PlacementWorld world = new PlacementWorld(context.access(), placement.states()); + RNG markerRandom = new RNG(context.random().nextLong()); + int salt = 0; + for (IrisObjectMarker markerConfig : config.getMarkers()) { + IrisMarker marker = placement.object().getLoader().getMarkerLoader().load(markerConfig.getMarker()); + int markerSalt = salt++; + if (marker == null) { + continue; + } + KList candidates = candidates(written, markerConfig, markerConfig.getMark(placement.data()), placement); + int remaining = markerConfig.getMaximumMarkers(); + for (BlockPosition position : candidates.shuffleCopy(markerRandom.nextParallelRNG(markerSalt))) { + if (remaining <= 0) { + break; + } + if (!marker.isEmptyAbove() || hasAirAbove(world, position)) { + context.access().marker(ObjectMarkers.of(position, markerConfig.getMarker())); + remaining--; + } + } + } + } + + private static KList candidates(WrittenBlocks written, IrisObjectMarker markerConfig, + KList targets, IrisPlacement placement) { + KList candidates = new KList<>(); + for (PlacedBlock block : written.blocks()) { + PlatformBlockState state = placement.states().toPlatform(block.state()); + if (targets.stream().anyMatch(target -> marks(markerConfig, target, state))) { + candidates.add(block.position()); + } + } + return candidates; + } + + private static boolean marks(IrisObjectMarker markerConfig, PlatformBlockState target, PlatformBlockState state) { + return markerConfig.isExact() + ? target.matches(state) + : IrisObjectShaping.materialKey(target).equals(IrisObjectShaping.materialKey(state)); + } + + private static boolean hasAirAbove(PlacementWorld world, BlockPosition position) { + for (int above = 1; above <= MARKER_HEADROOM_BLOCKS; above++) { + if (!B.isAir(world.get(position.x(), position.y() + above, position.z()))) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java new file mode 100644 index 000000000..cb8d8dbab --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -0,0 +1,63 @@ +/* + * 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.anchor.AnchorStages; +import art.arcane.iris.builtin.bore.BoreStages; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.validate.ValidateStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; + +/** Module {@code iris:bore}: fills the object's volume with air, extended up and down as configured. */ +public final class BoreModule implements IrisModule { + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:bore", "Bore", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(BoreStages.CLEAR) + .requires(AnchorStages.FINAL, ValidateStages.COLLISIONS) + .run(BoreModule::clear); + } + + private static void clear(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + if (!config.isBore()) { + return; + } + IrisPlacement placement = IrisPlacement.current(); + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(AnchorStages.FINAL).y()); + PlacementWorld world = new PlacementWorld(context.access(), placement.states()); + for (int x = volume.minX(); x <= volume.maxX(); x++) { + for (int y = volume.minY() - config.getBoreExtendMinY(); y <= volume.maxY() + config.getBoreExtendMaxY(); y++) { + for (int z = volume.minZ(); z <= volume.maxZ(); z++) { + world.set(x, y, z, IrisObject.States.AIR); + } + } + } + } +} 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 index 3845ec97b..23b508538 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisObjectLoot; @@ -197,6 +198,8 @@ public class IrisObjectPlacement { @SerializedName(value = "forcePlace", alternate = {"force"}) private boolean forcePlace = false; private transient AtomicCache cache = new AtomicCache<>(); + /** The pack modules' settings this placement declares, decoded with it. */ + private transient ModuleSettings moduleSettings = ModuleSettings.NONE; public IrisObjectPlacement toPlacement(String... place) { IrisObjectPlacement p = new IrisObjectPlacement(); @@ -241,6 +244,7 @@ public class IrisObjectPlacement { p.setAllowedCollisions(allowedCollisions); p.setForbiddenCollisions(forbiddenCollisions); p.setForcePlace(forcePlace); + p.setModuleSettings(moduleSettings); return p; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java deleted file mode 100644 index c9dae93a5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacementRunner.java +++ /dev/null @@ -1,43 +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 art.arcane.iris.engine.object.terrain.carving.CarveResult; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.RNG; - -import java.util.function.BiConsumer; - -/** Entry point for executing an engine's resolved placement plan. */ -public final class IrisObjectPlacementRunner { - private final IrisObject self; - - public IrisObjectPlacementRunner(IrisObject self) { - this.self = self; - } - - public int place(int x, int yv, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, - BiConsumer listener, CarveResult cave, IrisData data) { - PlacementContext context = new PlacementContext(config, data, placer, cave, rng, self, x, z, yv, listener); - return PlacementLifecycles.forPlacer(placer).get(config.getMode()).execute(context).heightOrRejected(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java index 57a0fb223..82d5cc89d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -21,6 +21,8 @@ package art.arcane.iris.engine.object.placement; public final class IrisObjectVacuum { private static final double DEFAULT_WAVE_AMPLITUDE = 3.0; private static final double DEFAULT_WAVE_SCALE = 5.0; + /** The widest bend, as the settings allow it; placements prepare this much around every object. */ + public static final int MAX_RADIUS_BLOCKS = 128; private IrisObjectVacuum() { } @@ -42,7 +44,7 @@ public final class IrisObjectVacuum { if (settings != null && settings.getRadius() > 0) { radius = settings.getRadius(); } - return Math.max(0, radius); + return Math.max(0, Math.min(MAX_RADIUS_BLOCKS, radius)); } public static int resolveStep(ObjectPlaceMode mode) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java deleted file mode 100644 index 0bca2e368..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectBlockPass.java +++ /dev/null @@ -1,259 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.marker.ObjectMarkerPlacement; -import art.arcane.iris.engine.object.material.BlockDataMergeSupport; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; -import art.arcane.iris.core.nms.container.Pair; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.BlockPosition; - -import java.util.List; -import java.util.Optional; -import java.util.function.BiConsumer; - -final class ObjectBlockPass { - - private List matchingMarkers; - private final BiConsumer listener; - - private final PlacementContext context; - private final PlacementState state; - private final VectorMap blocks; - private final VectorMap states; - private final ObjectMarkerPlacement markerPlacer; - private final PlacementLifecycle lifecycle; - - ObjectBlockPass( - PlacementContext context, - PlacementState state, - PlacementLifecycle lifecycle, - BiConsumer listener - ) { - this.context = context; - this.state = state; - this.lifecycle = lifecycle; - this.listener = listener; - this.blocks = context.self.blocks; - this.states = context.self.states; - - if (state.config.getMarkers().isNotEmpty() && state.placer.getEngine() != null) { - markerPlacer = new ObjectMarkerPlacement(context, state); - markerPlacer.loadPossibleMarkers(); - } else { - markerPlacer = null; - } - } - - void process() { - VectorMap.Cursor cursor = blocks.cursor(); - IrisObjectTranslate translate = state.config.getTranslate(); - CNG surfaceWarp = !state.config.getWarp().isFlat() ? state.config.getSurfaceWarp(context.rng, context.self.getLoader()) : null; - boolean preventingDecay = state.placer.isPreventingDecay(); - boolean waterlogCandidate = state.config.isWaterloggable() || state.config.isUnderwater(); - boolean hasStates = !states.isEmpty(); - int xx, zz; - - double warpHalf = !state.config.getWarp().isFlat() ? state.config.getWarp().getMultiplier() / 2D : 0D; - - while (cursor.next()) { - var read = readStateFrom(cursor, hasStates); - - PlatformBlockState data = read.getA(); - TileData tile = read.getB(); - IrisBlockVector vector = cursor.key().clone(); - - state.spin.rotate(vector); - PlacementBlock block = new PlacementBlock(data, tile, vector); - lifecycle.run(PlacementStage.TRANSFORM_BLOCK, context, state, block); - if (state.isRejected()) { - return; - } - - if (translate.canTranslate()) { - vector.add(state.translateOffset); - } - - lifecycle.run(PlacementStage.COLLECT_BLOCK, context, state, block); - if (state.isRejected()) { - return; - } - if (preventingDecay && IrisProceduralBlocks.hasProperty(data, "distance") && "false".equals(IrisProceduralBlocks.propertyValue(data, "persistent"))) { - data = data.withProperty("persistent", "true"); - } - - if (!state.config.getEdit().isEmpty()) { - var result = applyEdits(vector, data, tile); - data = result.data(); - tile = result.tile(); - } - - matchingMarkers = markerPlacer != null ? markerPlacer.matchMarkers(data) : null; - - data = state.spin.rotate(data); - xx = context.x + (int) Math.round(vector.getX()); - int yy = state.y + (int) Math.round(vector.getY()); - zz = context.z + (int) Math.round(vector.getZ()); - - if (!state.config.getWarp().isFlat()) { - xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, vector.getX() + context.x, vector.getY() + state.y, vector.getZ() + context.z); - zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, vector.getZ() + context.z, vector.getY() + state.y, vector.getX() + context.x); - } - - if (context.yv < 0 && (is(ObjectPlaceMode.PAINT)) && !B.isVineBlock(data)) { - yy = (int) Math.round(vector.getY()) + Math.floorDiv(context.self.h, 2) + state.placer.getHighest(xx, zz, context.self.getLoader(), state.config.isUnderwater()); - } - - if (state.config.isMeld() && !is(ObjectPlaceMode.STRUCTURE_PIECE) && !state.placer.isSolid(xx, yy, zz)) { - continue; - } - - if (waterlogCandidate && IrisProceduralBlocks.hasProperty(data, "waterlogged") && shouldAutoWaterlogBlock(context, state, xx, yy, zz)) { - data = data.withProperty("waterlogged", "true"); - } - - if (B.isVineBlock(data)) { - data = attachVineFaces(state.placer, data, xx, yy, zz); - } - - if (handleCustomData(data, tile, xx, yy, zz)) { - lifecycle.run(PlacementStage.BLOCK_WRITTEN, context, state, new PlacementBlockWrite(xx, yy, zz, data)); - if (state.isRejected()) { - return; - } - } - } - - if (markerPlacer != null) { - markerPlacer.placeMarkers(); - } - - - } - - private boolean is(ObjectPlaceMode mode) { - return state.config.getMode() == mode; - } - - static boolean shouldPlaceObjectBlock(boolean rawStructurePiece, boolean air, boolean wouldReplace) { - return !wouldReplace && (rawStructurePiece || !air); - } - - private boolean handleCustomData(PlatformBlockState data, TileData tile, int xx, int yy, int zz) { - // Short-circuit order matters for cost only: the mantle read is paid solely - // for vine blocks. Both operands are pure, so the value is unchanged. - boolean wouldReplace = B.isVineBlock(data) && B.isSolid(state.placer.get(xx, yy, zz)); - String material = IrisObjectShaping.materialKey(data); - boolean air = material.equals("minecraft:air") || material.equals("minecraft:cave_air"); - boolean place = shouldPlaceObjectBlock(is(ObjectPlaceMode.STRUCTURE_PIECE), air, wouldReplace); - if (data.isCustom() || place) { - state.placer.set(xx, yy, zz, data); - if (tile != null) { - state.placer.setTile(xx, yy, zz, tile); - } - if (matchingMarkers != null) { - BlockPosition markerPosition = new BlockPosition(xx, yy, zz); - for (ObjectMarkerPlacement.MarkerPlacement markerPlacement : matchingMarkers) { - markerPlacement.candidates.add(markerPosition); - } - } - if (listener != null) { - listener.accept(new BlockPosition(xx, yy, zz), data); - } - return true; - } - return false; - } - - private EditResult applyEdits(IrisBlockVector vector, PlatformBlockState data, TileData tile) { - for (IrisObjectReplace j : state.config.getEdit()) { - if (context.rng.chance(j.getChance())) { - for (PlatformBlockState k : j.getFind(context.rdata)) { - if (j.isExact() ? k.matches(data) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(data))) { - PlatformBlockState newData = j.getReplace(context.rng, vector.getX() + context.x, vector.getY() + state.y, vector.getZ() + context.z, context.rdata); - - if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(data)) && !(newData.isCustom() || data.isCustom())) - data = BlockDataMergeSupport.merge(data, newData); - else - data = newData; - - Optional t = j.getReplace().getTile(context.rng, context.x, state.y, context.z, context.rdata); - if (t.isPresent()) { - tile = t.get(); - } - } - } - } - } - return new EditResult(data, tile); - } - - static boolean shouldAutoWaterlogBlock(PlacementContext context, PlacementState state, int x, int y, int z) { - if (!(state.config.isWaterloggable() || state.config.isUnderwater())) { - return false; - } - - if (context.yv >= 0 && state.config.getCarvingSupport().equals(CarvingMode.CARVING_ONLY)) { - return false; - } - - PlatformBlockState existing = state.placer.get(x, y, z); - if (existing == null) { - return false; - } - - return B.isWater(existing) || B.isWaterLogged(existing); - } - - static PlatformBlockState attachVineFaces(IObjectPlacer placer, PlatformBlockState data, int x, int y, int z) { - PlatformBlockState result = data; - for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { - if (!IrisProceduralBlocks.hasProperty(data, face)) { - continue; - } - int[] mod = IrisProceduralBlocks.faceOffset(face); - PlatformBlockState facing = placer.get(x + mod[0], y + mod[1], z + mod[2]); - if (B.isSolid(facing) && !B.isVineBlock(facing)) { - result = result.withProperty(face, "true"); - } - } - return result; - } - - - private Pair readStateFrom(VectorMap.Cursor cursor, boolean hasStates) { - PlatformBlockState block; - TileData tile = null; - IrisBlockVector vector = cursor.key(); - try { - block = cursor.value(); - if (hasStates) { - tile = states.get(vector); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.warn("Failed to read block node " + vector.getBlockX() + "," + vector.getBlockY() + "," + vector.getBlockZ() + " in object " + context.self.getLoadKey() + " (cme)"); - block = IrisObject.States.AIR; - } - - if (block == null) { - IrisLogging.warn("Failed to read block node " + vector.getBlockX() + "," + vector.getBlockY() + "," + vector.getBlockZ() + " in object " + context.self.getLoadKey() + " (null)"); - block = IrisObject.States.AIR; - } - if (state.placer.isDebugSmartBore() && IrisObject.States.VAIR.equals(block)) { - block = IrisObject.States.VAIR_DEBUG; - } - return new Pair<>(block, tile); - } - - private record EditResult(PlatformBlockState data, TileData tile) {} -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java new file mode 100644 index 000000000..122ef4e7f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java @@ -0,0 +1,73 @@ +/* + * 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.core.loader.IrisData; +import art.arcane.iris.engine.object.material.BlockDataMergeSupport; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.math.RNG; + +/** + * A placement's block replacements ({@code edit}): each replacement, by its chance, swaps the blocks it + * finds for its palette's block at the block's position, keeping the old block's properties when the + * material stays the same. + */ +final class ObjectEdits { + private ObjectEdits() { + } + + /** {@code tile} may be null; the result's tile is the last replacement's tile, if it has one. */ + static Edited apply(IrisObjectPlacement config, PlatformBlockState data, TileData tile, RNG rng, + double x, double y, double z, IrisData rdata) { + PlatformBlockState edited = data; + TileData editedTile = tile; + for (IrisObjectReplace replace : config.getEdit()) { + if (!rng.chance(replace.getChance())) { + continue; + } + for (PlatformBlockState find : replace.getFind(rdata)) { + if (!finds(replace, find, edited)) { + continue; + } + edited = replaced(edited, replace.getReplace(rng, x, y, z, rdata)); + editedTile = replace.getReplace().getTile(rng, x, y, z, rdata).orElse(editedTile); + } + } + return new Edited(edited, editedTile); + } + + private static boolean finds(IrisObjectReplace replace, PlatformBlockState find, PlatformBlockState data) { + return replace.isExact() + ? find.matches(data) + : IrisObjectShaping.materialKey(find).equals(IrisObjectShaping.materialKey(data)); + } + + private static PlatformBlockState replaced(PlatformBlockState data, PlatformBlockState replacement) { + boolean sameMaterial = IrisObjectShaping.materialKey(replacement).equals(IrisObjectShaping.materialKey(data)); + if (sameMaterial && !replacement.isCustom() && !data.isCustom()) { + return BlockDataMergeSupport.merge(data, replacement); + } + return replacement; + } + + record Edited(PlatformBlockState data, TileData tile) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java deleted file mode 100644 index 4260e704c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectModuleCeilingHang.java +++ /dev/null @@ -1,11 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -public final class ObjectModuleCeilingHang implements PlacementModule { - static final PlacementLifecycleDependency FLIP = new PlacementLifecycleDependency("ceiling.flip"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(FLIP, PlacementStage.TRANSFORM_BLOCK, - (context, state, block) -> block.vector().setY(-block.vector().getBlockY())); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java index 7e7392c70..af6f6a335 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java @@ -20,130 +20,111 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.engine.object.annotations.Desc; -import java.util.function.Supplier; @Desc("Object Place modes are useful for positioning objects just right. The default value is CENTER_HEIGHT.") public enum ObjectPlaceMode { @Desc("The default place mode. This mode picks a center point (where the center of the object will be) and takes the height. That height is used for the whole object.") - CENTER_HEIGHT(PlacementModuleCenterHeight::new), + CENTER_HEIGHT(AnchorSampling.CENTER, StiltShape.NONE), @Desc("Samples a lot of points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.") - MAX_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, false)), + MAX_HEIGHT(AnchorSampling.HIGHEST, StiltShape.NONE), @Desc("Samples only 4 points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.\"") - FAST_MAX_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, true)), + FAST_MAX_HEIGHT(AnchorSampling.HIGHEST_CORNER, StiltShape.NONE), @Desc("Samples a lot of points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") - MIN_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, false)), + MIN_HEIGHT(AnchorSampling.LOWEST, StiltShape.NONE), @Desc("Samples only 4 points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") - FAST_MIN_HEIGHT(() -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, true)), + FAST_MIN_HEIGHT(AnchorSampling.LOWEST_CORNER, StiltShape.NONE), @Desc("Stilting is MAX_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.DEFAULT, false)), + STILT(AnchorSampling.HIGHEST, StiltShape.STRAIGHT), @Desc("Just like stilting but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") - FAST_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.DEFAULT, true)), + FAST_STILT(AnchorSampling.HIGHEST_CORNER, StiltShape.STRAIGHT), @Desc("Stilting is MIN_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - MIN_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.MIN, false)), + MIN_STILT(AnchorSampling.LOWEST, StiltShape.STRAIGHT), @Desc("Just like MIN_STILT but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") - FAST_MIN_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.MIN, true)), + FAST_MIN_STILT(AnchorSampling.LOWEST_CORNER, StiltShape.STRAIGHT), @Desc("Stilting is CENTER_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - CENTER_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.CENTER, false)), + CENTER_STILT(AnchorSampling.CENTER, StiltShape.STRAIGHT), @Desc("Erode stilting tapers columns downward like an ice cream cone. Blocks near the center extend deepest while edge blocks drop off first. Blocks are randomly skipped in the lower portion for a rough organic eroded texture.") - ERODE_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.ERODE, false)), + ERODE_STILT(AnchorSampling.HIGHEST, StiltShape.ERODE), @Desc("Organic stilting scans straight down from the bottom of the object to the first solid block (the cave floor, or terrain) and fills the gap with the object's own bottom block. Each column stops at a slightly different, noise-varied depth and the lower portion is randomly broken up, so the underside reads as rough organic roots rather than a flat disc. Designed for objects placed inside caves so they connect to the floor instead of floating. Tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") - ORGANIC_STILT(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.ORGANIC, false)), + ORGANIC_STILT(AnchorSampling.CENTER, StiltShape.ORGANIC), @Desc("Hangs the object upside-down from a cave ceiling. The object is flipped vertically (its tip points down like a stalactite) and its top is anchored to the ceiling, while an organic, noise-varied stilt grows up into the ceiling so it never floats below the roof. Use inside caves; tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") - CEILING_HANG(() -> new PlacementModuleStilt(PlacementModuleStilt.Mode.CEILING, false)), + CEILING_HANG(AnchorSampling.CENTER, StiltShape.CEILING), @Desc("Anchors the object at the terrain surface (plus translate.y) like CENTER_HEIGHT, then bends the surrounding terrain to be flush with the object's base. Columns inside the object footprint are raised (or lowered) to meet the base, and the deformation falls off parabolically out to a radius so the terrain smoothly blends back to its natural height. Use this to seat a floating/translated object on the ground without a flat stilt disc, e.g. a cube translated up 10 on a mountain pulls the terrain up to meet it. Tune with vacuum-settings (radius, falloff).") - VACUUM(PlacementModuleCenterHeight::new), + VACUUM(AnchorSampling.CENTER, StiltShape.NONE), @Desc("VACUUM with a larger radius and finer per-column sampling for the smoothest terrain blend. More expensive.") - VACUUM_HIGH(PlacementModuleCenterHeight::new), + VACUUM_HIGH(AnchorSampling.CENTER, StiltShape.NONE), @Desc("VACUUM with a smaller radius and coarser sampling for performance. Use when seating many objects.") - VACUUM_FAST(PlacementModuleCenterHeight::new), + VACUUM_FAST(AnchorSampling.CENTER, StiltShape.NONE), @Desc("VACUUM whose falloff radius is perturbed by noise per column, so the terrain meets the object with an irregular organic edge rather than a clean parabolic bowl.") - VACUUM_ORGANIC(PlacementModuleCenterHeight::new), + VACUUM_ORGANIC(AnchorSampling.CENTER, StiltShape.NONE), @Desc("VACUUM whose terrain bend is bent by smooth coherent simplex noise so the surface meets the object with a gently rolling, wavy slope instead of the ragged white-noise edge of VACUUM_ORGANIC or a clean parabolic bowl. The object itself still seats flush; the waves fade to zero under the object and at the outer rim, peaking across the mid-slope. Tune with vacuum-settings (waveAmplitude, waveScale).") - VACUUM_WAVY(PlacementModuleCenterHeight::new), + VACUUM_WAVY(AnchorSampling.CENTER, StiltShape.NONE), @Desc("Samples the height of the terrain at every x,z position of your object and pushes it down to the surface. It's pretty much like a melt function over the terrain.") - PAINT(PlacementModulePaint::new), + PAINT(AnchorSampling.SURFACE, StiltShape.NONE), @Desc("Places the object in pure air at an absolute Y driven entirely by translate.y (plus optional translate.yRandom). Terrain height, underwater, and carving anchor checks are skipped. Use this for floating islands, sky structures, clouds, or blimps where the object must not be translated to the ground.") - FLOATING(PlacementModuleFloating::new), + FLOATING(AnchorSampling.TRANSLATION, StiltShape.NONE), @Desc("Raw stamp at the caller-supplied (x, y, z). No terrain sampling, no stilting, no Y recomputation, no underwater or carving anchor guards. Used internally to route native Minecraft structure pieces (villages etc.) through the Iris object placer.") - STRUCTURE_PIECE(() -> lifecycle -> PlacementModuleAnchor.install(lifecycle, - (context, state, ignored) -> state.y = context.yv)); + STRUCTURE_PIECE(AnchorSampling.REQUESTED, StiltShape.NONE); + private final AnchorSampling anchor; + private final StiltShape stilt; - private final Supplier factory; - - ObjectPlaceMode(Supplier factory) { - this.factory = factory; + ObjectPlaceMode(AnchorSampling anchor, StiltShape stilt) { + this.anchor = anchor; + this.stilt = stilt; } - PlacementLifecycle createLifecycle() { - PlacementLifecycleBuilder lifecycle = new PlacementLifecycleBuilder(); - install(lifecycle); - return lifecycle.build(); + /** How a placement without a requested height finds one. */ + AnchorSampling anchor() { + return anchor; } - void install(PlacementLifecycleBuilder lifecycle) { - new PlacementModulePreparation().install(lifecycle); - new PlacementModuleSlope().install(lifecycle); - factory.get().install(lifecycle); - new PlacementModuleAnchor().install(lifecycle); - new PlacementModuleSurfaceSupport().install(lifecycle); - new PlacementModuleLimits().install(lifecycle); - new PlacementModuleNativeStructureProtection().install(lifecycle); - new PlacementModuleBounds().install(lifecycle); - new PlacementModuleCollision().install(lifecycle); - new PlacementModuleBore().install(lifecycle); - new PlacementModuleBlocks().install(lifecycle); - PlacementLifecycleDependency finish = switch (this) { - case STILT, FAST_STILT, MIN_STILT, FAST_MIN_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT, CEILING_HANG -> - PlacementModuleStilt.FILL; - case VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC, VACUUM_WAVY -> { - new PlacementModuleVacuum().install(lifecycle); - yield PlacementModuleVacuum.FINISH; - } - default -> PlacementModuleBlocks.COMPLETE; - }; - new PlacementModuleSnow(finish).install(lifecycle); + /** The stilt this mode grows under or above the object. */ + StiltShape stilt() { + return stilt; } - + boolean isVacuum() { + return IrisObjectVacuum.isVacuumMode(this); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java deleted file mode 100644 index 0107574e8..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlock.java +++ /dev/null @@ -1,9 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.IrisBlockVector; - -/** Source data and a placement-owned vector; changing the vector does not change the cached object. */ -public record PlacementBlock(PlatformBlockState data, TileData tile, IrisBlockVector vector) { -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java deleted file mode 100644 index 38a03f78c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementBlockWrite.java +++ /dev/null @@ -1,6 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.spi.PlatformBlockState; - -/** A completed object write, after its tile data and listener have been handled. */ -public record PlacementBlockWrite(int x, int y, int z, PlatformBlockState data) {} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java deleted file mode 100644 index a3f30eccc..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementContext.java +++ /dev/null @@ -1,45 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.terrain.carving.CarveResult; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.RNG; -import lombok.Getter; - -import java.util.Objects; -import java.util.function.BiConsumer; - -/** Caller inputs for one placement. Modules keep derived values in PlacementState. */ -@Getter -public final class PlacementContext { - public record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {} - public record WorldBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) {} - - final IrisObjectPlacement config; - final IrisData rdata; - final IObjectPlacer placer; - final CarveResult caveResult; - final RNG rng; - final IrisObject self; - final int x; - final int z; - final int yv; - final BiConsumer listener; - - public PlacementContext(IrisObjectPlacement config, IrisData rdata, IObjectPlacer placer, - CarveResult caveResult, RNG rng, IrisObject self, int x, int z, int yv, - BiConsumer listener) { - this.placer = Objects.requireNonNull(placer, "Object placer is required."); - this.config = Objects.requireNonNull(config, "Object placement config is required."); - this.rng = Objects.requireNonNull(rng, "Object placement RNG is required."); - this.rdata = Objects.requireNonNull(rdata, "Object placement data is required."); - this.self = Objects.requireNonNull(self, "Object is required."); - this.caveResult = caveResult; - this.x = x; - this.z = z; - this.yv = yv; - this.listener = listener; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java deleted file mode 100644 index 15326a3cc..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementFunction.java +++ /dev/null @@ -1,6 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -@FunctionalInterface -public interface PlacementFunction { - void execute(PlacementContext context, PlacementState state, C input); -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java deleted file mode 100644 index 378b59ee7..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycle.java +++ /dev/null @@ -1,35 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import java.util.List; - -/** Immutable plan. Placement performs no registration, graph traversal, or sorting. */ -public final class PlacementLifecycle { - private final List>> stages; - - PlacementLifecycle(List> ordered) { - stages = PlacementStage.ALL.stream() - .map(stage -> ordered.stream().filter(step -> step.stage() == stage).toList()).toList(); - } - - public PlacementState execute(PlacementContext context) { - PlacementState state = new PlacementState(context); - for (PlacementStage stage : PlacementStage.BEFORE_PASS) { - run(stage, context, state, null); - } - run(PlacementStage.BLOCKS, context, state, this); - run(PlacementStage.AFTER_BLOCKS, context, state, null); - return state; - } - - public void run(PlacementStage stage, PlacementContext context, PlacementState state, C input) { - for (PlacementLifecycleBuilder.Step step : stages.get(stage.order)) { - if (state.isRejected()) { - return; - } - // Registration pairs each function with its typed stage. - @SuppressWarnings("unchecked") - PlacementFunction function = (PlacementFunction) step.function(); - function.execute(context, state, input); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java deleted file mode 100644 index 9454cfe8c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleBuilder.java +++ /dev/null @@ -1,84 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.PriorityQueue; - -/** - * Registers steps and resolves their graph before an engine runtime is published. - * A dependency names a required step, not a Java class: two instances of the same module can - * register distinct work. Declaring a dependency does not install its prerequisite. - * The module composition must register it, in any order, before calling {@link #build()}. - * - *

{@code
- * lifecycle.add(FILL, PlacementStage.AFTER_BLOCKS, this::fill, HEIGHT, BOUNDS);
- * }
- * - * Independent steps retain registration order within their stage. Invalid graphs fail construction; - * the builder never executes functions. Functions must not capture mutable placement state. - */ -public final class PlacementLifecycleBuilder { - private final Map> steps = new LinkedHashMap<>(); - - public void add(PlacementLifecycleDependency id, PlacementStage stage, - PlacementFunction function, PlacementLifecycleDependency... after) { - Objects.requireNonNull(id, "Step id"); - Objects.requireNonNull(stage, "Stage"); - Objects.requireNonNull(function, "Function"); - Step step = new Step<>(id, stage, function, List.of(after), steps.size()); - if (steps.putIfAbsent(id, step) != null) { - throw new IllegalArgumentException("Duplicate placement step '" + id.name() + "'"); - } - } - - /** Stable topological sort; stage barriers do not need all-to-all edges. */ - public PlacementLifecycle build() { - Map remaining = new HashMap<>(); - Map>> dependents = new HashMap<>(); - PriorityQueue> ready = new PriorityQueue<>(Comparator.>comparingInt(step -> step.stage.order).thenComparingInt(Step::index)); - for (Step step : steps.values()) { - var prerequisites = step.after.stream().distinct().toList(); - remaining.put(step.id, prerequisites.size()); - for (PlacementLifecycleDependency id : prerequisites) { - Step prerequisite = steps.get(id); - if (prerequisite == null) { - throw new IllegalArgumentException("Placement step '" + step.id.name() - + "' requires missing step '" + id.name() + "'"); - } - if (prerequisite.stage.order > step.stage.order) { - throw new IllegalArgumentException("Placement step '" + step.id.name() + "' in " + step.stage - + " cannot depend on later step '" + id.name() + "' in " + prerequisite.stage); - } - dependents.computeIfAbsent(id, ignored -> new ArrayList<>()).add(step); - } - if (prerequisites.isEmpty()) { - ready.add(step); - } - } - List> ordered = new ArrayList<>(steps.size()); - while (!ready.isEmpty()) { - Step step = ready.remove(); - ordered.add(step); - for (Step dependent : dependents.getOrDefault(step.id, List.of())) { - if (remaining.compute(dependent.id, (ignored, count) -> count - 1) == 0) { - ready.add(dependent); - } - } - } - if (ordered.size() != steps.size()) { - throw new IllegalArgumentException("Placement dependency cycle; unresolved steps: " - + steps.keySet().stream().filter(id -> remaining.get(id) > 0) - .map(PlacementLifecycleDependency::name).toList()); - } - return new PlacementLifecycle(ordered); - } - - record Step(PlacementLifecycleDependency id, PlacementStage stage, PlacementFunction function, - List after, int index) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java deleted file mode 100644 index 399e7c0de..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycleDependency.java +++ /dev/null @@ -1,13 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import java.util.Objects; - -/** A named prerequisite, scoped to one placement plan. */ -public record PlacementLifecycleDependency(String name) { - public PlacementLifecycleDependency { - Objects.requireNonNull(name, "Dependency name"); - if (name.isBlank()) { - throw new IllegalArgumentException("Placement dependency name cannot be blank"); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java deleted file mode 100644 index d59d5eae8..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementLifecycles.java +++ /dev/null @@ -1,43 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import java.util.EnumMap; -import java.util.Map; - -/** One resolved plan per mode in an engine runtime. Engine-less tools share a separate default set. */ -public final class PlacementLifecycles { - private final Map plans; - - private PlacementLifecycles(Map plans) { - this.plans = Map.copyOf(plans); - } - - public static PlacementLifecycles resolve() { - Map plans = new EnumMap<>(ObjectPlaceMode.class); - for (ObjectPlaceMode mode : ObjectPlaceMode.values()) { - try { - plans.put(mode, mode.createLifecycle()); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Invalid placement lifecycle for " + mode + ": " + e.getMessage(), e); - } - } - return new PlacementLifecycles(plans); - } - - public static PlacementLifecycles defaults() { - return Defaults.INSTANCE; - } - - static PlacementLifecycles forPlacer(IObjectPlacer placer) { - var engine = placer.getEngine(); - PlacementLifecycles plans = engine == null ? null : engine.getPlacementLifecycles(); - return plans == null ? defaults() : plans; - } - - public PlacementLifecycle get(ObjectPlaceMode mode) { - return plans.get(java.util.Objects.requireNonNull(mode, "Placement mode")); - } - - private static final class Defaults { - private static final PlacementLifecycles INSTANCE = resolve(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java deleted file mode 100644 index e9e0eb433..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModule.java +++ /dev/null @@ -1,9 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -/** - * Registers work during runtime construction. Functions are shared by concurrent placements: - * implementations must receive placement state at execution time, never capture it at installation. - */ -public interface PlacementModule { - void install(PlacementLifecycleBuilder lifecycle); -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java deleted file mode 100644 index f9a60c738..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleAnchor.java +++ /dev/null @@ -1,43 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; -/** Common caller-supplied and from-bottom anchors wrap each mode's sampled height. */ -final class PlacementModuleAnchor implements PlacementModule { - static final PlacementLifecycleDependency HEIGHT = new PlacementLifecycleDependency("anchor.height"); - static final PlacementLifecycleDependency POSITIONED = new PlacementLifecycleDependency("anchor.positioned"); - static final PlacementLifecycleDependency FINAL_HEIGHT = new PlacementLifecycleDependency("anchor.final"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(POSITIONED, PlacementStage.HEIGHT, (context, state, ignored) -> { - if (context.yv >= 0 && state.config.isBottom() - && state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE) { - state.y += Math.floorDiv(context.self.h, 2); - if (!state.config.isForcePlace() && state.config.getCarvingSupport() != CarvingMode.CARVING_ONLY - && PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { - state.reject("carving-anchor"); - } - } - }, HEIGHT); - lifecycle.add(FINAL_HEIGHT, PlacementStage.BEFORE_BLOCKS, - (context, state, ignored) -> state.y += state.yrand, POSITIONED, PlacementModuleCollision.CHECK); - } - - static void install(PlacementLifecycleBuilder lifecycle, PlacementFunction sampledHeight) { - lifecycle.add(HEIGHT, PlacementStage.HEIGHT, (context, state, ignored) -> { - if (state.config.isFromBottom()) { - state.y = context.self.getH() + 1 + state.rty; - } else if (context.yv < 0) { - sampledHeight.execute(context, state, null); - return; - } else { - state.y = context.yv; - } - if (!state.config.isForcePlace() - && state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE - && PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { - state.reject("carving-anchor"); - } - }, PlacementModulePreparation.TRANSFORMS); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java deleted file mode 100644 index 5231eb414..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBlocks.java +++ /dev/null @@ -1,18 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -/** Owns block-pass execution and the object read lock. */ -final class PlacementModuleBlocks implements PlacementModule { - static final PlacementLifecycleDependency COMPLETE = new PlacementLifecycleDependency("blocks.complete"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(COMPLETE, PlacementStage.BLOCKS, (context, state, plan) -> { - context.self.readLock.lock(); - try { - new ObjectBlockPass(context, state, plan, context.listener).process(); - } finally { - context.self.readLock.unlock(); - } - }, PlacementModuleBore.BORE); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java deleted file mode 100644 index 3971388ef..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBore.java +++ /dev/null @@ -1,25 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -/** The first world-writing step; all placement guards must have completed. */ -final class PlacementModuleBore implements PlacementModule { - static final PlacementLifecycleDependency BORE = new PlacementLifecycleDependency("bore"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(BORE, PlacementStage.BEFORE_BLOCKS, (context, state, ignored) -> { - if (!state.config.isBore()) { - return; - } - var bounds = state.worldBounds; - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - for (int y = bounds.minY() - state.config.getBoreExtendMinY(); - y <= bounds.maxY() + state.config.getBoreExtendMaxY(); y++) { - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - state.placer.set(x, y, z, IrisObject.States.AIR); - } - } - } - }, PlacementModuleBounds.WORLD, PlacementModuleCollision.CHECK, PlacementModuleAnchor.FINAL_HEIGHT); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java deleted file mode 100644 index 50fc4674e..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleBounds.java +++ /dev/null @@ -1,43 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -/** Computes the shared world volume for collision checks and boring, only when needed. */ -final class PlacementModuleBounds implements PlacementModule { - static final PlacementLifecycleDependency WORLD = new PlacementLifecycleDependency("bounds.world"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(WORLD, PlacementStage.VALIDATE, (context, state, ignored) -> { - IrisObjectPlacement config = state.config; - if (config.isBore() || (!config.isForcePlace() && config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE - && (!config.getAllowedCollisions().isEmpty() || !config.getForbiddenCollisions().isEmpty()))) { - state.worldBounds = resolve(context, state, context.yv < 0 && config.getMode() == ObjectPlaceMode.PAINT); - } - }, PlacementModuleNativeStructureProtection.CHECK); - } - - private static PlacementContext.WorldBounds resolve(PlacementContext context, PlacementState state, boolean paint) { - int x = context.x; - int z = context.z; - int y = state.y + state.yrand; - int minX = x + state.bounds.minX(); - int maxX = x + state.bounds.maxX(); - int minZ = z + state.bounds.minZ(); - int maxZ = z + state.bounds.maxZ(); - if (!paint) { - return new PlacementContext.WorldBounds(minX, maxX, y + state.bounds.minY(), y + state.bounds.maxY(), minZ, maxZ); - } - - int minimumSurface = Integer.MAX_VALUE; - int maximumSurface = Integer.MIN_VALUE; - for (int worldX = minX; worldX <= maxX; worldX++) { - for (int worldZ = minZ; worldZ <= maxZ; worldZ++) { - int surface = state.placer.getHighest(worldX, worldZ, context.self.getLoader(), state.config.isUnderwater()); - minimumSurface = Math.min(minimumSurface, surface); - maximumSurface = Math.max(maximumSurface, surface); - } - } - int paintOffset = Math.floorDiv(context.self.h, 2); - return new PlacementContext.WorldBounds(minX, maxX, minimumSurface + state.bounds.minY() + paintOffset, - maximumSurface + state.bounds.maxY() + paintOffset, minZ, maxZ); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java deleted file mode 100644 index fe9cb93a2..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCenterHeight.java +++ /dev/null @@ -1,18 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -public final class PlacementModuleCenterHeight implements PlacementModule { - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - PlacementModuleAnchor.install(lifecycle, PlacementModuleCenterHeight::sample); - } - - private static void sample(PlacementContext context, PlacementState state, Void ignored) { - state.y = (context.caveResult != null ? context.caveResult.getSurface() : state.placer.getHighest(context.x, context.z, context.self.getLoader(), state.config.isUnderwater())) + state.rty; - if (!state.config.isForcePlace()) { - if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { - state.reject("carving-anchor"); - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java deleted file mode 100644 index db589dd06..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleCollision.java +++ /dev/null @@ -1,41 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.PlacedObject; - -/** Owns object collision policy and its data-engine requirement. */ -final class PlacementModuleCollision implements PlacementModule { - static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.collisions"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { - IrisObjectPlacement config = state.config; - if (config.isForcePlace() || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE - || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { - return; - } - Engine engine = context.rdata.getEngine(); - if (engine == null) { - throw new IllegalStateException("Object placement requires active Iris data for collision settings."); - } - var bounds = state.worldBounds; - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - for (int y = bounds.minY(); y <= bounds.maxY(); y++) { - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - PlacedObject placed = engine.getObjectPlacement(x, y, z); - if (placed == null || placed.getObject() == null) { - continue; - } - String key = placed.getObject().getLoadKey(); - if (key != null && config.getForbiddenCollisions().contains(key) - && !config.getAllowedCollisions().contains(key)) { - state.reject("object-collision"); - return; - } - } - } - } - }, PlacementModuleBounds.WORLD); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java deleted file mode 100644 index f407192ce..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleFloating.java +++ /dev/null @@ -1,10 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -public final class PlacementModuleFloating implements PlacementModule { - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - PlacementModuleAnchor.install(lifecycle, (context, state, ignored) -> state.y = state.rty); - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java deleted file mode 100644 index 8ddb2ee9c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleHeight.java +++ /dev/null @@ -1,57 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -public final class PlacementModuleHeight implements PlacementModule { - private final boolean fast; - private final Mode mode; - - public enum Mode { - MIN, - MAX - } - - public PlacementModuleHeight(Mode mode, boolean fast) { - this.fast = fast; - this.mode = mode; - } - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - PlacementModuleAnchor.install(lifecycle, this::sample); - } - - private void sample(PlacementContext context, PlacementState state, Void ignored) { - int minX = context.x + state.bounds.minX(); - int maxX = context.x + state.bounds.maxX(); - int minZ = context.z + state.bounds.minZ(); - int maxZ = context.z + state.bounds.maxZ(); - if (Mode.MIN == mode) { - state.y = Integer.MAX_VALUE; - } - int xStep = fast ? Math.max(0, (maxX - minX) / 2) + 1 : 1; - int zStep = fast ? Math.max(0, (maxZ - minZ) / 2) + 1 : 1; - for (int i = minX; i <= maxX; i += xStep) { - for (int ii = minZ; ii <= maxZ; ii += zStep) { - columnHeight(context, state, i, ii); - if (state.isRejected()) { - return; - } - } - } - } - - private void columnHeight(PlacementContext context, PlacementState state, int i, int ii) { - int h = state.placer.getHighest(i, ii, context.self.getLoader(), state.config.isUnderwater()) + state.rty; - if (!state.config.isForcePlace()) { - if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, i, h, ii)) { - state.reject("carving-anchor"); - } - } - - if (Mode.MIN == mode && h < state.y) { - state.y = h; - } - if (Mode.MAX == mode && h > state.y) { - state.y = h; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java deleted file mode 100644 index f2ec8852d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleLimits.java +++ /dev/null @@ -1,34 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -/** Water, cave clearance and height-clamp eligibility. */ -final class PlacementModuleLimits implements PlacementModule { - static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.limits"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { - IrisObjectPlacement config = state.config; - if (config.isForcePlace() || config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE) { - return; - } - if (context.yv < 0 && config.getMode() != ObjectPlaceMode.FLOATING - && !config.isUnderwater() && !config.isOnwater() - && state.placer.isUnderwater(context.x, context.z)) { - state.reject("underwater-anchor"); - return; - } - if (context.caveResult != null - && Math.max(0, context.self.h + state.yrand + state.ty) + 1 >= context.caveResult.getHeight()) { - state.reject("cave-clearance"); - return; - } - if (config.isUnderwater() && state.y + state.rty + state.ty >= state.placer.getFluidHeight()) { - state.reject("fluid-height"); - return; - } - if (!config.getClamp().canPlace(state.y + state.rty + state.ty, state.y - state.rty + state.ty)) { - state.reject("height-clamp"); - } - }, PlacementModuleSurfaceSupport.CHECK); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java deleted file mode 100644 index d535586ae..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleNativeStructureProtection.java +++ /dev/null @@ -1,113 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.NativeStructureVolume; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.volmlib.util.collection.KList; - -/** Native structures remain protected even when forcePlace bypasses optional placement checks. */ -final class PlacementModuleNativeStructureProtection implements PlacementModule { - static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.native-structures"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { - if (state.config.getMode() != ObjectPlaceMode.STRUCTURE_PIECE && vetoes(context, state)) { - state.reject("native-structure"); - } - }, PlacementModuleLimits.CHECK); - } - - private static boolean vetoes(PlacementContext context, PlacementState state) { - IrisObject self = context.self; - IObjectPlacer placer = state.placer; - IrisObjectPlacement config = state.config; - ObjectSpinKernel spin = state.spin; - IrisBlockVector translateOffset = state.translateOffset; - boolean translating = translateOffset != null; - boolean ceilingHang = config.getMode() == ObjectPlaceMode.CEILING_HANG; - boolean paint = context.yv < 0 && config.getMode() == ObjectPlaceMode.PAINT; - int warpMargin = state.warpMargin; - int x = context.x; - int y = state.y + state.yrand; - int z = context.z; - Engine engine = placer.getEngine(); - if (engine == null) { - return false; - } - - int margin = (Math.max(self.getW(), Math.max(self.getH(), self.getD())) / 2) + 1 + warpMargin; - if (translating) { - margin += Math.max(Math.abs(translateOffset.getBlockX()), - Math.max(Math.abs(translateOffset.getBlockY()), Math.abs(translateOffset.getBlockZ()))); - } - - KList volumes = engine.getNativeStructureVolumes(x - margin, z - margin, x + margin, z + margin); - if (volumes == null || volumes.isEmpty()) { - return false; - } - - int worldY = y + engine.getMinHeight(); - int envelopeMinY = paint ? Integer.MIN_VALUE : worldY - margin; - int envelopeMaxY = paint ? Integer.MAX_VALUE : worldY + margin; - boolean envelopeMeetsPiece = false; - for (NativeStructureVolume volume : volumes) { - if (volume.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { - envelopeMeetsPiece = true; - break; - } - } - - if (!envelopeMeetsPiece) { - return false; - } - - self.readLock.lock(); - try { - VectorMap.Cursor cursor = self.blocks.cursor(); - while (cursor.next()) { - PlatformBlockState source = cursor.value(); - if (source == null || isAirBlock(source)) { - continue; - } - - IrisBlockVector i = cursor.key().clone(); - spin.rotate(i); - if (ceilingHang) { - i.setY(-i.getBlockY()); - } - if (translating) { - i.add(translateOffset); - } - - int xx = x + (int) Math.round(i.getX()); - int zz = z + (int) Math.round(i.getZ()); - int yy = paint - ? (int) Math.round(i.getY()) + Math.floorDiv(self.h, 2) - + placer.getHighest(xx, zz, self.getLoader(), config.isUnderwater()) - : y + (int) Math.round(i.getY()); - int worldBlockY = yy + engine.getMinHeight(); - - for (NativeStructureVolume volume : volumes) { - if (volume.containsWithin(xx, worldBlockY, zz, warpMargin)) { - return true; - } - } - } - } finally { - self.readLock.unlock(); - } - - return false; - } - - private static boolean isAirBlock(PlatformBlockState state) { - String material = IrisObjectShaping.materialKey(state); - return material.equals("minecraft:air") || material.equals("minecraft:cave_air"); - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java deleted file mode 100644 index 4f1404e2a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePaint.java +++ /dev/null @@ -1,18 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -public final class PlacementModulePaint implements PlacementModule { - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - PlacementModuleAnchor.install(lifecycle, PlacementModulePaint::sample); - } - - private static void sample(PlacementContext context, PlacementState state, Void ignored) { - state.y = state.placer.getHighest(context.x, context.z, context.self.getLoader(), state.config.isUnderwater()) + state.rty; - if (!state.config.isForcePlace()) { - if (PlacementModuleSurfaceSupport.rejectsAnchor(context, state, context.x, state.y, context.z)) { - state.reject("carving-anchor"); - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java deleted file mode 100644 index a3593ccad..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModulePreparation.java +++ /dev/null @@ -1,98 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; -import art.arcane.iris.util.common.math.IrisBlockVector; - -/** Resolves the placer and transforms once, preserving the caller's RNG draw order. */ -final class PlacementModulePreparation implements PlacementModule { - static final PlacementLifecycleDependency PLACER = new PlacementLifecycleDependency("prepare.placer"); - static final PlacementLifecycleDependency TRANSFORMS = new PlacementLifecycleDependency("prepare.transforms"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(PLACER, PlacementStage.PREPARE, (context, state, ignored) -> { - if (state.config.getHeightmap() != null) { - state.placer = new HeightmapObjectPlacer(context.rng, context.x, context.yv, context.z, - state.config, context.placer); - } - }); - lifecycle.add(TRANSFORMS, PlacementStage.PREPARE, PlacementModulePreparation::prepare, - PlacementModuleSlope.SLOPE); - } - - private static void prepare(PlacementContext context, PlacementState state, Void ignored) { - IrisObjectPlacement config = state.config; - IrisObject self = context.self; - if (config.isSmartBore()) { - IrisObjectShaping.ensureSmartBored(self); - } - int spinx = context.rng.imax() / 1000; - int spiny = context.rng.imax() / 1000; - int spinz = context.rng.imax() / 1000; - state.spinX = spinx; - state.spinY = spiny; - state.spinZ = spinz; - state.rty = config.getRotation().rotate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); - state.ty = config.getTranslate().translate(new IrisBlockVector(0, self.getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); - state.spin = new ObjectSpinKernel(config.getRotation(), spinx, spiny, spinz); - IrisObjectTranslate translate = config.getTranslate(); - if (translate.canTranslate()) { - state.translateOffset = config.getRotation().rotate( - new IrisBlockVector(translate.getX(), translate.getY(), translate.getZ()), spinx, spiny, spinz); - } - int yrand = translate.getYRandom(); - state.yrand = yrand > 0 ? context.rng.i(0, yrand) : yrand < 0 ? context.rng.i(yrand, 0) : yrand; - state.warpMargin = !config.getWarp().isFlat() ? (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D) : 0; - state.bounds = transformedBounds(self, state.spin, state.translateOffset != null, state.translateOffset, - config.getMode() == ObjectPlaceMode.CEILING_HANG, state.warpMargin); - } - - private static PlacementContext.TransformedBounds transformedBounds(IrisObject self, ObjectSpinKernel spin, boolean translating, IrisBlockVector translateOffset, - boolean ceilingHang, int margin) { - int sourceMinX = -self.getCenter().getBlockX(); - int sourceMaxX = self.getW() - self.getCenter().getBlockX() - 1; - int sourceMinY = -self.getCenter().getBlockY(); - int sourceMaxY = self.getH() - self.getCenter().getBlockY() - 1; - int sourceMinZ = -self.getCenter().getBlockZ(); - int sourceMaxZ = self.getD() - self.getCenter().getBlockZ() - 1; - int minX = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE; - int minY = Integer.MAX_VALUE; - int maxY = Integer.MIN_VALUE; - int minZ = Integer.MAX_VALUE; - int maxZ = Integer.MIN_VALUE; - - for (int xCorner = 0; xCorner < 2; xCorner++) { - int sourceX = xCorner == 0 ? sourceMinX : sourceMaxX; - for (int yCorner = 0; yCorner < 2; yCorner++) { - int sourceY = yCorner == 0 ? sourceMinY : sourceMaxY; - for (int zCorner = 0; zCorner < 2; zCorner++) { - int sourceZ = zCorner == 0 ? sourceMinZ : sourceMaxZ; - IrisBlockVector corner = new IrisBlockVector(sourceX, sourceY, sourceZ); - spin.rotate(corner); - if (ceilingHang) { - corner.setY(-corner.getBlockY()); - } - if (translating) { - corner.add(translateOffset); - } - int transformedX = (int) Math.round(corner.getX()); - int transformedY = (int) Math.round(corner.getY()); - int transformedZ = (int) Math.round(corner.getZ()); - minX = Math.min(minX, transformedX); - maxX = Math.max(maxX, transformedX); - minY = Math.min(minY, transformedY); - maxY = Math.max(maxY, transformedY); - minZ = Math.min(minZ, transformedZ); - maxZ = Math.max(maxZ, transformedZ); - } - } - } - - return new PlacementContext.TransformedBounds(minX - margin, maxX + margin, minY, maxY, minZ - margin, maxZ + margin); - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java deleted file mode 100644 index bd8618767..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSlope.java +++ /dev/null @@ -1,72 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.util.project.stream.ProceduralStream; - -/** Slope checks precede random rotation and leave the caller's configuration intact. */ -final class PlacementModuleSlope implements PlacementModule { - static final PlacementLifecycleDependency SLOPE = new PlacementLifecycleDependency("prepare.slope"); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(SLOPE, PlacementStage.PREPARE, (context, state, ignored) -> { - IrisObjectPlacement config = state.config; - boolean evaluate = !config.isForcePlace() && !config.getSlopeCondition().isDefault(); - if (!evaluate && !config.isRotateTowardsSlope()) { - return; - } - Engine engine = state.placer.getEngine(); - if (engine == null) { - throw new IllegalStateException("Object placement requires an active Iris engine for slope settings."); - } - if (evaluate && !config.getSlopeCondition().isValid( - engine.getComplex().getSlopeStream().get(context.x, context.z))) { - state.reject("slope"); - return; - } - if (config.isRotateTowardsSlope()) { - state.config = rotate(context.self, config, engine, context.x, context.z); - } - }, PlacementModulePreparation.PLACER); - } - - private static IrisObjectPlacement rotate(IrisObject self, IrisObjectPlacement config, Engine engine, int x, int z) { - int slopeRotationY = 0; - ProceduralStream heightStream = engine.getComplex().getHeightStream(); - // Whichever side of the rectangle that bounds the object is lowest is the 'direction' of the slope (simply said). - double hNorth = heightStream.get(x, z + ((float) self.d) / 2); - double hEast = heightStream.get(x + ((float) self.w) / 2, z); - double hSouth = heightStream.get(x, z - ((float) self.d) / 2); - double hWest = heightStream.get(x - ((float) self.w) / 2, z); - double min = Math.min(Math.min(hNorth, hEast), Math.min(hSouth, hWest)); - if (min == hNorth) { - slopeRotationY = 0; - } else if (min == hEast) { - slopeRotationY = 90; - } else if (min == hSouth) { - slopeRotationY = 180; - } else if (min == hWest) { - slopeRotationY = 270; - } - - double newRotation = config.getRotation().getYAxis().getMin() + slopeRotationY; - IrisObjectRotation originalRotation = config.getRotation(); - IrisObjectRotation slopeRotation = new IrisObjectRotation(); - slopeRotation.setXAxis(originalRotation.getXAxis()); - slopeRotation.setZAxis(originalRotation.getZAxis()); - if (newRotation == 0) { - slopeRotation.setYAxis(new IrisAxisRotationClamp(false, false, 0, 0, 90)); - slopeRotation.setEnabled(originalRotation.canRotateX() || originalRotation.canRotateZ()); - } else { - slopeRotation.setYAxis(new IrisAxisRotationClamp(true, false, newRotation, newRotation, 90)); - slopeRotation.setEnabled(true); - } - config = config.toPlacement(config.getPlace().toArray(new String[0])); - config.setRotation(slopeRotation); - return config; - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java deleted file mode 100644 index 0a452c6c9..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSnow.java +++ /dev/null @@ -1,45 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.math.Position2; -import art.arcane.volmlib.util.math.RNG; - -/** Snow uses only successful object writes, and follows stilt or vacuum work. */ -final class PlacementModuleSnow implements PlacementModule { - static final PlacementLifecycleDependency COLLECT = new PlacementLifecycleDependency("snow.collect"); - static final PlacementLifecycleDependency FINISH = new PlacementLifecycleDependency("snow.finish"); - private final PlacementLifecycleDependency after; - - PlacementModuleSnow(PlacementLifecycleDependency after) { - this.after = after; - } - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(COLLECT, PlacementStage.BLOCK_WRITTEN, (context, state, block) -> { - if (!(state.config.getSnow() > 0)) { - return; - } - if (state.snowHeights == null) { - state.snowHeights = new KMap<>(); - } - Position2 position = new Position2(block.x(), block.z()); - Integer current = state.snowHeights.get(position); - if (current == null || current < block.y()) { - state.snowHeights.put(position, block.y()); - } - }); - lifecycle.add(FINISH, PlacementStage.AFTER_BLOCKS, (context, state, ignored) -> { - if (state.snowHeights == null) { - return; - } - RNG rng = context.rng.nextParallelRNG(3468854); - for (Position2 position : state.snowHeights.k()) { - int height = rng.i(0, (int) (state.config.getSnow() * 7)); - state.placer.set(position.getX(), state.snowHeights.get(position) + 1, position.getZ(), - IrisObject.States.SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); - } - }, COLLECT, after); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java deleted file mode 100644 index 67fd1b62b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleStilt.java +++ /dev/null @@ -1,317 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.material.BlockDataMergeSupport; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; - -/** Stilt preparation observes all transformed blocks before the fill step runs. */ -public final class PlacementModuleStilt implements PlacementModule { - static final PlacementLifecycleDependency BOUNDS = new PlacementLifecycleDependency("stilt.bounds"); - static final PlacementLifecycleDependency FILL = new PlacementLifecycleDependency("stilt.fill"); - - private final boolean fast; - private final Mode mode; - - public enum Mode { - DEFAULT, CENTER, MIN, ERODE, ORGANIC, CEILING - } - - public PlacementModuleStilt(Mode mode, boolean fast) { - this.mode = mode; - this.fast = fast; - } - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - PlacementModule height = switch (mode) { - case CENTER, ORGANIC, CEILING -> new PlacementModuleCenterHeight(); - case MIN -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MIN, fast); - case DEFAULT, ERODE -> new PlacementModuleHeight(PlacementModuleHeight.Mode.MAX, fast); - }; - height.install(lifecycle); - if (mode == Mode.CEILING) { - new ObjectModuleCeilingHang().install(lifecycle); - } - PlacementLifecycleDependency[] prerequisites = mode == Mode.CEILING - ? new PlacementLifecycleDependency[]{PlacementModuleAnchor.HEIGHT, ObjectModuleCeilingHang.FLIP} - : new PlacementLifecycleDependency[]{PlacementModuleAnchor.HEIGHT}; - lifecycle.add(BOUNDS, PlacementStage.COLLECT_BLOCK, (context, state, block) -> { - if (IrisObjectShaping.shouldStilt(block.data())) { - state.stiltLowest = Math.min(state.stiltLowest, block.vector().getBlockY()); - state.stiltHighest = Math.max(state.stiltHighest, block.vector().getBlockY()); - } - }, prerequisites); - lifecycle.add(FILL, PlacementStage.AFTER_BLOCKS, this::fill, PlacementModuleAnchor.HEIGHT, BOUNDS, PlacementModuleBlocks.COMPLETE); - } - - private void fill(PlacementContext context, PlacementState state, Void ignored) { - if (state.stiltLowest == Integer.MAX_VALUE) { - return; - } - IrisObject self = context.self; - IrisObjectPlacement config = state.config; - IObjectPlacer placer = state.placer; - IrisData rdata = context.rdata; - RNG rng = context.rng; - ObjectSpinKernel spin = state.spin; - IrisBlockVector translateOffset = state.translateOffset; - boolean translating = translateOffset != null; - boolean ceilingHang = mode == Mode.CEILING; - boolean organic = mode == Mode.ORGANIC || ceilingHang; - boolean eroding = mode == Mode.ERODE; - boolean hasEdits = !config.getEdit().isEmpty(); - boolean warped = !config.getWarp().isFlat(); - CNG surfaceWarp = warped ? config.getSurfaceWarp(rng, self.getLoader()) : null; - double warpHalf = warped ? config.getWarp().getMultiplier() / 2D : 0D; - int x = context.x; - int z = context.z; - int y = state.y; - int lowest = state.stiltLowest; - int topLayer = state.stiltHighest; - int xx, zz; - self.readLock.lock(); - try { - VectorMap blocks = self.blocks; - IrisStiltSettings settings = config.getStiltSettings(); - - double erodeCentroidX = 0; - double erodeCentroidZ = 0; - double erodeMaxDist = 1; - if (eroding) { - int centroidCount = 0; - VectorMap.Cursor centroidCursor = blocks.cursor(); - while (centroidCursor.next()) { - IrisBlockVector rot = centroidCursor.key().clone(); - spin.rotate(rot); - if (translating) { - rot.add(translateOffset); - } - if (rot.getBlockY() == lowest) { - PlatformBlockState bd = centroidCursor.value(); - if (bd != null && IrisObjectShaping.shouldStilt(bd)) { - erodeCentroidX += rot.getX(); - erodeCentroidZ += rot.getZ(); - centroidCount++; - } - } - } - if (centroidCount > 0) { - erodeCentroidX /= centroidCount; - erodeCentroidZ /= centroidCount; - } - VectorMap.Cursor spreadCursor = blocks.cursor(); - while (spreadCursor.next()) { - IrisBlockVector rot = spreadCursor.key().clone(); - spin.rotate(rot); - if (translating) { - rot.add(translateOffset); - } - if (rot.getBlockY() == lowest) { - PlatformBlockState bd = spreadCursor.value(); - if (bd != null && IrisObjectShaping.shouldStilt(bd)) { - double dx = rot.getX() - erodeCentroidX; - double dz = rot.getZ() - erodeCentroidZ; - double dist = Math.sqrt(dx * dx + dz * dz); - if (dist > erodeMaxDist) { - erodeMaxDist = dist; - } - } - } - } - } - - VectorMap.Cursor stiltCursor = blocks.cursor(); - while (stiltCursor.next()) { - IrisBlockVector g = stiltCursor.key(); - PlatformBlockState sourceData; - try { - sourceData = stiltCursor.value(); - } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (stilt cme)"); - sourceData = IrisObject.States.AIR; - } - - if (sourceData == null) { - IrisLogging.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + self.getLoadKey() + " (stilt null)"); - sourceData = IrisObject.States.AIR; - } - - if (!IrisObjectShaping.shouldStilt(sourceData)) { - continue; - } - - PlatformBlockState d = sourceData; - if (settings != null && settings.getPalette() != null) { - d = config.getStiltSettings().getPalette().get(rng, x, y, z, rdata); - } else { - String mat = IrisObjectShaping.materialKey(d); - if (mat.equals("minecraft:grass_block") || mat.equals("minecraft:mycelium") || mat.equals("minecraft:podzol") || mat.equals("minecraft:dirt_path")) { - d = B.getState("minecraft:dirt"); - } - } - - IrisBlockVector i = g.clone(); - spin.rotate(i); - if (ceilingHang) { - i.setY(-i.getBlockY()); - } - if (translating) { - i.add(translateOffset); - } - d = spin.rotate(d); - - int targetLayer = ceilingHang ? topLayer : lowest; - if (i.getBlockY() != targetLayer) - continue; - - if (hasEdits) { - for (IrisObjectReplace j : config.getEdit()) { - if (rng.chance(j.getChance())) { - for (PlatformBlockState k : j.getFind(rdata)) { - if (d == null) { - continue; - } - if (j.isExact() ? k.matches(d) : IrisObjectShaping.materialKey(k).equals(IrisObjectShaping.materialKey(d))) { - PlatformBlockState newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata); - - if (IrisObjectShaping.materialKey(newData).equals(IrisObjectShaping.materialKey(d))) { - d = BlockDataMergeSupport.merge(d, newData); - } else { - d = newData; - } - } - } - } - } - } - - if (d == null || !d.isOccluding()) - continue; - - xx = x + (int) Math.round(i.getX()); - zz = z + (int) Math.round(i.getZ()); - - if (warped) { - xx += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getX() + x, i.getY() + y, i.getZ() + z); - zz += surfaceWarp.fitDouble(-warpHalf, warpHalf, i.getZ() + z, i.getY() + y, i.getX() + x); - } - - if (organic) { - int startY = targetLayer + y; - int maxScan = settings != null ? Math.max(1, settings.getOrganicMaxScan()) : 48; - int jitterMax = settings != null ? Math.max(0, settings.getOrganicJitter()) : 3; - double scratch = settings != null ? Math.max(0, Math.min(1, settings.getOrganicScratch())) : 0.55; - long colHash = ((long) xx * 341873128712L) ^ ((long) zz * 132897987541L); - int jitter = jitterMax > 0 ? (int) (Math.abs(colHash) % (jitterMax + 1)) : 0; - - if (ceilingHang) { - int scan = 0; - int solidY = startY + 1; - while (scan < maxScan && !placer.isSolid(xx, solidY, zz)) { - solidY++; - scan++; - } - int topBound = (scan < maxScan ? solidY - 1 : startY + Math.min(maxScan, 8)) - jitter; - int total = topBound - startY; - for (int j = startY; j <= topBound; j++) { - if (scratch > 0 && total > 0) { - double ratio = (double) (j - startY) / total; - if (ratio > (1.0 - scratch)) { - long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); - double skipChance = (ratio - (1.0 - scratch)) / scratch; - if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { - continue; - } - } - } - placer.set(xx, j, zz, d); - } - } else { - int scan = 0; - int solidY = startY - 1; - while (scan < maxScan && !placer.isSolid(xx, solidY, zz)) { - solidY--; - scan++; - } - int bottomBound = (scan < maxScan ? solidY + 1 : startY - Math.min(maxScan, 8)) + jitter; - int total = startY - bottomBound; - for (int j = startY; j >= bottomBound; j--) { - if (scratch > 0 && total > 0) { - double ratio = (double) (startY - j) / total; - if (ratio > (1.0 - scratch)) { - long sh = ((long) xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L); - double skipChance = (ratio - (1.0 - scratch)) / scratch; - if ((Math.abs(sh) % 1000) / 1000.0 < skipChance * 0.7) { - continue; - } - } - } - placer.set(xx, j, zz, d); - } - } - continue; - } - - int highest = placer.getHighest(xx, zz, self.getLoader(), true); - - if (IrisProceduralBlocks.hasProperty(d, "waterlogged") && ObjectBlockPass.shouldAutoWaterlogBlock(context, state, xx, highest, zz)) { - d = d.withProperty("waterlogged", "true"); - } - - int lowerBound = highest - 1; - if (settings != null) { - lowerBound -= config.getStiltSettings().getOverStilt() - rng.i(0, config.getStiltSettings().getYRand()); - if (settings.getYMax() != 0) - lowerBound -= Math.min(config.getStiltSettings().getYMax() - (lowest + y - highest), 0); - } - - if (eroding) { - double dx = i.getX() - erodeCentroidX; - double dz = i.getZ() - erodeCentroidZ; - double normalizedDist = Math.sqrt(dx * dx + dz * dz) / erodeMaxDist; - normalizedDist = Math.min(normalizedDist, 1.0); - int totalDepth = (lowest + y) - lowerBound; - int erodeDepth = (int) (totalDepth * Math.pow(1.0 - normalizedDist, 1.5)); - lowerBound = (lowest + y) - erodeDepth; - } - - for (int j = lowest + y; j > lowerBound; j--) { - PlatformBlockState fluidState = placer.get(xx, j, zz); - if (B.isFluid(fluidState)) { - break; - } - if (eroding) { - int depth = (lowest + y) - j; - int totalDepth = (lowest + y) - lowerBound; - double depthRatio = totalDepth > 0 ? (double) depth / totalDepth : 0; - if (depthRatio > 0.4) { - long hash = ((long) (xx * 341873128712L) ^ ((long) j * 132897987541L) ^ ((long) zz * 735791245321L)); - double skipChance = (depthRatio - 0.4) / 0.6; - if ((Math.abs(hash) % 1000) / 1000.0 < skipChance * 0.7) { - continue; - } - } - } - - if (B.isVineBlock(d)) { - d = ObjectBlockPass.attachVineFaces(placer, d, xx, j, zz); - } - placer.set(xx, j, zz, d); - } - - } - } finally { - self.readLock.unlock(); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java deleted file mode 100644 index 1bfaf8e91..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleSurfaceSupport.java +++ /dev/null @@ -1,67 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; -import art.arcane.iris.spi.IrisLogging; -import java.util.concurrent.ConcurrentHashMap; - -/** Carving and surface support rules, including the bedrock diagnostic. */ -final class PlacementModuleSurfaceSupport implements PlacementModule { - static final PlacementLifecycleDependency CHECK = new PlacementLifecycleDependency("validate.surface"); - private static final long IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS = 5000L; - private static final ConcurrentHashMap IMPLAUSIBLE_BEDROCK_WARNS = new ConcurrentHashMap<>(); - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(CHECK, PlacementStage.VALIDATE, (context, state, ignored) -> { - IrisObjectPlacement config = state.config; - boolean rawStructurePiece = config.getMode() == ObjectPlaceMode.STRUCTURE_PIECE; - if (context.yv < 0 && !config.isForcePlace() && !config.isFromBottom() - && config.getMode() != ObjectPlaceMode.FLOATING && !rawStructurePiece - && config.getCarvingSupport().supportsSurface() && state.placer.getEngine() != null - && state.placer.getEngine().getDimension().isBedrock() && state.y <= 1) { - warnImplausibleBedrockPlacement(context.self, state.placer, config, context.x, state.y, context.z); - state.reject("bedrock-anchor"); - return; - } - boolean surfaceAnchored = context.yv < 0 ? config.getCarvingSupport().supportsSurface() - : config.getCarvingSupport() == CarvingMode.SURFACE_ONLY; - if (surfaceAnchored && !config.isForcePlace() && !config.isFromBottom() - && config.getMode() != ObjectPlaceMode.FLOATING && !rawStructurePiece - && !config.isUnderwater() && !config.isOnwater() && config.isRequireSurfaceSupport() - && IrisSurfaceSupport.isUnsupported(context.placer, context.self.getLoader(), context.x, context.z, - config.getTranslate(), config.getRotation(), state.spinX, state.spinY, state.spinZ, - context.self.getSurfaceSupportOffsets(), config.getSurfaceSupportBuffer(), config.getSurfaceSupportDepth())) { - state.reject("surface-support"); - } - }, PlacementModuleAnchor.POSITIONED); - } - - static boolean rejectsAnchor(PlacementContext context, PlacementState state, int x, int y, int z) { - return switch (state.config.getCarvingSupport()) { - case SURFACE_ONLY -> state.placer.isCarved(x, y, z); - case CARVING_ONLY -> !(state.placer.isCarved(x, y, z) || state.placer.isCarved(x, y - 1, z) - || state.placer.isCarved(x, y - 2, z) || state.placer.isCarved(x, y - 3, z)); - case ANYWHERE -> false; - }; - } - - private static void warnImplausibleBedrockPlacement(IrisObject self, IObjectPlacer placer, IrisObjectPlacement config, int x, int y, int z) { - String key = self.getLoadKey(); - String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); - long now = System.currentTimeMillis(); - Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); - if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { - return; - } - IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); - IrisLogging.warn("Implausible object placement rejected: " - + (key == null ? "" : key) - + " resolved anchorY=" + y + " at (" + x + "," + z + ") mode=" + config.getMode() - + " carving=" + config.getCarvingSupport() - + ". Surface-anchored placement should never land on the bedrock row. " - + "Height sampling returned a bogus value — not configured for floor placement " - + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); - } - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java deleted file mode 100644 index 564cc2fe9..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModuleVacuum.java +++ /dev/null @@ -1,90 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.noise.SimplexNoise; - -/** Collects written object bounds, then bends terrain to meet them. Installed for vacuum modes. */ -final class PlacementModuleVacuum implements PlacementModule { - static final PlacementLifecycleDependency COLLECT = new PlacementLifecycleDependency("vacuum.collect"); - static final PlacementLifecycleDependency FINISH = new PlacementLifecycleDependency("vacuum.finish"); - private static final long VACUUM_WAVE_SEED = 7392113L; - - @Override - public void install(PlacementLifecycleBuilder lifecycle) { - lifecycle.add(COLLECT, PlacementStage.BLOCK_WRITTEN, (context, state, block) -> { - state.vacuumLowest = Math.min(state.vacuumLowest, block.y()); - state.vacuumHighest = Math.max(state.vacuumHighest, block.y()); - }); - lifecycle.add(FINISH, PlacementStage.AFTER_BLOCKS, (context, state, ignored) -> { - if (state.vacuumLowest == Integer.MAX_VALUE || state.placer.getEngine() == null) { - return; - } - vacuumTerrain(context.self, state.placer, state.config, context.x, context.z, - state.bounds.minX(), state.bounds.maxX(), state.bounds.minZ(), state.bounds.maxZ(), - state.vacuumLowest, state.vacuumHighest); - }, COLLECT, PlacementModuleBlocks.COMPLETE); - } - - private static void vacuumTerrain(IrisObject self, IObjectPlacer placer, IrisObjectPlacement config, int centerX, int centerZ, int lowX, int highX, int lowZ, int highZ, int baseY, int topY) { - ObjectPlaceMode mode = config.getMode(); - IrisVacuumSettings settings = config.getVacuumSettings(); - int radius = IrisObjectVacuum.resolveRadius(mode, settings); - int step = IrisObjectVacuum.resolveStep(mode); - double falloff = IrisObjectVacuum.resolveFalloff(settings); - int jitter = settings != null ? Math.max(0, settings.getOrganicJitter()) : 4; - boolean organicEdge = mode == ObjectPlaceMode.VACUUM_ORGANIC; - boolean wavyEdge = mode == ObjectPlaceMode.VACUUM_WAVY; - double waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); - double waveScale = IrisObjectVacuum.resolveWaveScale(settings); - SimplexNoise waveNoise = (wavyEdge && waveAmplitude > 0) ? new SimplexNoise(VACUUM_WAVE_SEED) : null; - int meetY = baseY - 1; - - IrisComplex complex = placer.getEngine().getComplex(); - int worldMin = placer.getEngine().getMinHeight(); - int worldMax = worldMin + placer.getEngine().getHeight() - 1; - - for (int dx = lowX - radius; dx <= highX + radius; dx += step) { - for (int dz = lowZ - radius; dz <= highZ + radius; dz += step) { - int cx = centerX + dx; - int cz = centerZ + dz; - double effRadius = radius; - if (organicEdge && jitter > 0) { - long h = ((long) cx * 341873128712L) ^ ((long) cz * 132897987541L); - double n = ((Math.abs(h) % 1000) / 1000.0) - 0.5; - effRadius = Math.max(1.0, radius + (n * 2.0 * jitter)); - } - int origY = placer.getHighest(cx, cz, self.getLoader(), true); - int targetY = IrisObjectVacuum.columnTargetY(dx, dz, lowX, highX, lowZ, highZ, effRadius, falloff, origY, meetY); - if (waveNoise != null) { - int outX = IrisObjectVacuum.outset(dx, lowX, highX); - int outZ = IrisObjectVacuum.outset(dz, lowZ, highZ); - double waveDistance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); - double sample = waveNoise.noiseSigned(cx * waveScale, cz * waveScale); - targetY += IrisObjectVacuum.waveOffset(waveDistance, effRadius, sample, waveAmplitude); - } - if (targetY == origY) { - continue; - } - targetY = Math.max(worldMin + 1, Math.min(worldMax, targetY)); - if (targetY > origY) { - PlatformBlockState fill = complex != null ? complex.getRockStream().get(cx, cz) : null; - if (B.isAir(fill)) { - fill = IrisObject.States.STONE; - } - for (int yy = origY + 1; yy <= targetY; yy++) { - placer.set(cx, yy, cz, fill); - } - } else if (targetY < origY) { - boolean inside = IrisObjectVacuum.outset(dx, lowX, highX) == 0 && IrisObjectVacuum.outset(dz, lowZ, highZ) == 0; - int carveFloor = IrisObjectVacuum.carveFloorY(targetY, topY, inside); - for (int yy = origY; yy >= carveFloor; yy--) { - placer.set(cx, yy, cz, IrisObject.States.AIR); - } - } - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java new file mode 100644 index 000000000..7ca2ab130 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java @@ -0,0 +1,36 @@ +/* + * 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 com.volmit.IrisModule; + +import java.util.List; + +/** Iris's built-in object placement, as the IrisApi modules every pack's placement graph starts from. */ +public final class PlacementModules { + static final String VERSION = "built-in"; + + private PlacementModules() { + } + + public static List all() { + return List.of(new PrepareModule(), new AnchorModule(), new ValidateModule(), new BoreModule(), + new BlocksModule(), new StiltModule(), new VacuumModule(), new SnowModule()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java deleted file mode 100644 index 342918a9b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementStage.java +++ /dev/null @@ -1,38 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import java.util.List; - -/** - * Whole-placement phases surround a nested block pass. TRANSFORM_BLOCK runs after rotation and - * before translation; COLLECT_BLOCK runs before edits; BLOCK_WRITTEN runs only for successful - * object writes. Block prerequisites refer to the current block. AFTER_BLOCKS waits for the - * entire block pass, including markers. All whole-placement validation precedes world writes. - */ -public final class PlacementStage { - public static final PlacementStage PREPARE = new PlacementStage<>("prepare", 0); - public static final PlacementStage HEIGHT = new PlacementStage<>("height", 1); - public static final PlacementStage VALIDATE = new PlacementStage<>("validate", 2); - public static final PlacementStage BEFORE_BLOCKS = new PlacementStage<>("before-blocks", 3); - public static final PlacementStage TRANSFORM_BLOCK = new PlacementStage<>("transform-block", 4); - public static final PlacementStage COLLECT_BLOCK = new PlacementStage<>("collect-block", 5); - public static final PlacementStage BLOCK_WRITTEN = new PlacementStage<>("block-written", 6); - // BLOCKS denotes completion of the whole pass, so later steps can depend on all block work. - public static final PlacementStage BLOCKS = new PlacementStage<>("blocks", 7); - public static final PlacementStage AFTER_BLOCKS = new PlacementStage<>("after-blocks", 8); - static final List> ALL = List.of(PREPARE, HEIGHT, VALIDATE, BEFORE_BLOCKS, - TRANSFORM_BLOCK, COLLECT_BLOCK, BLOCK_WRITTEN, BLOCKS, AFTER_BLOCKS); - static final List> BEFORE_PASS = List.of(PREPARE, HEIGHT, VALIDATE, BEFORE_BLOCKS); - - private final String name; - final int order; - - private PlacementStage(String name, int order) { - this.name = name; - this.order = order; - } - - @Override - public String toString() { - return name; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java deleted file mode 100644 index c5def6945..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementState.java +++ /dev/null @@ -1,67 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.placement.PlacementContext.TransformedBounds; -import art.arcane.iris.engine.object.placement.PlacementContext.WorldBounds; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.math.Position2; -import lombok.AccessLevel; -import lombok.Getter; -import lombok.Setter; - -import java.util.Objects; - -/** Results and accumulators owned by one placement, never by a shared module or plan. */ -@Getter -@Setter -public final class PlacementState { - IrisObjectPlacement config; - IObjectPlacer placer; - ObjectSpinKernel spin; - int spinX; - int spinY; - int spinZ; - IrisBlockVector translateOffset; - int rty; - int ty; - int yrand; - int warpMargin; - int y; - TransformedBounds bounds; - WorldBounds worldBounds; - int stiltLowest = Integer.MAX_VALUE; - int stiltHighest = Integer.MIN_VALUE; - int vacuumLowest = Integer.MAX_VALUE; - int vacuumHighest = Integer.MIN_VALUE; - KMap snowHeights; - - @Setter(AccessLevel.NONE) - private String rejection; - - PlacementState(PlacementContext context) { - this(-1, null); - config = context.config; - placer = context.placer; - } - - PlacementState(int y, TransformedBounds bounds) { - this.y = y; - this.bounds = bounds; - } - - /** The first rejection is terminal. Each guard decides whether forcePlace exempts its rule. */ - public void reject(String reason) { - Objects.requireNonNull(reason, "Rejection reason"); - if (rejection == null) { - rejection = reason; - } - } - - public boolean isRejected() { - return rejection != null; - } - - public int heightOrRejected() { - return isRejected() ? -1 : y; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java new file mode 100644 index 000000000..49b0b6625 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java @@ -0,0 +1,64 @@ +/* + * 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.core.modules.BlockEntities; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.placement.PlacedBlock; +import com.volmit.placement.PlacementAccess; +import com.volmit.world.BlockPosition; + +import java.util.Optional; + +/** + * A placement stage's buffered world in Iris's block states: reads see the placement's earlier writes, + * writes wait for the placement to commit. + */ +final class PlacementWorld { + private final PlacementAccess access; + private final PlatformBlockStates states; + + PlacementWorld(PlacementAccess access, PlatformBlockStates states) { + this.access = access; + this.states = states; + } + + PlatformBlockState get(int x, int y, int z) { + return states.toPlatform(access.get(x, y, z)); + } + + boolean isSolid(int x, int y, int z) { + return B.isSolid(get(x, y, z)); + } + + PlacedBlock set(int x, int y, int z, PlatformBlockState state) { + return set(x, y, z, state, null); + } + + /** {@code tile} may be null for a block without tile data. */ + PlacedBlock set(int x, int y, int z, PlatformBlockState state, TileData tile) { + PlacedBlock block = new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), + Optional.ofNullable(tile).map(BlockEntities::of)); + access.set(block); + return block; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java new file mode 100644 index 000000000..f4b2c725f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -0,0 +1,176 @@ +/* + * 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.prepare.PrepareStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; +import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.util.project.stream.ProceduralStream; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:prepare}: checks the slope, turns the object downhill when asked, and chooses the + * placement's rotation, translation and random height offset. + */ +public final class PrepareModule implements IrisModule { + private static final int SPIN_DIVISOR = 1000; + private static final double NORTH = 0; + private static final double EAST = 90; + private static final double SOUTH = 180; + private static final double WEST = 270; + private static final double QUARTER_TURN = 90; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:prepare", "Placement preparation", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(PrepareStages.SLOPE).produce(PrepareModule::slope); + graph.define(PrepareStages.TRANSFORMS) + .requires(PrepareStages.SLOPE) + .produce(PrepareModule::transforms); + } + + private static IrisObjectPlacement slope(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + IrisObjectPlacement config = placement.config(); + boolean checksSlope = !config.isForcePlace() && !config.getSlopeCondition().isDefault(); + if (!checksSlope && !config.isRotateTowardsSlope()) { + return config; + } + Engine engine = placement.placer().getEngine(); + if (engine == null) { + throw new IllegalStateException("Object placement requires an active Iris engine for slope settings."); + } + if (checksSlope && !config.getSlopeCondition().isValid(engine.getComplex().getSlopeStream().get(placement.x(), placement.z()))) { + context.reject("slope"); + return config; + } + return config.isRotateTowardsSlope() ? turnedDownhill(placement.object(), config, engine, placement.x(), placement.z()) : config; + } + + /** A copy of {@code config} whose Y rotation faces the lowest side of the rectangle around the object. */ + private static IrisObjectPlacement turnedDownhill(IrisObject object, IrisObjectPlacement config, Engine engine, int x, int z) { + ProceduralStream heights = engine.getComplex().getHeightStream(); + double north = heights.get(x, z + ((float) object.d) / 2); + double east = heights.get(x + ((float) object.w) / 2, z); + double south = heights.get(x, z - ((float) object.d) / 2); + double west = heights.get(x - ((float) object.w) / 2, z); + double lowest = Math.min(Math.min(north, east), Math.min(south, west)); + double downhill = lowest == north ? NORTH : lowest == east ? EAST : lowest == south ? SOUTH : WEST; + + IrisObjectRotation requested = config.getRotation(); + double turn = requested.getYAxis().getMin() + downhill; + IrisObjectRotation rotation = new IrisObjectRotation(); + rotation.setXAxis(requested.getXAxis()); + rotation.setZAxis(requested.getZAxis()); + if (turn == 0) { + rotation.setYAxis(new IrisAxisRotationClamp(false, false, 0, 0, QUARTER_TURN)); + rotation.setEnabled(requested.canRotateX() || requested.canRotateZ()); + } else { + rotation.setYAxis(new IrisAxisRotationClamp(true, false, turn, turn, QUARTER_TURN)); + rotation.setEnabled(true); + } + IrisObjectPlacement turned = config.toPlacement(config.getPlace().toArray(new String[0])); + turned.setRotation(rotation); + return turned; + } + + private static PreparedPlacement transforms(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + IrisObjectPlacement config = context.output(PrepareStages.SLOPE); + IrisObject object = placement.object(); + RNG rng = new RNG(context.random().nextLong()); + IObjectPlacer terrain = config.getHeightmap() == null ? placement.placer() + : new HeightmapObjectPlacer(rng, placement.x(), placement.requestedY(), placement.z(), config, placement.placer()); + int spinX = rng.imax() / SPIN_DIVISOR; + int spinY = rng.imax() / SPIN_DIVISOR; + int spinZ = rng.imax() / SPIN_DIVISOR; + IrisObjectRotation rotation = config.getRotation(); + IrisObjectTranslate translate = config.getTranslate(); + int centerY = object.getCenter().getBlockY(); + int rotatedCenterY = rotation.rotate(new IrisBlockVector(0, centerY, 0), spinX, spinY, spinZ).getBlockY(); + int translatedCenterY = translate.translate(new IrisBlockVector(0, centerY, 0), rotation, spinX, spinY, spinZ).getBlockY(); + ObjectSpinKernel spin = new ObjectSpinKernel(rotation, spinX, spinY, spinZ); + IrisBlockVector translation = translate.canTranslate() + ? rotation.rotate(new IrisBlockVector(translate.getX(), translate.getY(), translate.getZ()), spinX, spinY, spinZ) + : null; + int randomY = randomHeightOffset(translate.getYRandom(), rng); + int warpMargin = config.getWarp().isFlat() ? 0 : (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D); + TransformedBounds bounds = transformedBounds(object, spin, translation, config.getMode() == ObjectPlaceMode.CEILING_HANG, warpMargin); + CNG surfaceWarp = config.getWarp().isFlat() ? null : config.getSurfaceWarp(rng, object.getLoader()); + return new PreparedPlacement(config, terrain, spin, spinX, spinY, spinZ, translation, rotatedCenterY, + translatedCenterY, randomY, warpMargin, bounds, surfaceWarp); + } + + /** Within {@code range} of zero, on the side its sign gives. */ + private static int randomHeightOffset(int range, RNG rng) { + if (range > 0) { + return rng.i(0, range); + } + return range < 0 ? rng.i(range, 0) : 0; + } + + private static TransformedBounds transformedBounds(IrisObject object, ObjectSpinKernel spin, IrisBlockVector translation, + boolean ceilingHang, int margin) { + int[] sourceX = {-object.getCenter().getBlockX(), object.getW() - object.getCenter().getBlockX() - 1}; + int[] sourceY = {-object.getCenter().getBlockY(), object.getH() - object.getCenter().getBlockY() - 1}; + int[] sourceZ = {-object.getCenter().getBlockZ(), object.getD() - object.getCenter().getBlockZ() - 1}; + int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; + int minY = Integer.MAX_VALUE, maxY = Integer.MIN_VALUE; + int minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE; + for (int x : sourceX) { + for (int y : sourceY) { + for (int z : sourceZ) { + IrisBlockVector corner = new IrisBlockVector(x, y, z); + spin.rotate(corner); + if (ceilingHang) { + corner.setY(-corner.getBlockY()); + } + if (translation != null) { + corner.add(translation); + } + int cornerX = (int) Math.round(corner.getX()); + int cornerY = (int) Math.round(corner.getY()); + int cornerZ = (int) Math.round(corner.getZ()); + minX = Math.min(minX, cornerX); + maxX = Math.max(maxX, cornerX); + minY = Math.min(minY, cornerY); + maxY = Math.max(maxY, cornerY); + minZ = Math.min(minZ, cornerZ); + maxZ = Math.max(maxZ, cornerZ); + } + } + } + return new TransformedBounds(minX - margin, maxX + margin, minY, maxY, minZ - margin, maxZ + margin); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java new file mode 100644 index 000000000..3aeed4175 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java @@ -0,0 +1,146 @@ +/* + * 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.spi.PlatformBlockState; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.project.noise.CNG; +import com.volmit.world.BlockPosition; + +/** + * What one placement chose before it is anchored: the settings it uses, the placer that answers its + * terrain questions, its random rotation and height offsets, and the bounds of the transformed object + * around its anchor. Object blocks are transformed by rotating them, flipping them for a ceiling hang and + * translating them. + */ +public final class PreparedPlacement { + private final IrisObjectPlacement config; + private final IObjectPlacer terrain; + private final ObjectSpinKernel spin; + private final int spinX; + private final int spinY; + private final int spinZ; + private final IrisBlockVector translation; + private final int rotatedCenterY; + private final int translatedCenterY; + private final int randomY; + private final int warpMargin; + private final TransformedBounds bounds; + private final CNG surfaceWarp; + + PreparedPlacement(IrisObjectPlacement config, IObjectPlacer terrain, ObjectSpinKernel spin, int spinX, int spinY, + int spinZ, IrisBlockVector translation, int rotatedCenterY, int translatedCenterY, int randomY, + int warpMargin, TransformedBounds bounds, CNG surfaceWarp) { + this.config = config; + this.terrain = terrain; + this.spin = spin; + this.spinX = spinX; + this.spinY = spinY; + this.spinZ = spinZ; + this.translation = translation; + this.rotatedCenterY = rotatedCenterY; + this.translatedCenterY = translatedCenterY; + this.randomY = randomY; + this.warpMargin = warpMargin; + this.bounds = bounds; + this.surfaceWarp = surfaceWarp; + } + + /** The settings this placement uses, which may differ from the requested ones. */ + public IrisObjectPlacement config() { + return config; + } + + /** Answers height, water and carving questions; a heightmap placement answers heights from its noise. */ + IObjectPlacer terrain() { + return terrain; + } + + ObjectPlaceMode mode() { + return config.getMode(); + } + + int spinX() { + return spinX; + } + + int spinY() { + return spinY; + } + + int spinZ() { + return spinZ; + } + + /** The rotated translation, or null when the placement does not translate. */ + IrisBlockVector translation() { + return translation; + } + + /** The height of the object's center after rotation. */ + int rotatedCenterY() { + return rotatedCenterY; + } + + /** The height of the object's center after translation. */ + int translatedCenterY() { + return translatedCenterY; + } + + /** The random height offset added once the anchor is final. */ + int randomY() { + return randomY; + } + + int warpMargin() { + return warpMargin; + } + + TransformedBounds bounds() { + return bounds; + } + + boolean isWarped() { + return surfaceWarp != null; + } + + /** Moves a world column by the surface warp, along X for {@code x} and along Z for the swapped call. */ + int warpOffset(double along, double y, double across) { + double half = config.getWarp().getMultiplier() / 2D; + return (int) surfaceWarp.fitDouble(-half, half, along, y, across); + } + + /** An object block's offset from the anchor after this placement's transforms. */ + BlockPosition transform(BlockPosition local) { + IrisBlockVector offset = new IrisBlockVector(local.x(), local.y(), local.z()); + spin.rotate(offset); + if (mode() == ObjectPlaceMode.CEILING_HANG) { + offset.setY(-offset.getBlockY()); + } + if (translation != null) { + offset.add(translation); + } + return new BlockPosition((int) Math.round(offset.getX()), (int) Math.round(offset.getY()), (int) Math.round(offset.getZ())); + } + + /** A block state turned with the object, so stairs and logs face the way the object does. */ + PlatformBlockState rotate(PlatformBlockState state) { + return spin.rotate(state); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java new file mode 100644 index 000000000..40dfa641e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -0,0 +1,88 @@ +/* + * 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.blocks.BlocksStages; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.snow.SnowStages; +import art.arcane.iris.builtin.stilt.StiltStages; +import art.arcane.iris.builtin.vacuum.VacuumStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.placement.PlacedBlock; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; +import com.volmit.world.BlockPosition; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Module {@code iris:snow}: a random depth of snow on top of each column of the object, deeper the more + * snow the placement asks for. Only the object's own written blocks carry snow. + */ +public final class SnowModule implements IrisModule { + private static final int LAYERS_PER_UNIT_OF_SNOW = 7; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:snow", "Snow", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(SnowStages.COVER) + .requires(BlocksStages.WRITE, BlocksStages.COMPLETE, PrepareStages.TRANSFORMS) + .softAfter(StiltStages.FILL.ref(), VacuumStages.TERRAIN.ref()) + .run(SnowModule::cover); + } + + private static void cover(PlacementStageContext context) { + double snow = context.output(PrepareStages.TRANSFORMS).config().getSnow(); + WrittenBlocks written = context.output(BlocksStages.WRITE); + if (!(snow > 0) || written.isEmpty()) { + return; + } + PlacementWorld world = new PlacementWorld(context.access(), IrisPlacement.current().states()); + RNG rng = new RNG(context.random().nextLong()); + int maxLayer = IrisObject.States.SNOW_LAYERS.length - 1; + for (BlockPosition top : columnTops(written).values()) { + int layer = rng.i(0, (int) (snow * LAYERS_PER_UNIT_OF_SNOW)); + world.set(top.x(), top.y() + 1, top.z(), IrisObject.States.SNOW_LAYERS[Math.max(Math.min(layer, maxLayer), 0)]); + } + } + + /** The highest written block of each column, columns in the order they were first written. */ + private static Map columnTops(WrittenBlocks written) { + Map tops = new LinkedHashMap<>(); + for (PlacedBlock block : written.blocks()) { + BlockPosition position = block.position(); + tops.merge(columnKey(position), position, (current, next) -> next.y() > current.y() ? next : current); + } + return tops; + } + + private static long columnKey(BlockPosition position) { + return ((long) position.x() << Integer.SIZE) | (position.z() & 0xFFFFFFFFL); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java new file mode 100644 index 000000000..096920cf2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -0,0 +1,269 @@ +/* + * 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.anchor.AnchorStages; +import art.arcane.iris.builtin.blocks.BlocksStages; +import art.arcane.iris.builtin.bore.BoreStages; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.stilt.StiltLayers; +import art.arcane.iris.builtin.stilt.StiltStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.object.ObjectBlock; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; +import com.volmit.world.BlockPosition; + +import java.util.List; +import java.util.Set; + +/** + * Module {@code iris:stilt}: once the object is written, repeats its bottom layer down to the ground, or + * for a ceiling hang its top layer up into the ceiling. Straight stilts reach the surface, eroded ones taper + * toward the edges, organic ones stop at the first solid block with a ragged, broken tip. + */ +public final class StiltModule implements IrisModule { + private static final Set SOIL_MATERIALS = Set.of("minecraft:grass_block", "minecraft:mycelium", + "minecraft:podzol", "minecraft:dirt_path"); + private static final String SOIL_REPLACEMENT = "minecraft:dirt"; + private static final String WATERLOGGED = "waterlogged"; + private static final long HASH_X = 341873128712L; + private static final long HASH_Y = 132897987541L; + private static final long HASH_Z = 735791245321L; + private static final int HASH_BUCKETS = 1000; + private static final double SKIP_CHANCE_SCALE = 0.7; + private static final int DEFAULT_ORGANIC_MAX_SCAN = 48; + private static final int DEFAULT_ORGANIC_JITTER = 3; + private static final double DEFAULT_ORGANIC_SCRATCH = 0.55; + private static final int UNANCHORED_ORGANIC_DEPTH = 8; + private static final double ERODE_SOLID_FRACTION = 0.4; + private static final double ERODE_TAPER_EXPONENT = 1.5; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:stilt", "Stilts", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(StiltStages.LAYERS) + .requires(PrepareStages.TRANSFORMS) + // Ordered after boring only so it shares the block pass that writes the object. + .softAfter(BoreStages.CLEAR.ref()) + .accumulate(StiltLayers::new, StiltModule::collectLayer); + graph.define(StiltStages.FILL) + .requires(StiltStages.LAYERS, AnchorStages.FINAL, BlocksStages.COMPLETE) + .run(StiltModule::fill); + } + + private static void collectLayer(BlockStageContext context, StiltLayers layers) { + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + if (prepared.mode().stilt() == StiltShape.NONE) { + return; + } + ObjectBlock block = context.block(); + if (!IrisObjectShaping.shouldStilt(IrisPlacement.current().states().toPlatform(block.state()))) { + return; + } + layers.include(new ObjectBlock(prepared.transform(block.position()), block.state(), block.blockEntity())); + } + + private static void fill(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + StiltShape shape = prepared.mode().stilt(); + StiltLayers layers = context.output(StiltStages.LAYERS); + if (shape == StiltShape.NONE || layers.isEmpty()) { + return; + } + StiltColumns columns = new StiltColumns(context, prepared, layers); + List layer = shape == StiltShape.CEILING ? layers.top() : layers.bottom(); + for (ObjectBlock block : layer) { + columns.grow(block); + } + } + + /** One placement's stilt, grown column by column under (or above) the blocks of its repeated layer. */ + private static final class StiltColumns { + private final IrisPlacement placement; + private final PreparedPlacement prepared; + private final IrisObjectPlacement config; + private final IrisStiltSettings settings; + private final StiltShape shape; + private final PlacementWorld world; + private final RNG rng; + private final int anchorY; + private final int layerY; + private final ErodeShape erode; + + private StiltColumns(PlacementStageContext context, PreparedPlacement prepared, StiltLayers layers) { + this.placement = IrisPlacement.current(); + this.prepared = prepared; + this.config = prepared.config(); + this.settings = config.getStiltSettings(); + this.shape = prepared.mode().stilt(); + this.world = new PlacementWorld(context.access(), placement.states()); + this.rng = new RNG(context.random().nextLong()); + this.anchorY = context.output(AnchorStages.FINAL).y(); + this.layerY = shape == StiltShape.CEILING ? layers.topY() : layers.bottomY(); + this.erode = shape == StiltShape.ERODE ? ErodeShape.of(layers.bottom()) : null; + } + + private void grow(ObjectBlock block) { + BlockPosition offset = block.position(); + PlatformBlockState state = stiltState(block, offset); + if (state == null || !state.isOccluding()) { + return; + } + int x = placement.x() + offset.x(); + int z = placement.z() + offset.z(); + if (prepared.isWarped()) { + x += prepared.warpOffset(offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z()); + z += prepared.warpOffset(offset.z() + placement.z(), offset.y() + anchorY, offset.x() + placement.x()); + } + switch (shape) { + case ORGANIC -> growOrganic(state, x, z, -1); + case CEILING -> growOrganic(state, x, z, 1); + case STRAIGHT, ERODE -> growToSurface(state, offset, x, z); + case NONE -> { + } + } + } + + /** The block the stilt repeats: the palette's when the settings have one, soil turned to dirt, edited and turned with the object. */ + private PlatformBlockState stiltState(ObjectBlock block, BlockPosition offset) { + PlatformBlockState state = placement.states().toPlatform(block.state()); + if (settings != null && settings.getPalette() != null) { + state = settings.getPalette().get(rng, placement.x(), anchorY, placement.z(), placement.data()); + } else if (SOIL_MATERIALS.contains(IrisObjectShaping.materialKey(state))) { + state = B.getState(SOIL_REPLACEMENT); + } + state = prepared.rotate(state); + if (config.getEdit().isEmpty() || state == null) { + return state; + } + return ObjectEdits.apply(config, state, null, rng, offset.x() + placement.x(), offset.y() + anchorY, + offset.z() + placement.z(), placement.data()).data(); + } + + private void growToSurface(PlatformBlockState state, BlockPosition offset, int x, int z) { + int top = layerY + anchorY; + int highest = prepared.terrain().getHighest(x, z, placement.object().getLoader(), true); + if (IrisProceduralBlocks.hasProperty(state, WATERLOGGED) + && BlocksModule.shouldWaterlog(world, config, placement.requestedY(), x, highest, z)) { + state = state.withProperty(WATERLOGGED, "true"); + } + int lowerBound = highest - 1; + if (settings != null) { + lowerBound -= settings.getOverStilt() - rng.i(0, settings.getYRand()); + if (settings.getYMax() != 0) { + lowerBound -= Math.min(settings.getYMax() - (top - highest), 0); + } + } + if (erode != null) { + lowerBound = top - erode.depth(offset, top - lowerBound); + } + for (int y = top; y > lowerBound; y--) { + if (B.isFluid(world.get(x, y, z))) { + return; + } + if (erode != null && erode.breaksAt(x, y, z, top - y, top - lowerBound)) { + continue; + } + if (B.isVineBlock(state)) { + state = BlocksModule.attachVineFaces(world, state, x, y, z); + } + world.set(x, y, z, state); + } + } + + /** Grows from the layer toward the first solid block in {@code direction}, -1 down or 1 up. */ + private void growOrganic(PlatformBlockState state, int x, int z, int direction) { + int maxScan = settings != null ? Math.max(1, settings.getOrganicMaxScan()) : DEFAULT_ORGANIC_MAX_SCAN; + int jitterMax = settings != null ? Math.max(0, settings.getOrganicJitter()) : DEFAULT_ORGANIC_JITTER; + double scratch = settings != null ? Math.max(0, Math.min(1, settings.getOrganicScratch())) : DEFAULT_ORGANIC_SCRATCH; + long columnHash = ((long) x * HASH_X) ^ ((long) z * HASH_Y); + int jitter = jitterMax > 0 ? (int) (Math.abs(columnHash) % (jitterMax + 1)) : 0; + int start = layerY + anchorY; + int scanned = 0; + int solidY = start + direction; + while (scanned < maxScan && !world.isSolid(x, solidY, z)) { + solidY += direction; + scanned++; + } + int end = (scanned < maxScan ? solidY - direction : start + direction * Math.min(maxScan, UNANCHORED_ORGANIC_DEPTH)) + - direction * jitter; + int length = (end - start) * direction; + for (int step = 0; step <= length; step++) { + int y = start + step * direction; + if (scratch > 0 && length > 0 && isScratched(x, y, z, (double) step / length, scratch)) { + continue; + } + world.set(x, y, z, state); + } + } + + /** Whether the broken tip skips this block: more often the deeper it lies in the scratched fraction. */ + private static boolean isScratched(int x, int y, int z, double depthRatio, double scratch) { + if (depthRatio <= 1.0 - scratch) { + return false; + } + double skipChance = (depthRatio - (1.0 - scratch)) / scratch; + return hashFraction(x, y, z) < skipChance * SKIP_CHANCE_SCALE; + } + } + + /** An eroded stilt: deepest under the layer's centroid, shallower toward its edge, broken up at depth. */ + private record ErodeShape(double centroidX, double centroidZ, double maxDistance) { + static ErodeShape of(List bottom) { + double centroidX = bottom.stream().mapToInt(block -> block.position().x()).average().orElse(0); + double centroidZ = bottom.stream().mapToInt(block -> block.position().z()).average().orElse(0); + double maxDistance = bottom.stream() + .mapToDouble(block -> Math.hypot(block.position().x() - centroidX, block.position().z() - centroidZ)) + .max().orElse(1); + return new ErodeShape(centroidX, centroidZ, Math.max(1, maxDistance)); + } + + int depth(BlockPosition offset, int fullDepth) { + double distance = Math.min(1.0, Math.hypot(offset.x() - centroidX, offset.z() - centroidZ) / maxDistance); + return (int) (fullDepth * Math.pow(1.0 - distance, ERODE_TAPER_EXPONENT)); + } + + boolean breaksAt(int x, int y, int z, int depth, int fullDepth) { + double depthRatio = fullDepth > 0 ? (double) depth / fullDepth : 0; + if (depthRatio <= ERODE_SOLID_FRACTION) { + return false; + } + double skipChance = (depthRatio - ERODE_SOLID_FRACTION) / (1.0 - ERODE_SOLID_FRACTION); + return hashFraction(x, y, z) < skipChance * SKIP_CHANCE_SCALE; + } + } + + private static double hashFraction(int x, int y, int z) { + long hash = ((long) x * HASH_X) ^ ((long) y * HASH_Y) ^ ((long) z * HASH_Z); + return (Math.abs(hash) % HASH_BUCKETS) / (double) HASH_BUCKETS; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java new file mode 100644 index 000000000..121a71cb0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java @@ -0,0 +1,32 @@ +/* + * 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; + +/** What a placement mode grows between the object and the ground or ceiling. */ +enum StiltShape { + NONE, + /** Repeats the bottom layer straight down to the surface. */ + STRAIGHT, + /** Like {@link #STRAIGHT}, tapering toward the edges and broken up at depth. */ + ERODE, + /** Repeats the bottom layer down to the first solid block, each column a little different. */ + ORGANIC, + /** Hangs the flipped object from a ceiling and grows its top layer up into it. */ + CEILING +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java b/src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java new file mode 100644 index 000000000..0b9d659e5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java @@ -0,0 +1,23 @@ +/* + * 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; + +/** The bounds of a transformed object around its anchor, inclusive, widened by the surface warp along X and Z. */ +record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java new file mode 100644 index 000000000..929060a14 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -0,0 +1,173 @@ +/* + * 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.blocks.BlocksStages; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.vacuum.VacuumStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.noise.SimplexNoise; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:vacuum}: bends the terrain around an object of a vacuum mode so it meets the object's + * base, raising columns with rock and carving them down, fading out across the bend's radius. + */ +public final class VacuumModule implements IrisModule { + private static final long WAVE_SEED = 7392113L; + private static final int DEFAULT_ORGANIC_JITTER = 4; + private static final long HASH_X = 341873128712L; + private static final long HASH_Z = 132897987541L; + private static final int HASH_BUCKETS = 1000; + private static final double HALF = 0.5; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:vacuum", "Vacuum", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(VacuumStages.TERRAIN) + .requires(BlocksStages.WRITE, BlocksStages.COMPLETE, PrepareStages.TRANSFORMS) + .reach(IrisObjectVacuum.MAX_RADIUS_BLOCKS) + .run(VacuumModule::bendTerrain); + } + + private static void bendTerrain(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + WrittenBlocks written = context.output(BlocksStages.WRITE); + Engine engine = prepared.terrain().getEngine(); + if (!prepared.mode().isVacuum() || written.isEmpty() || engine == null) { + return; + } + int baseY = written.blocks().stream().mapToInt(block -> block.position().y()).min().orElseThrow(); + int topY = written.blocks().stream().mapToInt(block -> block.position().y()).max().orElseThrow(); + new Bend(context, prepared, engine).apply(baseY, topY); + } + + /** One placement's terrain bend over the columns within its radius of the object's footprint. */ + private static final class Bend { + private final IrisPlacement placement; + private final PreparedPlacement prepared; + private final PlacementWorld world; + private final IrisComplex complex; + private final int radius; + private final int step; + private final double falloff; + private final int jitter; + private final double waveAmplitude; + private final double waveScale; + private final SimplexNoise waves; + private final int worldMin; + private final int worldMax; + + private Bend(PlacementStageContext context, PreparedPlacement prepared, Engine engine) { + ObjectPlaceMode mode = prepared.mode(); + this.placement = IrisPlacement.current(); + this.prepared = prepared; + this.world = new PlacementWorld(context.access(), placement.states()); + this.complex = engine.getComplex(); + IrisVacuumSettings settings = prepared.config().getVacuumSettings(); + this.radius = IrisObjectVacuum.resolveRadius(mode, settings); + this.step = IrisObjectVacuum.resolveStep(mode); + this.falloff = IrisObjectVacuum.resolveFalloff(settings); + this.jitter = settings != null ? Math.max(0, settings.getOrganicJitter()) : DEFAULT_ORGANIC_JITTER; + this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); + this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); + this.waves = mode == ObjectPlaceMode.VACUUM_WAVY && waveAmplitude > 0 ? new SimplexNoise(WAVE_SEED) : null; + this.worldMin = engine.getMinHeight(); + this.worldMax = worldMin + engine.getHeight() - 1; + } + + private void apply(int baseY, int topY) { + TransformedBounds bounds = prepared.bounds(); + for (int dx = bounds.minX() - radius; dx <= bounds.maxX() + radius; dx += step) { + for (int dz = bounds.minZ() - radius; dz <= bounds.maxZ() + radius; dz += step) { + bendColumn(bounds, dx, dz, baseY - 1, topY); + } + } + } + + private void bendColumn(TransformedBounds bounds, int dx, int dz, int meetY, int topY) { + int x = placement.x() + dx; + int z = placement.z() + dz; + double effectiveRadius = effectiveRadius(x, z); + int originalY = prepared.terrain().getHighest(x, z, placement.object().getLoader(), true); + int targetY = IrisObjectVacuum.columnTargetY(dx, dz, bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), + effectiveRadius, falloff, originalY, meetY) + waveOffset(bounds, dx, dz, x, z, effectiveRadius); + if (targetY == originalY) { + return; + } + targetY = Math.max(worldMin + 1, Math.min(worldMax, targetY)); + if (targetY > originalY) { + raise(x, z, originalY, targetY); + } else if (targetY < originalY) { + boolean inside = IrisObjectVacuum.outset(dx, bounds.minX(), bounds.maxX()) == 0 + && IrisObjectVacuum.outset(dz, bounds.minZ(), bounds.maxZ()) == 0; + carve(x, z, originalY, IrisObjectVacuum.carveFloorY(targetY, topY, inside)); + } + } + + /** The radius, perturbed per column for the organic mode. */ + private double effectiveRadius(int x, int z) { + if (prepared.mode() != ObjectPlaceMode.VACUUM_ORGANIC || jitter <= 0) { + return radius; + } + long hash = ((long) x * HASH_X) ^ ((long) z * HASH_Z); + double noise = ((Math.abs(hash) % HASH_BUCKETS) / (double) HASH_BUCKETS) - HALF; + return Math.max(1.0, radius + (noise * 2.0 * jitter)); + } + + private int waveOffset(TransformedBounds bounds, int dx, int dz, int x, int z, double effectiveRadius) { + if (waves == null) { + return 0; + } + int outX = IrisObjectVacuum.outset(dx, bounds.minX(), bounds.maxX()); + int outZ = IrisObjectVacuum.outset(dz, bounds.minZ(), bounds.maxZ()); + double distance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); + return IrisObjectVacuum.waveOffset(distance, effectiveRadius, waves.noiseSigned(x * waveScale, z * waveScale), waveAmplitude); + } + + private void raise(int x, int z, int fromY, int toY) { + PlatformBlockState fill = complex != null ? complex.getRockStream().get(x, z) : null; + if (B.isAir(fill)) { + fill = IrisObject.States.STONE; + } + for (int y = fromY + 1; y <= toY; y++) { + world.set(x, y, z, fill); + } + } + + private void carve(int x, int z, int fromY, int floorY) { + for (int y = fromY; y >= floorY; y--) { + world.set(x, y, z, IrisObject.States.AIR); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java new file mode 100644 index 000000000..5e4f0ef66 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -0,0 +1,254 @@ +/* + * 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.anchor.AnchorStages; +import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.validate.ValidateStages; +import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStructureVolume; +import art.arcane.iris.engine.framework.PlacedObject; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.terrain.carving.CarvingMode; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.object.ObjectBlock; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.StageGraph; +import com.volmit.world.BlockPosition; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Module {@code iris:validate}: the checks that reject a placement before anything is written. Forced + * placements skip all but the native structure check, which only structure pieces skip. + */ +public final class ValidateModule implements IrisModule { + private static final long IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS = 5000L; + private static final int BEDROCK_ROW = 1; + private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + private static final ConcurrentHashMap IMPLAUSIBLE_BEDROCK_WARNS = new ConcurrentHashMap<>(); + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:validate", "Placement checks", PlacementModules.VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(ValidateStages.SURFACE) + .requires(AnchorStages.HEIGHT) + .run(ValidateModule::checkSurface); + graph.define(ValidateStages.LIMITS) + .requires(ValidateStages.SURFACE, AnchorStages.HEIGHT) + .run(ValidateModule::checkLimits); + graph.define(ValidateStages.STRUCTURES) + .requires(ValidateStages.LIMITS, AnchorStages.HEIGHT) + .run(ValidateModule::checkNativeStructures); + graph.define(ValidateStages.COLLISIONS) + .requires(ValidateStages.STRUCTURES, AnchorStages.HEIGHT) + .run(ValidateModule::checkCollisions); + } + + private static void checkSurface(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + if (config.isForcePlace() || config.isFromBottom() || prepared.mode() == ObjectPlaceMode.FLOATING + || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { + return; + } + int y = context.output(AnchorStages.HEIGHT).y(); + boolean sampled = placement.requestedY() < 0; + if (sampled && config.getCarvingSupport().supportsSurface() && isOnBedrock(prepared, y)) { + warnImplausibleBedrockPlacement(placement, config, y); + context.reject("bedrock-anchor"); + return; + } + boolean surfaceAnchored = sampled ? config.getCarvingSupport().supportsSurface() + : config.getCarvingSupport() == CarvingMode.SURFACE_ONLY; + if (surfaceAnchored && !config.isUnderwater() && !config.isOnwater() && config.isRequireSurfaceSupport() + && lacksSurfaceSupport(placement, prepared)) { + context.reject("surface-support"); + } + } + + private static boolean isOnBedrock(PreparedPlacement prepared, int y) { + Engine engine = prepared.terrain().getEngine(); + return engine != null && engine.getDimension().isBedrock() && y <= BEDROCK_ROW; + } + + private static boolean lacksSurfaceSupport(IrisPlacement placement, PreparedPlacement prepared) { + IrisObjectPlacement config = prepared.config(); + IrisObject object = placement.object(); + return IrisSurfaceSupport.isUnsupported(placement.placer(), object.getLoader(), placement.x(), placement.z(), + config.getTranslate(), config.getRotation(), prepared.spinX(), prepared.spinY(), prepared.spinZ(), + object.getSurfaceSupportOffsets(), config.getSurfaceSupportBuffer(), config.getSurfaceSupportDepth()); + } + + private static void checkLimits(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + if (config.isForcePlace() || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { + return; + } + int y = context.output(AnchorStages.HEIGHT).y(); + int rotated = prepared.rotatedCenterY(); + int translated = prepared.translatedCenterY(); + if (placement.requestedY() < 0 && prepared.mode() != ObjectPlaceMode.FLOATING && !config.isUnderwater() + && !config.isOnwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) { + context.reject("underwater-anchor"); + } else if (placement.cave() != null + && Math.max(0, placement.object().h + prepared.randomY() + translated) + 1 >= placement.cave().getHeight()) { + context.reject("cave-clearance"); + } else if (config.isUnderwater() && y + rotated + translated >= prepared.terrain().getFluidHeight()) { + context.reject("fluid-height"); + } else if (!config.getClamp().canPlace(y + rotated + translated, y - rotated + translated)) { + context.reject("height-clamp"); + } + } + + private static void checkNativeStructures(PlacementStageContext context) { + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + if (prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { + return; + } + int y = context.output(AnchorStages.HEIGHT).y() + prepared.randomY(); + if (meetsNativeStructure(context, IrisPlacement.current(), prepared, y)) { + context.reject("native-structure"); + } + } + + private static boolean meetsNativeStructure(PlacementStageContext context, IrisPlacement placement, + PreparedPlacement prepared, int y) { + Engine engine = prepared.terrain().getEngine(); + if (engine == null) { + return false; + } + int x = placement.x(); + int z = placement.z(); + int margin = nativeStructureMargin(placement.object(), prepared); + KList volumes = engine.getNativeStructureVolumes(x - margin, z - margin, x + margin, z + margin); + if (volumes == null || volumes.isEmpty()) { + return false; + } + boolean painted = WorldVolume.isPainted(placement, prepared); + int worldY = y + engine.getMinHeight(); + int envelopeMinY = painted ? Integer.MIN_VALUE : worldY - margin; + int envelopeMaxY = painted ? Integer.MAX_VALUE : worldY + margin; + boolean envelopeMeetsPiece = volumes.stream() + .anyMatch(volume -> volume.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)); + if (!envelopeMeetsPiece) { + return false; + } + for (ObjectBlock block : context.request().object().blocks()) { + if (isAir(block.state())) { + continue; + } + BlockPosition offset = prepared.transform(block.position()); + int blockX = x + offset.x(); + int blockZ = z + offset.z(); + int blockY = painted + ? offset.y() + Math.floorDiv(placement.object().h, 2) + + prepared.terrain().getHighest(blockX, blockZ, placement.object().getLoader(), prepared.config().isUnderwater()) + : y + offset.y(); + int worldBlockY = blockY + engine.getMinHeight(); + for (NativeStructureVolume volume : volumes) { + if (volume.containsWithin(blockX, worldBlockY, blockZ, prepared.warpMargin())) { + return true; + } + } + } + return false; + } + + /** How far around the anchor any block of the transformed object can reach. */ + private static int nativeStructureMargin(IrisObject object, PreparedPlacement prepared) { + int margin = (Math.max(object.getW(), Math.max(object.getH(), object.getD())) / 2) + 1 + prepared.warpMargin(); + if (prepared.translation() == null) { + return margin; + } + return margin + Math.max(Math.abs(prepared.translation().getBlockX()), + Math.max(Math.abs(prepared.translation().getBlockY()), Math.abs(prepared.translation().getBlockZ()))); + } + + private static boolean isAir(BlockState state) { + return AIR_MATERIALS.contains(state.material().toString()); + } + + private static void checkCollisions(PlacementStageContext context) { + IrisPlacement placement = IrisPlacement.current(); + PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + IrisObjectPlacement config = prepared.config(); + if (config.isForcePlace() || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE + || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { + return; + } + Engine engine = placement.data().getEngine(); + if (engine == null) { + throw new IllegalStateException("Object placement requires active Iris data for collision settings."); + } + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(AnchorStages.HEIGHT).y() + prepared.randomY()); + if (collidesWithForbiddenObject(engine, config, volume)) { + context.reject("object-collision"); + } + } + + private static boolean collidesWithForbiddenObject(Engine engine, IrisObjectPlacement config, WorldVolume volume) { + for (int x = volume.minX(); x <= volume.maxX(); x++) { + for (int y = volume.minY(); y <= volume.maxY(); y++) { + for (int z = volume.minZ(); z <= volume.maxZ(); z++) { + PlacedObject placed = engine.getObjectPlacement(x, y, z); + if (placed == null || placed.getObject() == null) { + continue; + } + String key = placed.getObject().getLoadKey(); + if (key != null && config.getForbiddenCollisions().contains(key) && !config.getAllowedCollisions().contains(key)) { + return true; + } + } + } + } + return false; + } + + private static void warnImplausibleBedrockPlacement(IrisPlacement placement, IrisObjectPlacement config, int y) { + String key = placement.object().getLoadKey(); + String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); + long now = System.currentTimeMillis(); + Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); + if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { + return; + } + IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); + IrisLogging.warn("Implausible object placement rejected: " + + (key == null ? "" : key) + + " resolved anchorY=" + y + " at (" + placement.x() + "," + placement.z() + ") mode=" + config.getMode() + + " carving=" + config.getCarvingSupport() + + ". Surface-anchored placement should never land on the bedrock row. " + + "Height sampling returned a bogus value — not configured for floor placement " + + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java new file mode 100644 index 000000000..fca0d968c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java @@ -0,0 +1,55 @@ +/* + * 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.core.modules.IrisPlacement; + +/** + * The world blocks a placed object occupies, inclusive: its transformed bounds around the anchor. A painted + * object follows the surface column by column, so its volume spans every surface height under it. + */ +record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { + static WorldVolume of(IrisPlacement placement, PreparedPlacement prepared, int anchorY) { + TransformedBounds bounds = prepared.bounds(); + int minX = placement.x() + bounds.minX(); + int maxX = placement.x() + bounds.maxX(); + int minZ = placement.z() + bounds.minZ(); + int maxZ = placement.z() + bounds.maxZ(); + if (!isPainted(placement, prepared)) { + return new WorldVolume(minX, maxX, anchorY + bounds.minY(), anchorY + bounds.maxY(), minZ, maxZ); + } + int lowestSurface = Integer.MAX_VALUE; + int highestSurface = Integer.MIN_VALUE; + for (int x = minX; x <= maxX; x++) { + for (int z = minZ; z <= maxZ; z++) { + int surface = prepared.terrain().getHighest(x, z, placement.object().getLoader(), prepared.config().isUnderwater()); + lowestSurface = Math.min(lowestSurface, surface); + highestSurface = Math.max(highestSurface, surface); + } + } + int paintOffset = Math.floorDiv(placement.object().h, 2); + return new WorldVolume(minX, maxX, lowestSurface + bounds.minY() + paintOffset, + highestSurface + bounds.maxY() + paintOffset, minZ, maxZ); + } + + /** Whether each block of the placement follows the surface of its own column. */ + static boolean isPainted(IrisPlacement placement, PreparedPlacement prepared) { + return placement.requestedY() < 0 && prepared.mode() == ObjectPlaceMode.PAINT; + } +} 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 index a4c6102b4..cb6a2e1e7 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -21,10 +21,11 @@ package art.arcane.iris.engine.object.prefab; 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.placement.IrisObjectPlacementRunner; 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.iris.engine.data.cache.AtomicCache; import art.arcane.iris.platform.bukkit.BukkitBlockState; @@ -40,6 +41,7 @@ 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; @@ -64,7 +66,7 @@ import java.util.function.BiConsumer; *

* 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 IrisObjectPlacementRunner} + * {@link IrisObjectTransforms} (rotation, scaling, interpolated upscaling) and {@link ModuleObjectPlacement} * (world placement). */ @Accessors(chain = true) @@ -87,6 +89,7 @@ public class IrisObject extends IrisRegistrant { 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 @@ -220,8 +223,7 @@ public class IrisObject extends IrisRegistrant { blocks.put(v, block); } - surfaceSupportOffsets.reset(); - floatingFootprint.reset(); + forgetDerivedShapes(); } public void setUnsignedTile(int x, int y, int z, TileData tile) { @@ -232,6 +234,8 @@ public class IrisObject extends IrisRegistrant { } else { states.put(v, tile); } + + forgetDerivedShapes(); } public void setUnsigned(int x, int y, int z, Block block, boolean legacy) { @@ -250,8 +254,7 @@ public class IrisObject extends IrisRegistrant { } } - surfaceSupportOffsets.reset(); - floatingFootprint.reset(); + forgetDerivedShapes(); } public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisData rdata) { @@ -270,8 +273,21 @@ public class IrisObject extends IrisRegistrant { 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 new IrisObjectPlacementRunner(this).place(x, yv, z, oplacer, config, rng, listener, c, 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() { 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 index 338fcc6c1..1cda4d051 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java @@ -93,8 +93,7 @@ public final class IrisObjectIO { } static void readLegacy(IrisObject self, InputStream in) throws IOException { - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); + self.forgetDerivedShapes(); DataInputStream din = new DataInputStream(in); self.w = din.readInt(); self.h = din.readInt(); @@ -126,8 +125,7 @@ public final class IrisObjectIO { } static void read(IrisObject self, InputStream in) throws Throwable { - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); + self.forgetDerivedShapes(); DataInputStream din = new DataInputStream(in); self.w = din.readInt(); self.h = din.readInt(); 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 index 822a54801..f348832ad 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java @@ -175,6 +175,7 @@ public final class IrisObjectShaping { try { if (!self.smartBored) { bore.forEach((v, s) -> self.blocks.computeIfAbsent(v, (vv) -> s)); + self.forgetDerivedShapes(); self.smartBored = true; } } finally { @@ -259,8 +260,7 @@ public final class IrisObjectShaping { self.shrinkOffset = offset; self.blocks = b; self.states = s; - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); + self.forgetDerivedShapes(); } public static void clean(IrisObject self) { @@ -272,8 +272,7 @@ public final class IrisObjectShaping { self.blocks = d; self.states = dx; - self.surfaceSupportOffsets.reset(); - self.floatingFootprint.reset(); + self.forgetDerivedShapes(); } public static boolean shouldStilt(PlatformBlockState state) { From 90f5181a8844ecb1abc2e0389e0c91874ecbdafb Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 08:50:51 +0200 Subject: [PATCH 004/139] Port perfection to an IrisApi chunk module - iris:perfection/surface does what IrisPerfectionModifier did on overworld chunks: hide ores when the dimension asks, then remove decorations whose block below cannot hold them until none is left. - It runs in the pack's chunk graph on Iris's block hunk, after the world mode's stages, so it now follows the custom block stage instead of preceding it. ModeOverworld no longer registers it and IrisPerfectionModifier is deleted. - The passes run on the generating thread instead of fanning columns out to the burst executor. --- .../builtin/perfection/PerfectionStages.java | 31 +++ .../iris/engine/mode/ModeOverworld.java | 4 - .../modifier/IrisPerfectionModifier.java | 200 ------------------ .../engine/modifier/PerfectionModule.java | 187 ++++++++++++++++ 4 files changed, 218 insertions(+), 204 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java delete mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java diff --git a/src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java b/src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java new file mode 100644 index 000000000..d20a500f3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.perfection; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:perfection}: the last touches on an overworld chunk's blocks. */ +public final class PerfectionStages { + /** Hides ores when the dimension asks, then removes decorations that nothing holds up. */ + public static final ChunkStage SURFACE = Stage.chunk("iris:perfection/surface"); + + private PerfectionStages() { + } +} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java b/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java index a2f1e161c..3534e2f78 100644 --- a/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java +++ b/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java @@ -30,7 +30,6 @@ import art.arcane.iris.engine.modifier.IrisCarveModifier; import art.arcane.iris.engine.modifier.IrisCustomModifier; import art.arcane.iris.engine.modifier.IrisDepositModifier; import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier; -import art.arcane.iris.engine.modifier.IrisPerfectionModifier; import art.arcane.iris.engine.modifier.IrisPostModifier; import art.arcane.iris.spi.IrisLogging; @@ -49,7 +48,6 @@ public class ModeOverworld extends IrisEngineMode implements EngineMode { IrisCarveModifier cave = new IrisCarveModifier(getEngine()); IrisPostModifier post = new IrisPostModifier(getEngine()); IrisDepositModifier deposit = new IrisDepositModifier(getEngine()); - IrisPerfectionModifier perfection = new IrisPerfectionModifier(getEngine()); IrisCustomModifier custom = new IrisCustomModifier(getEngine()); IrisFloatingChildBiomeModifier floatingChildBiomes = new IrisFloatingChildBiomeModifier(getEngine()); EngineStage sBiome = (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c); @@ -91,7 +89,6 @@ public class ModeOverworld extends IrisEngineMode implements EngineMode { }; EngineStage sFloatingTerrainSolid = (x, z, k, p, m, c) -> floatingChildBiomes.modify(x, z, k, m, c); EngineStage sFloatingDecorate = (x, z, k, p, m, c) -> floatingChildBiomes.decorateColumns(x, z, k, m, c); - EngineStage sPerfection = (x, z, k, p, m, c) -> perfection.modify(x, z, k, m, c); EngineStage sCustom = (x, z, k, p, m, c) -> { if (shouldBypassMantleStages()) { return; @@ -115,7 +112,6 @@ public class ModeOverworld extends IrisEngineMode implements EngineMode { registerStage(sInsertMatter); registerStage(sDecorant); registerStage(sFloatingDecorate); - registerStage(sPerfection); registerStage(sCustom); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java deleted file mode 100644 index 163cda7dc..000000000 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisPerfectionModifier.java +++ /dev/null @@ -1,200 +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.modifier; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedModifier; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.iris.util.common.parallel.BurstExecutor; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.PlatformBlockState; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -public class IrisPerfectionModifier extends EngineAssignedModifier { - private static final class States { - private static final PlatformBlockState AIR = B.getState("AIR"); - private static final PlatformBlockState WATER = B.getState("WATER"); - private static final Map ORE_BASES = buildOreBases(); - } - - public IrisPerfectionModifier(Engine engine) { - super(engine, "Perfection"); - } - - private static Map buildOreBases() { - Map map = new HashMap<>(); - PlatformBlockState stone = B.getState("STONE"); - PlatformBlockState deepslate = B.getState("DEEPSLATE"); - PlatformBlockState netherrack = B.getState("NETHERRACK"); - PlatformBlockState blackstone = B.getState("BLACKSTONE"); - map.put("minecraft:coal_ore", stone); - map.put("minecraft:copper_ore", stone); - map.put("minecraft:iron_ore", stone); - map.put("minecraft:gold_ore", stone); - map.put("minecraft:redstone_ore", stone); - map.put("minecraft:lapis_ore", stone); - map.put("minecraft:diamond_ore", stone); - map.put("minecraft:emerald_ore", stone); - map.put("minecraft:deepslate_coal_ore", deepslate); - map.put("minecraft:deepslate_copper_ore", deepslate); - map.put("minecraft:deepslate_iron_ore", deepslate); - map.put("minecraft:deepslate_gold_ore", deepslate); - map.put("minecraft:deepslate_redstone_ore", deepslate); - map.put("minecraft:deepslate_lapis_ore", deepslate); - map.put("minecraft:deepslate_diamond_ore", deepslate); - map.put("minecraft:deepslate_emerald_ore", deepslate); - map.put("minecraft:nether_gold_ore", netherrack); - map.put("minecraft:nether_quartz_ore", netherrack); - map.put("minecraft:ancient_debris", netherrack); - map.put("minecraft:gilded_blackstone", blackstone); - return map; - } - - private static String baseKey(PlatformBlockState state) { - String key = state.key(); - int bracket = key.indexOf('['); - return bracket < 0 ? key : key.substring(0, bracket); - } - - @Override - public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - if (getDimension().isHideOresForHiddenOre()) { - hideOres(output, multicore); - } - AtomicBoolean changed = new AtomicBoolean(true); - BurstExecutor burst = burst().burst(multicore); - while (changed.get()) { - changed.set(false); - for (int i = 0; i < 16; i++) { - int finalI = i; - burst.queue(() -> { - List surfaces = new ArrayList<>(); - List ceilings = new ArrayList<>(); - for (int j = 0; j < 16; j++) { - surfaces.clear(); - ceilings.clear(); - int top = getHeight(output, finalI, j); - boolean inside = true; - surfaces.add(top); - - for (int k = top; k >= 0; k--) { - PlatformBlockState b = output.get(finalI, k, j); - boolean now = b != null && !(B.isAir(b) || B.isFluid(b)); - - if (now != inside) { - inside = now; - - if (inside) { - surfaces.add(k); - } else { - ceilings.add(k + 1); - } - } - } - - for (int k : surfaces) { - PlatformBlockState tip = output.get(finalI, k, j); - - if (tip == null) { - continue; - } - - boolean remove = false; - boolean remove2 = false; - - if (B.isDecorant(tip)) { - PlatformBlockState bel = output.get(finalI, k - 1, j); - - if (bel == null) { - remove = true; - } else if (!B.canPlaceOnto(tip, bel)) { - remove = true; - } else if (IrisProceduralBlocks.hasProperty(bel, "half")) { - PlatformBlockState bb = output.get(finalI, k - 2, j); - if (bb == null || !B.canPlaceOnto(bel, bb)) { - remove = true; - remove2 = true; - } - } - - if (remove) { - changed.set(true); - output.set(finalI, k, j, States.AIR); - - if (remove2) { - output.set(finalI, k - 1, j, States.AIR); - } - } - } - } - } - }); - } - burst.complete(); - } - - getEngine().getMetrics().getPerfection().put(p.getMilliseconds()); - } - - private void hideOres(Hunk output, boolean multicore) { - BurstExecutor burst = burst().burst(multicore); - int height = output.getHeight(); - for (int i = 0; i < 16; i++) { - int finalI = i; - burst.queue(() -> { - for (int j = 0; j < 16; j++) { - for (int k = height - 1; k >= 0; k--) { - PlatformBlockState block = output.get(finalI, k, j); - if (block == null) { - continue; - } - PlatformBlockState base = States.ORE_BASES.get(baseKey(block)); - if (base != null) { - output.set(finalI, k, j, base); - } - } - } - }); - } - burst.complete(); - } - - private int getHeight(Hunk output, int x, int z) { - for (int i = output.getHeight() - 1; i >= 0; i--) { - PlatformBlockState b = output.get(x, i, z); - - if (b != null) { - if (!B.isAir(b) && !B.isFluid(b)) { - return i; - } - } - } - - return 0; - } -} diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java new file mode 100644 index 000000000..4a2f8b5e8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -0,0 +1,187 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.perfection.PerfectionStages; +import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.dimension.IrisDimensionModeType; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Module {@code iris:perfection}: on overworld chunks, turns ores back into the stone around them when the + * dimension hides its ores, then removes decorations whose block below cannot hold them, again until none + * is left, since removing one can strand the one above. + */ +public final class PerfectionModule implements IrisModule { + private static final String VERSION = "built-in"; + private static final String HALF = "half"; + private static final char PROPERTIES_START = '['; + + private static final class States { + private static final PlatformBlockState AIR = B.getState("AIR"); + private static final Map ORE_BASES = oreBases(); + } + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:perfection", "Perfection", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(PerfectionStages.SURFACE).run(PerfectionModule::perfect); + } + + private static void perfect(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + Engine engine = chunk.engine(); + IrisDimension dimension = engine.getDimension(); + if (dimension.getMode().getType() != IrisDimensionModeType.OVERWORLD) { + return; + } + PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); + Hunk blocks = chunk.blocks(); + if (dimension.isHideOresForHiddenOre()) { + hideOres(blocks); + } + boolean removed; + do { + removed = removeUnsupportedDecorants(blocks); + } while (removed); + engine.getMetrics().getPerfection().put(stopwatch.getMilliseconds()); + } + + private static void hideOres(Hunk blocks) { + for (int x = 0; x < blocks.getWidth(); x++) { + for (int z = 0; z < blocks.getDepth(); z++) { + for (int y = blocks.getHeight() - 1; y >= 0; y--) { + PlatformBlockState block = blocks.get(x, y, z); + PlatformBlockState base = block == null ? null : States.ORE_BASES.get(materialOf(block)); + if (base != null) { + blocks.set(x, y, z, base); + } + } + } + } + } + + /** One pass over every column; whether it removed anything. */ + private static boolean removeUnsupportedDecorants(Hunk blocks) { + boolean removed = false; + for (int x = 0; x < blocks.getWidth(); x++) { + for (int z = 0; z < blocks.getDepth(); z++) { + for (int surface : surfaces(blocks, x, z)) { + removed |= removeIfUnsupported(blocks, x, surface, z); + } + } + } + return removed; + } + + /** The topmost solid block of a column and each solid block with open space above it below that. */ + private static List surfaces(Hunk blocks, int x, int z) { + List surfaces = new ArrayList<>(); + int top = topSolid(blocks, x, z); + surfaces.add(top); + boolean inside = true; + for (int y = top; y >= 0; y--) { + boolean solid = isSolid(blocks.get(x, y, z)); + if (solid != inside) { + inside = solid; + if (inside) { + surfaces.add(y); + } + } + } + return surfaces; + } + + private static boolean removeIfUnsupported(Hunk blocks, int x, int y, int z) { + PlatformBlockState tip = blocks.get(x, y, z); + if (tip == null || !B.isDecorant(tip)) { + return false; + } + PlatformBlockState below = blocks.get(x, y - 1, z); + if (below == null || !B.canPlaceOnto(tip, below)) { + blocks.set(x, y, z, States.AIR); + return true; + } + if (!IrisProceduralBlocks.hasProperty(below, HALF)) { + return false; + } + PlatformBlockState belowBelow = blocks.get(x, y - 2, z); + if (belowBelow != null && B.canPlaceOnto(below, belowBelow)) { + return false; + } + blocks.set(x, y, z, States.AIR); + blocks.set(x, y - 1, z, States.AIR); + return true; + } + + private static int topSolid(Hunk blocks, int x, int z) { + for (int y = blocks.getHeight() - 1; y >= 0; y--) { + if (isSolid(blocks.get(x, y, z))) { + return y; + } + } + return 0; + } + + private static boolean isSolid(PlatformBlockState block) { + return block != null && !(B.isAir(block) || B.isFluid(block)); + } + + private static String materialOf(PlatformBlockState state) { + String key = state.key(); + int properties = key.indexOf(PROPERTIES_START); + return properties < 0 ? key : key.substring(0, properties); + } + + private static Map oreBases() { + Map bases = new HashMap<>(); + PlatformBlockState stone = B.getState("STONE"); + PlatformBlockState deepslate = B.getState("DEEPSLATE"); + PlatformBlockState netherrack = B.getState("NETHERRACK"); + PlatformBlockState blackstone = B.getState("BLACKSTONE"); + for (String ore : List.of("coal", "copper", "iron", "gold", "redstone", "lapis", "diamond", "emerald")) { + bases.put("minecraft:" + ore + "_ore", stone); + bases.put("minecraft:deepslate_" + ore + "_ore", deepslate); + } + bases.put("minecraft:nether_gold_ore", netherrack); + bases.put("minecraft:nether_quartz_ore", netherrack); + bases.put("minecraft:ancient_debris", netherrack); + bases.put("minecraft:gilded_blackstone", blackstone); + return bases; + } +} From 70a69fadad1ebbfc821fad12c46694fedfc7cb5f Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 08:53:17 +0200 Subject: [PATCH 005/139] Describe the ported built-in modules in the README --- README.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 51f9a1f99..bd0790394 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,14 @@ # Iris default module -This project owns the 388 built-in Iris feature and setting sources under -`src/main/java/art/arcane/iris/engine`. The files retain their existing packages, behavior, pack -fields and direct dependencies on Iris internals. +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. + +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`, +`iris:vacuum`, `iris:snow`) and `iris:perfection`. Their stage constants and the output types packs +may read live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; +their stage bodies live beside the features they replace. 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 From a77a097bafd983170c259813f85996ac20c7581f Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 12:02:38 +0200 Subject: [PATCH 006/139] Generate every world through built-in module stages and remove the world modes The overworld pipeline becomes ten built-in modules with typed ordering: biome, terrain, carve, post, floating, deposit, matter, decorant, perfection and custom. The world modes and the dimension's mode setting are gone; a pack's mode key now gets the unknown-key warning. iris:biome, iris:deposit and the cave planning of iris:carve are full ports. Deposits are settings of their own (iris:deposit, written as "deposits": [...]) that stack: a chunk gets the dimension's, the region's and the biome's at its centre column. Cave planning is a mantle stage with a reach of one block, its work done by CaveCarving. The other stages wrap the existing actuators and modifiers. Perfection no longer checks for an overworld. --- README.md | 15 +- source-patterns.txt | 1 - .../iris/builtin/biome/BiomeStages.java | 31 +++++ .../iris/builtin/carve/CarveStages.java | 34 +++++ .../iris/builtin/custom/CustomStages.java | 31 +++++ .../iris/builtin/decorant/DecorantStages.java | 31 +++++ .../iris/builtin/deposit/DepositSettings.java | 49 +++++++ .../iris/builtin/deposit/DepositStages.java | 34 +++++ .../iris/builtin/floating/FloatingStages.java | 33 +++++ .../iris/builtin/matter/MatterStages.java | 31 +++++ .../arcane/iris/builtin/post/PostStages.java | 31 +++++ .../iris/builtin/terrain/TerrainStages.java | 31 +++++ .../iris/engine/actuator/BiomeModule.java | 126 +++++++++++++++++ .../iris/engine/actuator/DecorantModule.java | 51 +++++++ .../engine/actuator/IrisBiomeActuator.java | 115 ---------------- .../iris/engine/actuator/TerrainModule.java | 50 +++++++ ...CarvingComponent.java => CaveCarving.java} | 77 +++++------ .../iris/engine/mode/ModeEnclosure.java | 38 ------ .../arcane/iris/engine/mode/ModeIslands.java | 38 ------ .../iris/engine/mode/ModeOverworld.java | 129 ------------------ .../iris/engine/mode/ModeSuperFlat.java | 38 ------ .../iris/engine/modifier/CarveModule.java | 78 +++++++++++ .../iris/engine/modifier/CustomModule.java | 55 ++++++++ .../iris/engine/modifier/DepositModule.java | 78 +++++++++++ ...epositModifier.java => DepositPlacer.java} | 36 +++-- .../iris/engine/modifier/FloatingModule.java | 62 +++++++++ .../iris/engine/modifier/MatterModule.java | 59 ++++++++ .../engine/modifier/PerfectionModule.java | 9 +- .../iris/engine/modifier/PostModule.java | 54 ++++++++ .../engine/object/world/biome/IrisBiome.java | 4 - .../object/world/dimension/IrisDimension.java | 7 - .../world/dimension/IrisDimensionMode.java | 43 ------ .../dimension/IrisDimensionModeType.java | 54 -------- .../object/world/region/IrisRegion.java | 4 - 34 files changed, 1012 insertions(+), 545 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CarveStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/custom/CustomStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/matter/MatterStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/post/PostStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java rename src/main/java/art/arcane/iris/engine/mantle/components/{MantleCarvingComponent.java => CaveCarving.java} (91%) delete mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java delete mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeIslands.java delete mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java delete mode 100644 src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CarveModule.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CustomModule.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/DepositModule.java rename src/main/java/art/arcane/iris/engine/modifier/{IrisDepositModifier.java => DepositPlacer.java} (91%) create mode 100644 src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/MatterModule.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/PostModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java diff --git a/README.md b/README.md index bd0790394..f1ba758e0 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,18 @@ direct dependencies on Iris internals. 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`, -`iris:vacuum`, `iris:snow`) and `iris:perfection`. Their stage constants and the output types packs -may read live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; -their stage bodies live beside the features they replace. +`iris:vacuum`, `iris:snow`) and chunk generation, which every world runs in this order: `iris:biome`, +`iris:terrain`, `iris:carve` (a mantle stage planning caves, and a chunk stage cutting them), +`iris:post`, `iris:floating` (solids), `iris:deposit`, `iris:matter`, `iris:decorant`, `iris:floating` +(decoration), `iris:perfection` and `iris:custom`. There are no world modes any more. Their stage +constants, and the settings and output types packs may read, live in +`src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live +beside the features they replace. + +`iris:biome` and `iris:deposit` (chunk stages) and the cave planning of `iris:carve` (a mantle stage) are +full ports: the module owns its logic and per-engine state. The other generation stages are thin wrappers +that run the existing actuator or modifier unchanged. Iris's object, floating object and structure mantle +components are still Iris mantle components. 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 diff --git a/source-patterns.txt b/source-patterns.txt index 6e0d633f7..b09f3c28b 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -1,7 +1,6 @@ art/arcane/iris/engine/actuator/** art/arcane/iris/engine/decorator/** art/arcane/iris/engine/modifier/** -art/arcane/iris/engine/mode/** art/arcane/iris/engine/mantle/components/** art/arcane/iris/engine/object/** art/arcane/iris/engine/image/** diff --git a/src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java b/src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java new file mode 100644 index 000000000..c83b8efc0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.biome; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:biome}: the biomes a chunk reports to the server. */ +public final class BiomeStages { + /** Writes every column's biome, sky biome or custom biome, into the chunk. */ + public static final ChunkStage WRITE = Stage.chunk("iris:biome/write"); + + private BiomeStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarveStages.java b/src/main/java/art/arcane/iris/builtin/carve/CarveStages.java new file mode 100644 index 000000000..d63809438 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CarveStages.java @@ -0,0 +1,34 @@ +/* + * 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.builtin.carve; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.MantleStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:carve}: caves, planned in the mantle and cut into each chunk's terrain. */ +public final class CarveStages { + /** Plans the caves of the dimension's cave profiles into the mantle, one block into each neighbor. */ + public static final MantleStage CAVES = Stage.mantle("iris:carve/caves"); + /** Cuts the planned caves out of the chunk's terrain and decorates their floors and ceilings. */ + public static final ChunkStage APPLY = Stage.chunk("iris:carve/apply"); + + private CarveStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/custom/CustomStages.java b/src/main/java/art/arcane/iris/builtin/custom/CustomStages.java new file mode 100644 index 000000000..c7ca96c7b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/custom/CustomStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.custom; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:custom}: blocks of content plugins, which the server places after generation. */ +public final class CustomStages { + /** Records the chunk's custom blocks so the server can place them once the chunk exists. */ + public static final ChunkStage BLOCKS = Stage.chunk("iris:custom/blocks"); + + private CustomStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java new file mode 100644 index 000000000..1158ada20 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.decorant; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:decorant}: the decorators of biomes, such as grass, flowers and cave ceilings. */ +public final class DecorantStages { + /** Places every column's surface, sea, shore and cave decorators. */ + public static final ChunkStage DECORATE = Stage.chunk("iris:decorant/decorate"); + + private DecorantStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java new file mode 100644 index 000000000..c9901093e --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java @@ -0,0 +1,49 @@ +/* + * 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.builtin.deposit; + +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The deposits one dimension, region or biome declares, written as {@code "deposits": [...]}. Levels stack: + * a chunk gets the deposits of its dimension, its centre column's region and that column's biome. + */ +@Desc("Ores and other deposits generated in every chunk where this applies") +@Feature(id = "iris:deposit", name = "Deposits", alias = "deposits", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class DepositSettings implements IrisFeature { + @Desc("Define deposit generators that this applies to chunks") + private List generators = List.of(); + + public DepositSettings() { + } + + public DepositSettings(List generators) { + this.generators = List.copyOf(generators); + } + + public List generators() { + return generators; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java new file mode 100644 index 000000000..e61abc3ca --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java @@ -0,0 +1,34 @@ +/* + * 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.builtin.deposit; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:deposit}: ores and other deposits. */ +public final class DepositStages { + /** + * Places the deposits every level declares at the chunk's centre column, the dimension's, the region's and + * the biome's, each with its own clumps. Active where any column of the chunk has deposits. + */ + public static final ChunkStage ORES = Stage.chunk("iris:deposit/ores"); + + private DepositStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java new file mode 100644 index 000000000..d3deb4680 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java @@ -0,0 +1,33 @@ +/* + * 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.builtin.floating; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:floating}: the floating islands of floating child biomes. */ +public final class FloatingStages { + /** Writes the islands' solid blocks. */ + public static final ChunkStage SOLIDS = Stage.chunk("iris:floating/solids"); + /** Decorates the islands' tops and bottoms once the chunk's own decoration is done. */ + public static final ChunkStage DECORATE = Stage.chunk("iris:floating/decorate"); + + private FloatingStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/matter/MatterStages.java b/src/main/java/art/arcane/iris/builtin/matter/MatterStages.java new file mode 100644 index 000000000..8becc062b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/matter/MatterStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.matter; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:matter}: the blocks the mantle planned for a chunk, such as objects and structures. */ +public final class MatterStages { + /** Copies the chunk's planned mantle blocks into it. */ + public static final ChunkStage INSERT = Stage.chunk("iris:matter/insert"); + + private MatterStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/post/PostStages.java b/src/main/java/art/arcane/iris/builtin/post/PostStages.java new file mode 100644 index 000000000..8c45102c1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/post/PostStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.post; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:post}: smoothing a chunk's surface after carving. */ +public final class PostStages { + /** Fills single-block holes, places slabs and walls on steps and settles snow. */ + public static final ChunkStage SMOOTH = Stage.chunk("iris:post/smooth"); + + private PostStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java new file mode 100644 index 000000000..da7131982 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.terrain; + +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:terrain}: the solid ground, fluids and biome layers of a chunk. */ +public final class TerrainStages { + /** Fills each column from bedrock up to its height and the fluid height, with its biome's layers. */ + public static final ChunkStage SHAPE = Stage.chunk("iris:terrain/shape"); + + private TerrainStages() { + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java b/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java new file mode 100644 index 000000000..1ef7c0591 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java @@ -0,0 +1,126 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.biome.BiomeStages; +import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBiome; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.context.ChunkedDataCache; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.collection.KMap; +import art.arcane.volmlib.util.mantle.runtime.Mantle; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterBiomeInject; +import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:biome}: writes each column's biome into the chunk's biome hunk, a custom biome under the + * dimension's namespace, and records the biome id in the mantle for platforms that inject biomes later. + */ +public final class BiomeModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:biome", "Biomes", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(BiomeStages.WRITE).run(BiomeModule::write); + } + + private static void write(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + chunk.state(BiomeWriter.class, BiomeWriter::new).write(chunk.originX(), chunk.originZ(), chunk.biomes(), chunk.context()); + } + + /** What writing biomes keeps for one engine runtime: the biome stream's random and the platform biomes resolved so far. */ + static final class BiomeWriter { + private final Engine engine; + private final RNG rng; + private final KMap resolvedBiomes = new KMap<>(); + + BiomeWriter(Engine engine) { + this.engine = engine; + this.rng = new RNG(engine.getSeedManager().getBiome()); + } + + /** A partial biome write fails the chunk: a chunk flagged done with default biomes would keep them forever. */ + void write(int originX, int originZ, Hunk biomes, ChunkContext context) { + PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); + Mantle mantle = engine.getMantle().getMantle(); + ChunkedDataCache biomeCache = context.getBiome(); + for (int localX = 0; localX < biomes.getWidth(); localX++) { + for (int localZ = 0; localZ < biomes.getDepth(); localZ++) { + int worldX = originX + localX; + int worldZ = originZ + localZ; + ResolvedBiome resolved = resolve(keyOf(biomeCache.get(localX, localZ), worldX, worldZ)); + if (resolved.biome() != null) { + biomes.set(localX, 0, localZ, localX, biomes.getHeight() - 1, localZ, resolved.biome()); + } + mantle.set(worldX, 0, worldZ, resolved.matter()); + } + } + engine.getMetrics().getBiome().put(stopwatch.getMilliseconds()); + } + + private String keyOf(IrisBiome biome, int worldX, int worldZ) { + if (!biome.isCustom()) { + return biome.getSkyBiomeKey(rng, engine, worldX, 0, worldZ); + } + IrisBiomeCustom custom = biome.getCustomBiome(rng, engine, worldX, 0, worldZ); + return engine.getDimension().getLoadKey() + ":" + custom.getId(); + } + + /** + * The registry lookup and the biome id depend only on the key, so the pair is cached instead of paying two + * string-keyed lookups per column. Unresolved biomes are never cached, so a biome registered later still + * resolves. + */ + private ResolvedBiome resolve(String key) { + ResolvedBiome cached = key == null ? null : resolvedBiomes.get(key); + if (cached != null) { + return cached; + } + IrisPlatform platform = IrisPlatforms.get(); + PlatformBiome biome = platform.registries().biome(key); + ResolvedBiome resolved = new ResolvedBiome(biome, BiomeInjectMatter.get(platform.biomeWriter().biomeIdFor(key))); + if (key != null && biome != null) { + resolvedBiomes.put(key, resolved); + } + return resolved; + } + } + + private record ResolvedBiome(PlatformBiome biome, MatterBiomeInject matter) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java new file mode 100644 index 000000000..d1a8b1b2a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -0,0 +1,51 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.decorant.DecorantStages; +import art.arcane.iris.builtin.matter.MatterStages; +import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:decorant}: the biomes' decorators, placed on the surface the mantle's blocks left. A thin + * wrapper: the stage runs {@link IrisDecorantActuator} unchanged, one per engine runtime. + */ +public final class DecorantModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:decorant", "Decorators", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(DecorantStages.DECORATE).requires(MatterStages.INSERT).run(DecorantModule::decorate); + } + + private static void decorate(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + chunk.state(IrisDecorantActuator.class, IrisDecorantActuator::new) + .actuate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java b/src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java deleted file mode 100644 index d420dfc73..000000000 --- a/src/main/java/art/arcane/iris/engine/actuator/IrisBiomeActuator.java +++ /dev/null @@ -1,115 +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.actuator; - -import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedActuator; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.context.ChunkedDataCache; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterBiomeInject; -import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; -import art.arcane.volmlib.util.scheduling.ChronoLatch; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBiome; - -public class IrisBiomeActuator extends EngineAssignedActuator { - private final RNG rng; - private final ChronoLatch cl = new ChronoLatch(5000); - private final KMap resolvedBiomes = new KMap<>(); - - public IrisBiomeActuator(Engine engine) { - super(engine, "Biome"); - rng = new RNG(engine.getSeedManager().getBiome()); - } - - @BlockCoordinates - @Override - public void onActuate(int x, int z, Hunk h, boolean multicore, ChunkContext context) { - // No catch here: a partial biome write must fail the chunk (EngineAssignedActuator - // rethrows), or the chunk is flagged REAL with default plains columns forever. - PrecisionStopwatch p = PrecisionStopwatch.start(); - int width = h.getWidth(); - int depth = h.getDepth(); - int height = h.getHeight(); - Engine engine = getEngine(); - Mantle mantle = engine.getMantle().getMantle(); - ChunkedDataCache biomeCache = context.getBiome(); - - for (int xf = 0; xf < width; xf++) { - IrisBiome ib; - for (int zf = 0; zf < depth; zf++) { - ib = biomeCache.get(xf, zf); - String key; - - if (ib.isCustom()) { - IrisBiomeCustom custom = ib.getCustomBiome(rng, engine, x + xf, 0, z + zf); - key = getDimension().getLoadKey() + ":" + custom.getId(); - } else { - key = ib.getSkyBiomeKey(rng, engine, x + xf, 0, z + zf); - } - - ResolvedBiome resolved = resolve(key); - PlatformBiome biome = resolved.biome(); - - if (biome != null) { - h.set(xf, 0, zf, xf, height - 1, zf, biome); - } - - mantle.set(x + xf, 0, z + zf, resolved.matter()); - } - } - engine.getMetrics().getBiome().put(p.getMilliseconds()); - } - - /** - * The registry lookup and the biome id only depend on the scatter resolved key, so cache the pair - * instead of paying two string keyed lookups per column. Unresolved biomes are never cached, so a - * biome registered later still resolves. - */ - private ResolvedBiome resolve(String key) { - ResolvedBiome cached = key == null ? null : resolvedBiomes.get(key); - - if (cached != null) { - return cached; - } - - IrisPlatform platform = IrisPlatforms.get(); - PlatformBiome biome = platform.registries().biome(key); - ResolvedBiome resolved = new ResolvedBiome(biome, BiomeInjectMatter.get(platform.biomeWriter().biomeIdFor(key))); - - if (key != null && biome != null) { - resolvedBiomes.put(key, resolved); - } - - return resolved; - } - - private record ResolvedBiome(PlatformBiome biome, MatterBiomeInject matter) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java new file mode 100644 index 000000000..9bc017a6b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -0,0 +1,50 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.terrain.TerrainStages; +import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. A thin wrapper: the stage runs + * {@link IrisTerrainNormalActuator} unchanged, one per engine runtime. + */ +public final class TerrainModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:terrain", "Terrain", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(TerrainStages.SHAPE).run(TerrainModule::shape); + } + + private static void shape(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + chunk.state(IrisTerrainNormalActuator.class, IrisTerrainNormalActuator::new) + .actuate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java rename to src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index fa61ed86f..c67e63461 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/MantleCarvingComponent.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -20,9 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.mantle.ComponentFlag; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.mantle.IrisMantleComponent; +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.terrain.carving.IrisCaveProfile; @@ -38,7 +36,6 @@ import art.arcane.iris.util.project.stream.utility.ChunkFillableDoubleStream2D; import art.arcane.iris.util.simd.SimdKernels; import art.arcane.iris.util.simd.SimdSupport; import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.flag.ReservedFlag; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; @@ -48,8 +45,12 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; -@ComponentFlag(ReservedFlag.CARVED) -public class MantleCarvingComponent extends IrisMantleComponent { +/** + * Plans one chunk's caves into the mantle for {@link art.arcane.iris.engine.modifier.CarveModule}: the cave + * profiles of the dimension's carving entries and of the regions and biomes around the chunk, blended over + * their borders. One per engine runtime, keeping a carver per cave profile. + */ +public class CaveCarving { private static final int CHUNK_SIZE = 16; private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; private static final int BLEND_RADIUS = 3; @@ -64,6 +65,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; private static final ThreadLocal BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); + private final Engine engine; private final Object profileCarverLock = new Object(); private volatile Map profileCarvers = new IdentityHashMap<>(); @@ -80,31 +82,20 @@ public class MantleCarvingComponent extends IrisMantleComponent { } } - public MantleCarvingComponent(EngineMantle engineMantle) { - super(engineMantle, ReservedFlag.CARVED, 0); + public CaveCarving(Engine engine) { + this.engine = engine; } - @Override - public void hotload() { - super.hotload(); - // Hotload swaps in fresh IrisCaveProfile instances (identity keys), so retained - // entries would strand a full carver set pinning the closed IrisData per reload. - // Carvers rebuild deterministically from the carve seed, so output is unchanged. - synchronized (profileCarverLock) { - profileCarvers = new IdentityHashMap<>(); - } - } - - @Override - public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ + public void carve(MantleWriter writer, int x, int z, ChunkContext context) { IrisComplex complex = context.getComplex(); IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); BlendScratch blendScratch = BLEND_SCRATCH.get(); int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); List weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); - getEngineMantle().getEngine().getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); - int fluidHeight = getDimension().getFluidHeight(); + engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); + int fluidHeight = engine.getDimension().getFluidHeight(); int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY; SurfaceFluidBoundaryPlan.fill( chunkSurfaceHeights, @@ -120,8 +111,8 @@ public class MantleCarvingComponent extends IrisMantleComponent { carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); } - UpperDimensionContext upperCtx = getEngineMantle().getEngine().getUpperContext(); - if (upperCtx != null && getDimension().isUpperDimensionCarving()) { + UpperDimensionContext upperCtx = engine.getUpperContext(); + if (upperCtx != null && engine.getDimension().isUpperDimensionCarving()) { carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, chunkSurfaceHeights, fluidSupportPlan); } fluidSupportPlan.resolve(writer.acquireChunk(x, z)); @@ -158,9 +149,9 @@ public class MantleCarvingComponent extends IrisMantleComponent { private void carveUpperTerrain(UpperDimensionContext upperCtx, List normalProfiles, MantleWriter writer, int cx, int cz, int[] lowerSurfaceHeights, CaveFluidSupportPlan fluidSupportPlan) { - int chunkHeight = getEngineMantle().getEngine().getHeight(); - int worldMinHeight = getEngineMantle().getEngine().getWorld().minHeight(); - int gap = getDimension().getUpperDimensionGap(); + int chunkHeight = engine.getHeight(); + int worldMinHeight = engine.getWorld().minHeight(); + int gap = engine.getDimension().getUpperDimensionGap(); int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); @@ -307,7 +298,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { List weightedProfiles = new ArrayList<>(); - List entries = getDimension().getCarving(); + List entries = engine.getDimension().getCarving(); if (entries == null || entries.isEmpty()) { return weightedProfiles; } @@ -320,7 +311,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { continue; } - IrisBiome rootBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), entry, resolverState); + IrisBiome rootBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry, resolverState); if (rootBiome == null) { continue; } @@ -333,7 +324,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { IrisRange worldYRange = entry.getWorldYRange(); for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { IrisDimensionCarvingEntry resolvedEntry = columnPlan[columnIndex]; - IrisBiome resolvedBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), resolvedEntry, resolverState); + IrisBiome resolvedBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); if (resolvedBiome == null) { continue; } @@ -368,7 +359,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldZ = baseZ + localZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - columnPlan[columnIndex] = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), entry, worldX, worldZ, resolverState); + columnPlan[columnIndex] = IrisDimensionCarvingResolver.resolveFromRoot(engine, entry, worldX, worldZ, resolverState); } } } @@ -416,7 +407,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { IrisDimensionCarvingResolver.State resolverState ) { IrisCaveProfile resolved = null; - IrisCaveProfile dimensionProfile = getDimension().getCaveProfile(); + IrisCaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); if (isProfileEnabled(dimensionProfile)) { resolved = dimensionProfile; } @@ -437,12 +428,12 @@ public class MantleCarvingComponent extends IrisMantleComponent { int roundedSurfaceY = (int) Math.round(surfaceHeight); int sampleY = Math.max(1, roundedSurfaceY - 56); - int worldY = sampleY + getEngineMantle().getEngine().getWorld().minHeight(); - IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(getEngineMantle().getEngine(), worldY, resolverState); + int worldY = sampleY + engine.getWorld().minHeight(); + IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(engine, worldY, resolverState); IrisBiome resolvedCarvingBiome = null; if (rootCarvingEntry != null) { - IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(getEngineMantle().getEngine(), rootCarvingEntry, worldX, worldZ, resolverState); - resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(getEngineMantle().getEngine(), resolvedCarvingEntry, resolverState); + IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(engine, rootCarvingEntry, worldX, worldZ, resolverState); + resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolvedCarvingEntry, resolverState); if (resolvedCarvingBiome != null) { caveBiome = resolvedCarvingBiome; } @@ -514,7 +505,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { return carver; } - IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(getEngineMantle().getEngine(), profile); + IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(engine, profile); synchronized (profileCarverLock) { IrisCaveCarver3D published = profileCarvers.get(profile); if (published != null) { @@ -532,10 +523,6 @@ public class MantleCarvingComponent extends IrisMantleComponent { return profile != null && profile.isEnabled(); } - protected int computeRadius() { - return 1; - } - private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) { int[] surfaceHeights = scratch; int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); @@ -565,7 +552,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { surfaceHeights[columnIndex] = (int) Math.round(cachedChunkHeights[(localZ << 4) + localX]); continue; } - surfaceHeights[columnIndex] = getEngineMantle().getEngine().getHeight(worldX, worldZ); + surfaceHeights[columnIndex] = engine.getHeight(worldX, worldZ); } } return surfaceHeights; @@ -582,7 +569,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { int clampedLimit = Math.max(1, maxProfiles); List rankedProfiles = new ArrayList<>(blendedProfiles); - rankedProfiles.sort(MantleCarvingComponent::compareBySelectionRank); + rankedProfiles.sort(CaveCarving::compareBySelectionRank); List keptProfiles = new ArrayList<>(); int keptCount = Math.min(clampedLimit, rankedProfiles.size()); for (int index = 0; index < keptCount; index++) { @@ -620,7 +607,7 @@ public class MantleCarvingComponent extends IrisMantleComponent { double averageWeight = computeAverageWeight(keptProfile.columnWeights, areaSize); mergedProfiles.add(new WeightedProfile(keptProfile.profile, keptProfile.columnWeights, averageWeight, keptProfile.worldYRange, keptProfile.sequence)); } - mergedProfiles.sort(MantleCarvingComponent::compareByCarveOrder); + mergedProfiles.sort(CaveCarving::compareByCarveOrder); return mergedProfiles; } diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java b/src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.java deleted file mode 100644 index 09d2f9f15..000000000 --- a/src/main/java/art/arcane/iris/engine/mode/ModeEnclosure.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.mode; - -import art.arcane.iris.engine.actuator.IrisBiomeActuator; -import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineMode; -import art.arcane.iris.engine.framework.IrisEngineMode; - -public class ModeEnclosure extends IrisEngineMode implements EngineMode { - public ModeEnclosure(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - - registerStage(burst( - (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c), - (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c) - )); - } -} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeIslands.java b/src/main/java/art/arcane/iris/engine/mode/ModeIslands.java deleted file mode 100644 index 494b46bc8..000000000 --- a/src/main/java/art/arcane/iris/engine/mode/ModeIslands.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.mode; - -import art.arcane.iris.engine.actuator.IrisBiomeActuator; -import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineMode; -import art.arcane.iris.engine.framework.IrisEngineMode; - -public class ModeIslands extends IrisEngineMode implements EngineMode { - public ModeIslands(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - - registerStage(burst( - (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c), - (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c) - )); - } -} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java b/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java deleted file mode 100644 index 3534e2f78..000000000 --- a/src/main/java/art/arcane/iris/engine/mode/ModeOverworld.java +++ /dev/null @@ -1,129 +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.mode; - -import art.arcane.iris.engine.actuator.IrisBiomeActuator; -import art.arcane.iris.engine.actuator.IrisDecorantActuator; -import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineMode; -import art.arcane.iris.engine.framework.EnginePlatformHooks; -import art.arcane.iris.engine.framework.EngineStage; -import art.arcane.iris.engine.framework.IrisEngineMode; -import art.arcane.iris.engine.modifier.IrisCarveModifier; -import art.arcane.iris.engine.modifier.IrisCustomModifier; -import art.arcane.iris.engine.modifier.IrisDepositModifier; -import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier; -import art.arcane.iris.engine.modifier.IrisPostModifier; -import art.arcane.iris.spi.IrisLogging; - -import java.util.concurrent.atomic.AtomicLong; - -public class ModeOverworld extends IrisEngineMode implements EngineMode { - private static final AtomicLong lastMaintenanceBypassLog = new AtomicLong(0L); - private final EnginePlatformHooks platformHooks; - - public ModeOverworld(Engine engine) { - super(engine); - platformHooks = engine.getPlatformHooks(); - IrisTerrainNormalActuator terrain = new IrisTerrainNormalActuator(getEngine()); - IrisBiomeActuator biome = new IrisBiomeActuator(getEngine()); - IrisDecorantActuator decorant = new IrisDecorantActuator(getEngine()); - IrisCarveModifier cave = new IrisCarveModifier(getEngine()); - IrisPostModifier post = new IrisPostModifier(getEngine()); - IrisDepositModifier deposit = new IrisDepositModifier(getEngine()); - IrisCustomModifier custom = new IrisCustomModifier(getEngine()); - IrisFloatingChildBiomeModifier floatingChildBiomes = new IrisFloatingChildBiomeModifier(getEngine()); - EngineStage sBiome = (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c); - EngineStage sGenMatter = (x, z, k, p, m, c) -> { - if (shouldBypassMantleStages()) { - return; - } - generateMatter( - x >> 4, - z >> 4, - m || getEngine().isStudio(), - c); - }; - EngineStage sTerrain = (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c); - EngineStage sDecorant = (x, z, k, p, m, c) -> decorant.actuate(x, z, k, m, c); - EngineStage sCave = (x, z, k, p, m, c) -> { - if (shouldBypassMantleStages()) { - return; - } - cave.modify(x >> 4, z >> 4, k, m, c); - }; - EngineStage sDeposit = (x, z, k, p, m, c) -> { - if (shouldBypassMantleStages()) { - return; - } - deposit.modify(x, z, k, m, c); - }; - EngineStage sPost = (x, z, k, p, m, c) -> { - if (shouldBypassMantleStages()) { - return; - } - post.modify(x, z, k, m, c); - }; - EngineStage sInsertMatter = (x, z, K, p, m, c) -> { - if (shouldBypassMantleStages()) { - return; - } - getMantle().insertMatter(x >> 4, z >> 4, K, m); - }; - EngineStage sFloatingTerrainSolid = (x, z, k, p, m, c) -> floatingChildBiomes.modify(x, z, k, m, c); - EngineStage sFloatingDecorate = (x, z, k, p, m, c) -> floatingChildBiomes.decorateColumns(x, z, k, m, c); - EngineStage sCustom = (x, z, k, p, m, c) -> { - if (shouldBypassMantleStages()) { - return; - } - custom.modify(x, z, k, m, c); - }; - - registerStage(burst( - sBiome, - sGenMatter, - sTerrain - )); - registerStage(sCave); - registerStage(sPost); - registerStage(sFloatingTerrainSolid); - // Never burst these three: all of them write the same block hunk (and sDecorant reads - // the surface sInsertMatter writes), so parallel order is scheduler-dependent. The - // production path already runs them inline in this order; sequential registration - // makes studio (the only multicore path) match production and the goldenhash baseline. - registerStage(sDeposit); - registerStage(sInsertMatter); - registerStage(sDecorant); - registerStage(sFloatingDecorate); - registerStage(sCustom); - } - - private boolean shouldBypassMantleStages() { - boolean active = platformHooks.shouldBypassMantleStages(getEngine()); - if (active) { - long now = System.currentTimeMillis(); - long last = lastMaintenanceBypassLog.get(); - if (now - last >= 5000L && lastMaintenanceBypassLog.compareAndSet(last, now)) { - IrisLogging.info("Maintenance regen bypass: skipping mantle-backed overworld stages for Folia safety."); - } - } - return active; - } -} diff --git a/src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java b/src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.java deleted file mode 100644 index 6cc04308b..000000000 --- a/src/main/java/art/arcane/iris/engine/mode/ModeSuperFlat.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.mode; - -import art.arcane.iris.engine.actuator.IrisBiomeActuator; -import art.arcane.iris.engine.actuator.IrisTerrainNormalActuator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineMode; -import art.arcane.iris.engine.framework.IrisEngineMode; - -public class ModeSuperFlat extends IrisEngineMode implements EngineMode { - public ModeSuperFlat(Engine engine) { - super(engine); - var terrain = new IrisTerrainNormalActuator(getEngine()); - var biome = new IrisBiomeActuator(getEngine()); - - registerStage(burst( - (x, z, k, p, m, c) -> terrain.actuate(x, z, k, m, c), - (x, z, k, p, m, c) -> biome.actuate(x, z, p, m, c) - )); - } -} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java new file mode 100644 index 000000000..476645917 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -0,0 +1,78 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.carve.CarveStages; +import art.arcane.iris.builtin.terrain.TerrainStages; +import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.core.modules.IrisMantleChunk; +import art.arcane.iris.engine.mantle.components.CaveCarving; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.volmlib.util.mantle.flag.ReservedFlag; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.MantleStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:carve}: caves. A mantle stage plans them into the mantle, reaching one block into each + * neighboring chunk where blended cave walls cross the border; a chunk stage later cuts them out of the chunk's + * terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by + * {@link CaveCarving}, one per engine runtime. The chunk stage is a thin wrapper around {@link IrisCarveModifier}. + */ +public final class CarveModule implements IrisModule { + private static final String VERSION = "built-in"; + /** Blended cave walls reach one block past the chunk. */ + private static final int CAVE_REACH_BLOCKS = 1; + private static final int CHUNK_SHIFT = 4; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:carve", "Caves", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(CarveStages.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); + graph.define(CarveStages.APPLY).requires(TerrainStages.SHAPE).run(CarveModule::applyCaves); + } + + private static void planCaves(MantleStageContext context) { + IrisMantleChunk chunk = IrisMantleChunk.current(); + if (!carves(chunk.engine().getDimension())) { + return; + } + chunk.state(CaveCarving.class, CaveCarving::new).carve(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + } + + private static void applyCaves(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + if (chunk.bypassesMantleStages()) { + return; + } + chunk.state(IrisCarveModifier.class, IrisCarveModifier::new).modify(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, + chunk.blocks(), chunk.multicore(), chunk.context()); + } + + /** A dimension turns carving off with {@code carvingEnabled}, or by listing {@code CARVED} in {@code disabledComponents}. */ + private static boolean carves(IrisDimension dimension) { + return dimension.isCarvingEnabled() && !dimension.getDisabledComponents().contains(ReservedFlag.CARVED); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java new file mode 100644 index 000000000..1be418b26 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java @@ -0,0 +1,55 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.custom.CustomStages; +import art.arcane.iris.builtin.perfection.PerfectionStages; +import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:custom}: records the chunk's content-plugin blocks for the server to place later. A thin + * wrapper: the stage runs {@link IrisCustomModifier} unchanged, one per engine runtime, except while + * maintenance regeneration bypasses the mantle. + */ +public final class CustomModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:custom", "Custom blocks", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(CustomStages.BLOCKS).requires(PerfectionStages.SURFACE).run(CustomModule::record); + } + + private static void record(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + if (chunk.bypassesMantleStages()) { + return; + } + chunk.state(IrisCustomModifier.class, IrisCustomModifier::new) + .modify(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java new file mode 100644 index 000000000..cdbc14311 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -0,0 +1,78 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.deposit.DepositSettings; +import art.arcane.iris.builtin.deposit.DepositStages; +import art.arcane.iris.builtin.floating.FloatingStages; +import art.arcane.iris.builtin.terrain.TerrainStages; +import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +import java.util.List; + +/** + * Module {@code iris:deposit}: ores and other deposits. The dimension, a region and a biome each declare their + * own {@link DepositSettings}, and they stack: a chunk gets every level's deposits at its centre column, the + * dimension's first, then the region's, then the biome's. The stage runs where any column of the chunk has + * deposits, but places only what the centre column declares, so a chunk's deposits do not depend on which + * of its columns a biome border crosses. + */ +public final class DepositModule implements IrisModule { + private static final String VERSION = "built-in"; + private static final int CHUNK_CENTRE = 7; + private static final int CHUNK_SHIFT = 4; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:deposit", "Deposits", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(DepositStages.ORES) + .when(DepositSettings.class) + .requires(TerrainStages.SHAPE) + .softAfter(FloatingStages.SOLIDS.ref()) + .run(DepositModule::place); + } + + private static void place(ChunkStageContext context, List> inChunk) { + IrisChunk chunk = IrisChunk.current(); + List generators = generatorsAtCentre(context.settings(), context.originX(), context.originZ()); + if (generators.isEmpty() || chunk.bypassesMantleStages()) { + return; + } + chunk.state(DepositPlacer.class, DepositPlacer::new).generate(generators, chunk.blocks(), + chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.multicore(), chunk.context()); + } + + /** Every level's generators at the centre column of the chunk whose first block is {@code originX}, {@code originZ}, in level order. */ + static List generatorsAtCentre(FeatureSettings settings, int originX, int originZ) { + return settings.at(DepositSettings.class, originX + CHUNK_CENTRE, originZ + CHUNK_CENTRE).stream() + .flatMap(entry -> entry.value().generators().stream()) + .toList(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java rename to src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 796c5d103..21e944c01 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisDepositModifier.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedModifier; +import art.arcane.iris.engine.framework.EngineAssignedComponent; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositHeightDistribution; @@ -41,41 +41,37 @@ import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; -public class IrisDepositModifier extends EngineAssignedModifier { +import java.util.List; + +/** + * Places deposit clumps into one chunk for {@link DepositModule}: one per engine runtime, holding the deposit + * stream's random. Each generator gets its own random, derived from the chunk and its position in the list. + */ +public class DepositPlacer extends EngineAssignedComponent { private final RNG rng; - public IrisDepositModifier(Engine engine) { + public DepositPlacer(Engine engine) { super(engine, "Deposit"); rng = new RNG(getEngine().getSeedManager().getDeposit()); } - @Override - public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + /** Runs {@code generators}, in order, on the chunk at chunk coordinates {@code x}, {@code z}. */ + public void generate(List generators, Hunk terrain, int x, int z, boolean multicore, + ChunkContext context) { PrecisionStopwatch p = PrecisionStopwatch.start(); - generateDeposits(output, Math.floorDiv(x, 16), Math.floorDiv(z, 16), multicore, context); + generateDeposits(generators, terrain, x, z, multicore, context); getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); } - public void generateDeposits(Hunk terrain, int x, int z, boolean multicore, ChunkContext context) { - IrisRegion region = context.getRegion().get(7, 7); - IrisBiome biome = context.getBiome().get(7, 7); + private void generateDeposits(List generators, Hunk terrain, int x, int z, + boolean multicore, ChunkContext context) { BurstExecutor burst = burst().burst(multicore); long seed = x * 341873128712L + z * 132897987541L; long mask = 0; MantleChunk chunk = getEngine().getMantle().getMantle().getChunk(x, z).use(); try { - for (IrisDepositGenerator k : getDimension().getDeposits()) { - long finalSeed = seed * ++mask; - burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); - } - - for (IrisDepositGenerator k : region.getDeposits()) { - long finalSeed = seed * ++mask; - burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); - } - - for (IrisDepositGenerator k : biome.getDeposits()) { + for (IrisDepositGenerator k : generators) { long finalSeed = seed * ++mask; burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java new file mode 100644 index 000000000..dc260c18d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -0,0 +1,62 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.decorant.DecorantStages; +import art.arcane.iris.builtin.floating.FloatingStages; +import art.arcane.iris.builtin.post.PostStages; +import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:floating}: the islands of floating child biomes, their solids after smoothing and their + * decoration after the chunk's own. A thin wrapper: both stages run {@link IrisFloatingChildBiomeModifier} + * unchanged, one per engine runtime. + */ +public final class FloatingModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:floating", "Floating islands", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(FloatingStages.SOLIDS).requires(PostStages.SMOOTH).run(FloatingModule::solids); + graph.define(FloatingStages.DECORATE).requires(DecorantStages.DECORATE).run(FloatingModule::decorate); + } + + private static void solids(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + islands(chunk).modify(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + } + + private static void decorate(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + islands(chunk).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + } + + private static IrisFloatingChildBiomeModifier islands(IrisChunk chunk) { + return chunk.state(IrisFloatingChildBiomeModifier.class, IrisFloatingChildBiomeModifier::new); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java new file mode 100644 index 000000000..b36865087 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -0,0 +1,59 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.deposit.DepositStages; +import art.arcane.iris.builtin.floating.FloatingStages; +import art.arcane.iris.builtin.matter.MatterStages; +import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:matter}: copies the blocks the mantle planned for the chunk, its objects and structures, + * into it. A thin wrapper around the engine mantle's own insertion. It orders itself after deposits without + * requiring them, since deposits run only where a level declares some. + */ +public final class MatterModule implements IrisModule { + private static final String VERSION = "built-in"; + private static final int CHUNK_SHIFT = 4; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:matter", "Mantle blocks", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(MatterStages.INSERT) + .requires(FloatingStages.SOLIDS) + .softAfter(DepositStages.ORES.ref()) + .run(MatterModule::insert); + } + + private static void insert(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + if (chunk.bypassesMantleStages()) { + return; + } + chunk.engine().getMantle().insertMatter(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.blocks(), chunk.multicore()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index 4a2f8b5e8..2019f94f0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.floating.FloatingStages; import art.arcane.iris.builtin.perfection.PerfectionStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.world.dimension.IrisDimensionModeType; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.hunk.Hunk; @@ -39,7 +39,7 @@ import java.util.List; import java.util.Map; /** - * Module {@code iris:perfection}: on overworld chunks, turns ores back into the stone around them when the + * Module {@code iris:perfection}: turns ores back into the stone around them when the * dimension hides its ores, then removes decorations whose block below cannot hold them, again until none * is left, since removing one can strand the one above. */ @@ -60,16 +60,13 @@ public final class PerfectionModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(PerfectionStages.SURFACE).run(PerfectionModule::perfect); + graph.define(PerfectionStages.SURFACE).requires(FloatingStages.DECORATE).run(PerfectionModule::perfect); } private static void perfect(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); Engine engine = chunk.engine(); IrisDimension dimension = engine.getDimension(); - if (dimension.getMode().getType() != IrisDimensionModeType.OVERWORLD) { - return; - } PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); Hunk blocks = chunk.blocks(); if (dimension.isHideOresForHiddenOre()) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java new file mode 100644 index 000000000..f34ef829c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -0,0 +1,54 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.carve.CarveStages; +import art.arcane.iris.builtin.post.PostStages; +import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:post}: smooths the carved surface. A thin wrapper: the stage runs {@link IrisPostModifier} + * unchanged, one per engine runtime, except while maintenance regeneration bypasses the mantle. + */ +public final class PostModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:post", "Post-processing", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(PostStages.SMOOTH).requires(CarveStages.APPLY).run(PostModule::smooth); + } + + private static void smooth(ChunkStageContext context) { + IrisChunk chunk = IrisChunk.current(); + if (chunk.bypassesMantleStages()) { + return; + } + chunk.state(IrisPostModifier.class, IrisPostModifier::new) + .modify(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + } +} 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 index f2bab53ca..10f40aafc 100644 --- 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 @@ -33,7 +33,6 @@ import art.arcane.iris.engine.object.terrain.IrisBiomeLayerGenerator; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.deposit.IrisBiomeOres; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; @@ -225,9 +224,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @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()); - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @Desc("Define biome deposit generators that add onto the existing regional and global deposit generators") - private KList deposits = new KList<>(); @MinNumber(0) @MaxNumber(1) @Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") 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 index 899ccc241..aad10040f 100644 --- 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 @@ -35,7 +35,6 @@ import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; @@ -250,9 +249,6 @@ public class IrisDimension extends IrisRegistrant { @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; - @Required - @Desc("Define the mode of this dimension (required!)") - private IrisDimensionMode mode = new IrisDimensionMode(); @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.") @@ -281,9 +277,6 @@ public class IrisDimension extends IrisRegistrant { private boolean useMantle = true; @Desc("Prevent Leaf decay as if placed in creative mode") private boolean preventLeafDecay = false; - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @Desc("Define global deposit generators") - private KList deposits = new KList<>(); @ArrayType(min = 1, type = IrisDepositVariant.class) @Desc("Dimension-wide deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied after biome and region rules; first matching dimension rule wins.") private KList depositVariants = new KList<>(); diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java deleted file mode 100644 index fc2f39358..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionMode.java +++ /dev/null @@ -1,43 +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.framework.Engine; -import art.arcane.iris.engine.framework.EngineMode; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("dimension-mode") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a dimensional mode") -@Data -public class IrisDimensionMode { - @Desc("The dimension type") - private IrisDimensionModeType type = IrisDimensionModeType.OVERWORLD; - - public EngineMode create(Engine engine) { - return type.create(engine); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.java deleted file mode 100644 index c2a248b3c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionModeType.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.object.world.dimension; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineMode; -import art.arcane.iris.engine.mode.ModeEnclosure; -import art.arcane.iris.engine.mode.ModeIslands; -import art.arcane.iris.engine.mode.ModeOverworld; -import art.arcane.iris.engine.mode.ModeSuperFlat; -import art.arcane.iris.engine.object.annotations.Desc; - -import java.util.function.Function; - -@Desc("The type of dimension this is") -public enum IrisDimensionModeType { - @Desc("Typical dimensions. Has a fluid height, and all features of a biome based world") - OVERWORLD(ModeOverworld::new), - - @Desc("Ultra fast, but very limited in features. Only supports terrain & biomes. No decorations, mobs, objects, or anything of the sort!") - SUPERFLAT(ModeSuperFlat::new), - - @Desc("Like the nether, a ceiling & floor carved out") - ENCLOSURE(ModeEnclosure::new), - - @Desc("Floating islands of terrain") - ISLANDS(ModeIslands::new), - ; - private final Function factory; - - IrisDimensionModeType(Function factory) { - this.factory = factory; - } - - public EngineMode create(Engine e) { - return factory.apply(e); - } -} 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 index 59a08e80c..b128642a1 100644 --- 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 @@ -26,7 +26,6 @@ import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; @@ -150,9 +149,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { @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<>(); - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @Desc("Define regional deposit generators that add onto the global deposit generators") - private KList deposits = new KList<>(); @ArrayType(min = 1, type = IrisDepositVariant.class) @Desc("Deposit ore remap rules scoped to this region. Each entry declares a vertical band and a source->replacement block id map. Applied after biome rules but before dimension rules; first matching region rule wins.") private KList depositVariants = new KList<>(); From 847dba82128e50b48b8d1477332d96697f3d34b8 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 12:44:43 +0200 Subject: [PATCH 007/139] Port Iris's object, floating object and structure mantle components to built-in mantle stages The three mantle components become per-runtime workers constructed from the engine, like CaveCarving: ObjectPlacing, FloatingObjectPlacing and StructurePlacing, each with place(writer, x, z, context) and reach(). New built-in mantle stages run them: iris:objects/place (after the caves), iris:floating/objects (after objects) and iris:structure/place (after objects and floating objects). Each works out its reach from the pack when it loads, as the component's radius used to be. CarveModule no longer checks disabledComponents itself: Iris disables the cave stage's pass by its CARVED flag like any other. Studio's disabledComponents list offers the flags of Iris's own mantle stages, CARVED included again. --- README.md | 24 ++--- .../iris/builtin/floating/FloatingStages.java | 3 + .../iris/builtin/objects/ObjectStages.java | 31 +++++++ .../builtin/structure/StructureStages.java | 31 +++++++ ...ponent.java => FloatingObjectPlacing.java} | 39 ++++---- .../mantle/components/ObjectModule.java | 63 +++++++++++++ ...bjectComponent.java => ObjectPlacing.java} | 93 ++++++++++--------- .../mantle/components/StructureModule.java | 64 +++++++++++++ ...reComponent.java => StructurePlacing.java} | 69 +++++++------- .../iris/engine/modifier/CarveModule.java | 8 +- .../iris/engine/modifier/FloatingModule.java | 30 +++++- .../functions/ComponentFlagFunction.java | 27 ++---- 12 files changed, 349 insertions(+), 133 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureStages.java rename src/main/java/art/arcane/iris/engine/mantle/components/{MantleFloatingObjectComponent.java => FloatingObjectPlacing.java} (95%) create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java rename src/main/java/art/arcane/iris/engine/mantle/components/{MantleObjectComponent.java => ObjectPlacing.java} (96%) create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java rename src/main/java/art/arcane/iris/engine/mantle/components/{IrisStructureComponent.java => StructurePlacing.java} (93%) diff --git a/README.md b/README.md index f1ba758e0..daefa6d7c 100644 --- a/README.md +++ b/README.md @@ -6,18 +6,20 @@ direct dependencies on Iris internals. 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`, -`iris:vacuum`, `iris:snow`) and chunk generation, which every world runs in this order: `iris:biome`, -`iris:terrain`, `iris:carve` (a mantle stage planning caves, and a chunk stage cutting them), -`iris:post`, `iris:floating` (solids), `iris:deposit`, `iris:matter`, `iris:decorant`, `iris:floating` -(decoration), `iris:perfection` and `iris:custom`. There are no world modes any more. Their stage -constants, and the settings and output types packs may read, live in -`src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live -beside the features they replace. +`iris:vacuum`, `iris:snow`), the mantle, and chunk generation. Every mantle stage is a pass of Iris's +mantle of its own, in the stage graph's order: `iris:carve/caves`, `iris:objects/place`, +`iris:floating/objects`, `iris:structure/place`, so a pack's mantle stage can order itself after any of +them. Chunk generation then runs, in this order: `iris:biome`, `iris:terrain`, `iris:carve` (cutting the +planned caves), `iris:post`, `iris:floating` (solids), `iris:deposit`, `iris:matter`, `iris:decorant`, +`iris:floating` (decoration), `iris:perfection` and `iris:custom`. There are no world modes and no Iris +mantle components outside the stage graph any more. Their stage constants, and the settings and output +types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack +modules; their stage bodies live beside the features they replace. -`iris:biome` and `iris:deposit` (chunk stages) and the cave planning of `iris:carve` (a mantle stage) are -full ports: the module owns its logic and per-engine state. The other generation stages are thin wrappers -that run the existing actuator or modifier unchanged. Iris's object, floating object and structure mantle -components are still Iris mantle components. +`iris:biome` and `iris:deposit` (chunk stages) and every mantle stage (caves, objects, floating objects, +structures) are full ports: the module owns its logic and per-engine state, and the mantle stages work out +their reach from the pack when it loads. The other chunk stages are thin wrappers that run the existing +actuator or modifier unchanged. 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 diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java index d3deb4680..19f1282e9 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java @@ -19,10 +19,13 @@ package art.arcane.iris.builtin.floating; import com.volmit.stage.ChunkStage; +import com.volmit.stage.MantleStage; import com.volmit.stage.Stage; /** Module {@code iris:floating}: the floating islands of floating child biomes. */ public final class FloatingStages { + /** Places the objects on and under the islands into the mantle, after the dimension's other objects. */ + public static final MantleStage OBJECTS = Stage.mantle("iris:floating/objects"); /** Writes the islands' solid blocks. */ public static final ChunkStage SOLIDS = Stage.chunk("iris:floating/solids"); /** Decorates the islands' tops and bottoms once the chunk's own decoration is done. */ diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java new file mode 100644 index 000000000..9917dd1ab --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.objects; + +import com.volmit.stage.MantleStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:objects}: the objects the dimension's regions and biomes place. */ +public final class ObjectStages { + /** Places surface, cave and upper-dimension objects into the mantle, after the caves they anchor in. */ + public static final MantleStage PLACE = Stage.mantle("iris:objects/place"); + + private ObjectStages() { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureStages.java b/src/main/java/art/arcane/iris/builtin/structure/StructureStages.java new file mode 100644 index 000000000..5ea26c630 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureStages.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.structure; + +import com.volmit.stage.MantleStage; +import com.volmit.stage.Stage; + +/** Module {@code iris:structure}: Iris structures, assembled from pieces. */ +public final class StructureStages { + /** Places the structures of the dimension, its regions and biomes into the mantle, after objects and floating objects. */ + public static final MantleStage PLACE = Stage.mantle("iris:structure/place"); + + private StructureStages() { + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java similarity index 95% rename from src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java rename to src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 8a1bfc446..249c80a13 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/MantleFloatingObjectComponent.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -22,9 +22,7 @@ import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.data.cache.Cache; -import art.arcane.iris.engine.mantle.ComponentFlag; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.mantle.IrisMantleComponent; +import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; @@ -43,7 +41,6 @@ import art.arcane.iris.util.common.math.IrisBlockVector; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.flag.ReservedFlag; import art.arcane.volmlib.util.math.RNG; import java.io.File; @@ -53,23 +50,29 @@ import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; -@ComponentFlag(ReservedFlag.FLOATING_OBJECT) -public class MantleFloatingObjectComponent extends IrisMantleComponent { +/** + * Places the objects of floating child biomes on and under their islands into the mantle for + * {@link art.arcane.iris.engine.modifier.FloatingModule}. One per engine runtime. Its reach is the + * largest placement reach of any floating object the dimension's biomes can place, at least 16 blocks. + */ +public class FloatingObjectPlacing { private static final int INVERTED_PICK_ATTEMPTS = 8; private static final IrisObjectRotation ROTATION_NONE = IrisObjectRotation.of(0, 0, 0); - public MantleFloatingObjectComponent(EngineMantle engineMantle) { - super(engineMantle, ReservedFlag.FLOATING_OBJECT, 2); + private final Engine engine; + + public FloatingObjectPlacing(Engine engine) { + this.engine = engine; } - @Override - public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ + public void place(MantleWriter writer, int x, int z, ChunkContext context) { IrisComplex complex = context.getComplex(); - IrisData data = getData(); + IrisData data = engine.getData(); int minX = x << 4; int minZ = z << 4; - RNG chunkRng = new RNG(Cache.key(x, z) + seed() + 0x0FA710BEL); - FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(getEngineMantle(), context.getFloatingIslandBoundarySampler()); + RNG chunkRng = new RNG(Cache.key(x, z) + engine.getSeedManager().getMantle() + 0x0FA710BEL); + FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(engine.getMantle(), context.getFloatingIslandBoundarySampler()); FloatingIslandSample.clearChunkMemo(); @@ -543,14 +546,14 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { }; } - @Override - protected int computeRadius() { + /** How far, in blocks along X and Z, placements may write beyond their chunk. */ + public int reach() { int maxObjectExtent = 16; Map sizeCache = new HashMap<>(); Set warnedLargeObjects = new HashSet<>(); try { - IrisData data = getData(); - for (IrisBiome biome : getDimension().getReachableBiomes(this::getData)) { + IrisData data = engine.getData(); + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { KList entries = biome.getFloatingChildBiomes(); if (entries == null || entries.isEmpty()) { continue; @@ -599,7 +602,7 @@ public class MantleFloatingObjectComponent extends IrisMantleComponent { size = IrisObject.sampleSize(file); sizeCache.put(objectKey, size); } - int reach = MantleObjectComponent.calculatePlacementReach(size, placement); + int reach = ObjectPlacing.calculatePlacementReach(size, placement); if (reach > 128 && warnedLargeObjects.add(objectKey)) { IrisLogging.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java new file mode 100644 index 000000000..b1b1734fc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -0,0 +1,63 @@ +/* + * 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.carve.CarveStages; +import art.arcane.iris.builtin.objects.ObjectStages; +import art.arcane.iris.core.modules.IrisMantleChunk; +import art.arcane.iris.core.modules.IrisPackSettings; +import art.arcane.iris.engine.framework.Engine; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.config.PackSettings; +import com.volmit.stage.MantleStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle + * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work + * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. + */ +public final class ObjectModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:objects", "Objects", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(ObjectStages.PLACE).requires(CarveStages.CAVES).reach(ObjectModule::reach).run(ObjectModule::place); + } + + private static void place(MantleStageContext context) { + IrisMantleChunk chunk = IrisMantleChunk.current(); + placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + } + + private static int reach(PackSettings settings) { + return placing(IrisPackSettings.of(settings).engine()).reach(); + } + + /** The engine runtime's object placing, which {@link Engine#getObjectsAt} also asks. */ + public static ObjectPlacing placing(Engine engine) { + return engine.getGeneration().state(ObjectPlacing.class, ObjectPlacing::new); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java similarity index 96% rename from src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java rename to src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 94ccb244e..8702ababf 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/MantleObjectComponent.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -26,9 +26,6 @@ import art.arcane.iris.util.common.data.B; import art.arcane.iris.engine.data.cache.Cache; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.mantle.ComponentFlag; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.mantle.IrisMantleComponent; import art.arcane.iris.engine.mantle.MantleWriter; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.TreeBlockMaterial; @@ -55,7 +52,6 @@ import art.arcane.volmlib.util.collection.KSet; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.flag.ReservedFlag; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterStructurePOI; @@ -74,16 +70,23 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -@ComponentFlag(ReservedFlag.OBJECT) -public class MantleObjectComponent extends IrisMantleComponent { +/** + * Places the objects of the dimension's regions and biomes into the mantle for + * {@link ObjectModule}: surface, cave and upper-dimension objects, and procedural objects, one chunk at a + * time after the caves they anchor in are planned. One per engine runtime. Its reach is the largest + * placement reach of any object the dimension can place. + */ +public class ObjectPlacing { private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L; private static final int BEDROCK_CLEARANCE = 6; private static final byte LIQUID_FORCED_AIR = 3; private static final Map CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>(); private static final Set MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet(); - public MantleObjectComponent(EngineMantle engineMantle) { - super(engineMantle, ReservedFlag.OBJECT, 1); + private final Engine engine; + + public ObjectPlacing(Engine engine) { + this.engine = engine; } private static String placementMarker(IrisObject object, int id, String context) { @@ -111,21 +114,21 @@ public class MantleObjectComponent extends IrisMantleComponent { placer.setData(x, y, z, TreeBlockMaterial.of(data)); } - @Override - public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ + public void place(MantleWriter writer, int x, int z, ChunkContext context) { IrisComplex complex = context.getComplex(); boolean traceRegen = isRegenTraceThread(); - RNG rng = applyNoise(x, z, Cache.key(x, z) + seed()); + RNG rng = applyNoise(x, z, Cache.key(x, z) + engine.getSeedManager().getMantle()); int xxx = 8 + (x << 4); int zzz = 8 + (z << 4); IrisRegion region = complex.getRegionStream().get(xxx, zzz); IrisBiome surfaceBiome = complex.getTrueBiomeStream().get(xxx, zzz); - int surfaceY = getEngineMantle().getEngine().getHeight(xxx, zzz, true); + int surfaceY = engine.getHeight(xxx, zzz, true); IrisBiome caveBiome = resolveCaveObjectBiome(xxx, zzz, surfaceY, surfaceBiome); if (IrisSettings.get().getGeneral().isDebug() && (x & 31) == 0 && (z & 31) == 0) { int carvedBlocks = 0; int minY = 1; - int maxY = Math.min(getEngineMantle().getEngine().getHeight() - 1, surfaceY - 14); + int maxY = Math.min(engine.getHeight() - 1, surfaceY - 14); for (int sy = minY; sy < maxY; sy++) { if (writer.isCarved(8 + (x << 4), sy, 8 + (z << 4))) { carvedBlocks++; @@ -153,8 +156,8 @@ public class MantleObjectComponent extends IrisMantleComponent { } ObjectPlacementSummary summary = placeObjects(writer, rng, x, z, surfaceBiome, caveBiome, region, complex, traceRegen); placeProceduralObjects(writer, rng, x, z, surfaceBiome, caveBiome, region); - UpperDimensionContext upperCtx = getEngineMantle().getEngine().getUpperContext(); - IrisDimension dimension = getDimension(); + UpperDimensionContext upperCtx = engine.getUpperContext(); + IrisDimension dimension = engine.getDimension(); if (upperCtx != null && dimension.isUpperDimensionObjects()) { placeUpperObjects(writer, rng, x, z, xxx, zzz, surfaceY, upperCtx, dimension, complex, traceRegen); } @@ -183,7 +186,7 @@ public class MantleObjectComponent extends IrisMantleComponent { private IrisBiome resolveCaveObjectBiome(int x, int z, int surfaceY, IrisBiome surfaceBiome) { int legacySampleY = Math.max(1, surfaceY - 48); - IrisBiome legacyCaveBiome = getEngineMantle().getEngine().getCaveBiome(x, legacySampleY, z); + IrisBiome legacyCaveBiome = engine.getCaveBiome(x, legacySampleY, z); if (legacyCaveBiome == null) { legacyCaveBiome = surfaceBiome; } @@ -192,7 +195,7 @@ public class MantleObjectComponent extends IrisMantleComponent { IrisBiome ladderChoice = null; for (int sampleDepth : sampleDepths) { int sampleY = Math.max(1, surfaceY - sampleDepth); - IrisBiome sampled = getEngineMantle().getEngine().getCaveBiome(x, sampleY, z); + IrisBiome sampled = engine.getCaveBiome(x, sampleY, z); boolean sameSurface = sampled == surfaceBiome; if (!sameSurface && sampled != null && surfaceBiome != null) { String sampledKey = sampled.getLoadKey(); @@ -435,7 +438,7 @@ public class MantleObjectComponent extends IrisMantleComponent { IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName()) : basePlacer; int density = Math.max(1, p.getDensity()); for (int i = 0; i < density; i++) { - IrisObject variant = p.getVariantObject(getData(), rng); + IrisObject variant = p.getVariantObject(engine.getData(), rng); if (variant == null) { if (golden) { IrisLogging.debug("Goldendebug procedural pick: chunk=" + x + "," + z @@ -473,7 +476,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int zz = caveAnchor == null ? rng.i(blockZ, blockZ + 16) : caveAnchor.z(); int id = rng.i(0, Integer.MAX_VALUE); if (golden) { - KList pool = p.getVariantObjects(getData()); + KList pool = p.getVariantObjects(engine.getData()); IrisLogging.debug("Goldendebug procedural pick: chunk=" + x + "," + z + " placement=" + p.getName() + " densityIndex=" + i @@ -521,7 +524,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (treePlacement && marker != null) { writeTreeMaterial(placer, b.getX(), b.getY(), b.getZ(), data); } - }, null, getData()); + }, null, engine.getData()); } if (golden) { IrisLogging.debug("Goldendebug procedural result: chunk=" + x + "," + z @@ -582,7 +585,7 @@ public class MantleObjectComponent extends IrisMantleComponent { underwater, writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), candidateY, - getDimension().getCaveLavaHeight())) { + engine.getDimension().getCaveLavaHeight())) { continue; } return new CavePlacementAnchor(candidateX, candidateY, candidateZ); @@ -629,7 +632,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { transaction.setData(block.getX(), block.getY(), block.getZ(), MatterStructurePOI.BURIED_TREASURE); } - }, null, getData()); + }, null, engine.getData()); if (result < 0) { transaction.discard(); return new ContainedPlacementResult(result, CaveObjectPlacementTransaction.CommitResult.EMPTY); @@ -655,7 +658,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int rejected = 0; int nullObjects = 0; int errors = 0; - int density = objectPlacement.getDensity(rng, x, z, getData()); + int density = objectPlacement.getDensity(rng, x, z, engine.getData()); boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ); for (int i = 0; i < density; i++) { @@ -699,7 +702,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) { writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); } - }, null, getData()); + }, null, engine.getData()); if (result >= 0) { placed++; @@ -746,7 +749,6 @@ public class MantleObjectComponent extends IrisMantleComponent { if (expectedCaveBiomeKey == null) { return false; } - Engine engine = getEngineMantle().getEngine(); IrisBiome at = engine.getCaveBiome(x, y, z); IrisBiome surface = engine.getSurfaceBiome(x, z); return caveAnchorBiomeConflicts(at, surface, expectedCaveBiomeKey); @@ -788,7 +790,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int errors = 0; int minX = chunkX << 4; int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, getData()); + int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) { anchorMode = IrisCaveAnchorMode.CEILING; @@ -1025,11 +1027,11 @@ public class MantleObjectComponent extends IrisMantleComponent { boolean traceRegen, String scope ) { - int chunkHeight = getEngineMantle().getEngine().getHeight(); + int chunkHeight = engine.getHeight(); int upperGap = dimension.getUpperDimensionGap(); int minX = chunkX << 4; int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, getData()); + int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); for (int i = 0; i < density; i++) { IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); @@ -1039,7 +1041,7 @@ public class MantleObjectComponent extends IrisMantleComponent { int xx = rng.i(minX, minX + 16); int zz = rng.i(minZ, minZ + 16); - int columnLowerSurfaceY = getEngineMantle().getEngine().getHeight(xx, zz, true); + int columnLowerSurfaceY = engine.getHeight(xx, zz, true); int rawUpperSurface = upperCtx.getUpperSurfaceY(xx, zz); int upperSurfaceY = Math.max(rawUpperSurface, columnLowerSurfaceY + upperGap); if (upperSurfaceY >= chunkHeight - 2) { @@ -1073,7 +1075,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); } - }, null, getData()); + }, null, engine.getData()); if (traceRegen) { IrisLogging.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ @@ -1164,7 +1166,7 @@ public class MantleObjectComponent extends IrisMantleComponent { /** Dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ private IrisObjectPlacement applyDimensionSurfaceSupport(IrisObjectPlacement placement) { - IrisDimension dimension = getDimension(); + IrisDimension dimension = engine.getDimension(); boolean require = placement.isRequireSurfaceSupport() && dimension.isRequireObjectSurfaceSupport(); int buffer = Math.max(placement.getSurfaceSupportBuffer(), dimension.getObjectSurfaceSupportBuffer()); if (require == placement.isRequireSurfaceSupport() && buffer == placement.getSurfaceSupportBuffer()) { @@ -1249,7 +1251,7 @@ public class MantleObjectComponent extends IrisMantleComponent { } private KList scanCaveAnchorColumn(MantleWriter writer, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z, CaveAnchorCache anchorCache) { - int height = getEngineMantle().getEngine().getHeight(); + int height = engine.getHeight(); int step = Math.max(1, anchorScanStep); int surfaceY = anchorCache.getSurfaceHeight(x, z); int maxAnchorExclusive = caveAnchorScanUpperBound(height, surfaceY, objectMinDepthBelowSurface); @@ -1316,7 +1318,7 @@ public class MantleObjectComponent extends IrisMantleComponent { } private IrisCaveProfile resolveCaveProfile(IrisCaveProfile preferred, IrisCaveProfile secondary) { - IrisCaveProfile dimensionProfile = getDimension().getCaveProfile(); + IrisCaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); if (preferred != null && preferred.isEnabled()) { return preferred; } @@ -1416,8 +1418,8 @@ public class MantleObjectComponent extends IrisMantleComponent { @BlockCoordinates private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { Set f = new KSet<>(); - for (int i = 0; i < objectPlacement.getDensity(rng, x, z, getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(getComplex(), rng)); + for (int i = 0; i < objectPlacement.getDensity(rng, x, z, engine.getData()); i++) { + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng)); if (v == null) { continue; } @@ -1430,9 +1432,9 @@ public class MantleObjectComponent extends IrisMantleComponent { public Set guess(int x, int z) { // todo The guess doesnt bring into account that the placer may return -1 - RNG rng = applyNoise(x, z, Cache.key(x, z) + seed()); - IrisBiome biome = getEngineMantle().getEngine().getSurfaceBiome((x << 4) + 8, (z << 4) + 8); - IrisRegion region = getEngineMantle().getEngine().getRegion((x << 4) + 8, (z << 4) + 8); + RNG rng = applyNoise(x, z, Cache.key(x, z) + engine.getSeedManager().getMantle()); + IrisBiome biome = engine.getSurfaceBiome((x << 4) + 8, (z << 4) + 8); + IrisRegion region = engine.getRegion((x << 4) + 8, (z << 4) + 8); Set v = new KSet<>(); for (IrisObjectPlacement i : biome.getSurfaceObjects()) { if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { @@ -1449,19 +1451,20 @@ public class MantleObjectComponent extends IrisMantleComponent { return v; } - protected int computeRadius() { - IrisDimension dimension = getDimension(); + /** How far, in blocks along X and Z, placements may write beyond their chunk. */ + public int reach() { + IrisDimension dimension = engine.getDimension(); KMap sizeCache = new KMap<>(); KSet warnedLargeObjects = new KSet<>(); int radius = 0; - for (IrisRegion region : dimension.getAllRegions(this::getData)) { + for (IrisRegion region : dimension.getAllRegions(engine)) { if (region == null) { continue; } radius = Math.max(radius, computePlacementRadius(region.getObjects(), sizeCache, warnedLargeObjects)); radius = Math.max(radius, computeProceduralRadius(region.getProceduralObjects())); } - for (IrisBiome biome : dimension.getReachableBiomes(this::getData)) { + for (IrisBiome biome : dimension.getReachableBiomes(engine)) { if (biome == null) { continue; } @@ -1510,7 +1513,7 @@ public class MantleObjectComponent extends IrisMantleComponent { if (placement == null) { continue; } - KList variants = placement.getVariantObjects(getData()); + KList variants = placement.getVariantObjects(engine.getData()); if (variants == null) { continue; } @@ -1578,7 +1581,7 @@ public class MantleObjectComponent extends IrisMantleComponent { private IrisBlockVector loadObjectSize(KMap sizeCache, String objectKey) { return sizeCache.computeIfAbsent(objectKey, k -> { try { - return IrisObject.sampleSize(getData().getObjectLoader().findFile(objectKey)); + return IrisObject.sampleSize(engine.getData().getObjectLoader().findFile(objectKey)); } catch (IOException e) { IrisLogging.reportError(e); } @@ -1641,7 +1644,7 @@ public class MantleObjectComponent extends IrisMantleComponent { return surfaceY; } - surfaceY = getEngineMantle().getEngine().getHeight(x, z); + surfaceY = engine.getHeight(x, z); surfaceHeights.put(columnKey, surfaceY); return surfaceY; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java new file mode 100644 index 000000000..5915045a2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -0,0 +1,64 @@ +/* + * 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.FloatingStages; +import art.arcane.iris.builtin.objects.ObjectStages; +import art.arcane.iris.builtin.structure.StructureStages; +import art.arcane.iris.core.modules.IrisMantleChunk; +import art.arcane.iris.core.modules.IrisPackSettings; +import art.arcane.iris.engine.framework.Engine; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.config.PackSettings; +import com.volmit.stage.MantleStageContext; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear + * where they intersect, and after floating objects. A port of what was Iris's structure mantle component, its + * work done by {@link StructurePlacing}, one per engine runtime. Its reach is the pack's largest structure. + */ +public final class StructureModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:structure", "Structures", VERSION); + } + + @Override + public void install(StageGraph graph) { + graph.define(StructureStages.PLACE).requires(ObjectStages.PLACE).softAfter(FloatingStages.OBJECTS.ref()) + .reach(StructureModule::reach).run(StructureModule::place); + } + + private static void place(MantleStageContext context) { + IrisMantleChunk chunk = IrisMantleChunk.current(); + placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + } + + private static int reach(PackSettings settings) { + return placing(IrisPackSettings.of(settings).engine()).reach(); + } + + private static StructurePlacing placing(Engine engine) { + return engine.getGeneration().state(StructurePlacing.class, StructurePlacing::new); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java similarity index 93% rename from src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java rename to src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java index 40edd8af8..fede31277 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IrisStructureComponent.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -27,9 +27,7 @@ import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.framework.StructurePlacementScope; import art.arcane.iris.engine.framework.StructurePlacementMarker; import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.mantle.ComponentFlag; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.mantle.IrisMantleComponent; +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; @@ -56,7 +54,6 @@ 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.mantle.flag.ReservedFlag; import art.arcane.volmlib.util.math.RNG; import it.unimi.dsi.fastutil.longs.Long2IntMap; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; @@ -65,19 +62,25 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; -@ComponentFlag(ReservedFlag.JIGSAW) -public class IrisStructureComponent extends IrisMantleComponent { +/** + * 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); - public IrisStructureComponent(EngineMantle engineMantle) { - super(engineMantle, ReservedFlag.JIGSAW, 3); + private final Engine engine; + + public StructurePlacing(Engine engine) { + this.engine = engine; } - @Override + /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ @ChunkCoordinates - public void generateLayer(MantleWriter writer, int x, int z, ChunkContext context) { + public void place(MantleWriter writer, int x, int z, ChunkContext context) { for (IrisStructurePlacement placement : StructurePlacementScope.placementsAt( - getEngineMantle().getEngine(), x, z)) { + engine, x, z)) { if (!placement.hasIrisStructures()) { continue; } @@ -88,7 +91,7 @@ public class IrisStructureComponent extends IrisMantleComponent { @ChunkCoordinates private void placeFromPlacement(MantleWriter writer, IrisStructurePlacement placement, int cx, int cz) { IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement( - getEngineMantle().getEngine(), placement, cx, cz); + engine, placement, cx, cz); if (resolved == null) { return; } @@ -173,7 +176,7 @@ public class IrisStructureComponent extends IrisMantleComponent { boolean surfaceStructure) { IrisMaterialPalette palette = Objects.requireNonNull( settings.getPalette(), "Structure stilt palette must not be null"); - int mantleOffset = getEngineMantle().getEngine().getMinHeight(); + int mantleOffset = engine.getMinHeight(); int maxDepth = Math.max(1, settings.getMaxDepth()); for (Long2IntMap.Entry column : columns.long2IntEntrySet()) { int worldX = StructureFoundationPlanner.unpackX(column.getLongKey()); @@ -184,7 +187,7 @@ public class IrisStructureComponent extends IrisMantleComponent { if (foundationState == null || !foundationState.isSolid()) { continue; } - int terrainHeight = getEngineMantle().trueHeight(worldX, worldZ); + int terrainHeight = engine.getMantle().trueHeight(worldX, worldZ); int groundY = StructureFoundationPlanner.findGroundY( foundationY, maxDepth, 0, y -> { @@ -203,7 +206,7 @@ public class IrisStructureComponent extends IrisMantleComponent { } StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> { writeFoundationSupport( - writer, palette, rng, getData(), worldX, y, worldZ, mantleOffset); + writer, palette, rng, engine.getData(), worldX, y, worldZ, mantleOffset); }); } } @@ -259,14 +262,14 @@ public class IrisStructureComponent extends IrisMantleComponent { int maxX = bounds[3] + pad; int maxY = bounds[4] + Math.max(0, terrain.getCeilingPadding()); int maxZ = bounds[5] + pad; - int worldMin = getEngineMantle().getEngine().getMinHeight() + 1; - int worldMax = getEngineMantle().getEngine().getMinHeight() + getEngineMantle().getEngine().getHeight() - 1; + 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 = getEngineMantle().getEngine().getMinHeight(); + 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++) { @@ -287,9 +290,9 @@ public class IrisStructureComponent extends IrisMantleComponent { int head = Math.max(0, terrain.getCeilingPadding()); int floorCut = Math.max(0, terrain.getFloorPadding()); double strength = terrain.resolvedErosionStrength(); - int mantleOffset = getEngineMantle().getEngine().getMinHeight(); - int worldMin = getEngineMantle().getEngine().getMinHeight() + 1; - int worldMax = getEngineMantle().getEngine().getMinHeight() + getEngineMantle().getEngine().getHeight() - 1; + int mantleOffset = engine.getMinHeight(); + int worldMin = engine.getMinHeight() + 1; + int worldMax = engine.getMinHeight() + engine.getHeight() - 1; int upExtension = shape.maximumCeilingExtension(head, strength); if (shape == IrisStructureCarveShape.BOX) { @@ -309,7 +312,7 @@ public class IrisStructureComponent extends IrisMantleComponent { CNG blob = null; CNG roll = null; if (eroded) { - RNG noiseRng = new RNG(seed() + Cache.key(bounds[0], bounds[2])); + RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + Cache.key(bounds[0], bounds[2])); blob = CNG.signature(noiseRng); roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17)); } @@ -404,8 +407,8 @@ public class IrisStructureComponent extends IrisMantleComponent { } private void clearIntersectingObjectTrees(MantleWriter writer, IrisStructureLocator.ResolvedPlacement resolved) { - int mantleOffset = getEngineMantle().getEngine().getMinHeight(); - int worldHeight = getEngineMantle().getEngine().getHeight(); + int mantleOffset = engine.getMinHeight(); + int worldHeight = engine.getHeight(); Map intersectingObjects = new HashMap<>(); for (PlacedStructurePiece piece : resolved.pieces()) { for (IrisBlockVector local : piece.getObject().getBlocks().keys()) { @@ -450,7 +453,7 @@ public class IrisStructureComponent extends IrisMantleComponent { if (decoded == null) { return; } - IrisObject object = getData().load(IrisObject.class, decoded.objectKey(), false); + IrisObject object = engine.getData().load(IrisObject.class, decoded.objectKey(), false); if (object == null) { return; } @@ -543,7 +546,7 @@ public class IrisStructureComponent extends IrisMantleComponent { if (mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) { config.setForcePlace(true); } - int placeY = (y == -1) ? -1 : y - getEngineMantle().getEngine().getMinHeight(); + 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( @@ -552,7 +555,7 @@ public class IrisStructureComponent extends IrisMantleComponent { if (marker != null && shouldWriteStructureMarker(state)) { writer.setData(position.getX(), position.getY(), position.getZ(), marker); } - }, null, getData()); + }, null, engine.getData()); } static boolean shouldWriteStructureMarker(PlatformBlockState state) { @@ -578,15 +581,15 @@ public class IrisStructureComponent extends IrisMantleComponent { return StructurePlacementMarker.encodeStructure(objectKey, placementId, structureKey); } - @Override - protected int computeRadius() { - IrisDimension dimension = getDimension(); + /** 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(this::getData)) { + for (IrisRegion region : dimension.getAllRegions(engine)) { maxBlocks = Math.max(maxBlocks, maxBlocksFrom(region.getStructures())); } - for (IrisBiome biome : dimension.getReachableBiomes(this::getData)) { + for (IrisBiome biome : dimension.getReachableBiomes(engine)) { maxBlocks = Math.max(maxBlocks, maxBlocksFrom(biome.getStructures())); } maxBlocks = Math.max(maxBlocks, maxBlocksFrom(dimension.getStructures())); @@ -605,7 +608,7 @@ public class IrisStructureComponent extends IrisMantleComponent { || terrain.resolvedMode() == IrisStructureTerrainMode.BORE ? Math.max(0, terrain.getHorizontalPadding()) : 0; for (String key : placement.getStructures()) { - IrisStructure structure = getData().load(IrisStructure.class, key, false); + IrisStructure structure = engine.getData().load(IrisStructure.class, key, false); if (structure != null) { max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 476645917..0e6ce0642 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -24,7 +24,6 @@ import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.engine.mantle.components.CaveCarving; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.volmlib.util.mantle.flag.ReservedFlag; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; @@ -71,8 +70,11 @@ public final class CarveModule implements IrisModule { chunk.blocks(), chunk.multicore(), chunk.context()); } - /** A dimension turns carving off with {@code carvingEnabled}, or by listing {@code CARVED} in {@code disabledComponents}. */ + /** + * A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents} + * also does: Iris then skips this stage's mantle pass like any disabled component. + */ private static boolean carves(IrisDimension dimension) { - return dimension.isCarvingEnabled() && !dimension.getDisabledComponents().contains(ReservedFlag.CARVED); + return dimension.isCarvingEnabled(); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index dc260c18d..f63346186 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -20,17 +20,26 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.decorant.DecorantStages; import art.arcane.iris.builtin.floating.FloatingStages; +import art.arcane.iris.builtin.objects.ObjectStages; import art.arcane.iris.builtin.post.PostStages; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.core.modules.IrisMantleChunk; +import art.arcane.iris.core.modules.IrisPackSettings; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.config.PackSettings; import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; /** - * Module {@code iris:floating}: the islands of floating child biomes, their solids after smoothing and their - * decoration after the chunk's own. A thin wrapper: both stages run {@link IrisFloatingChildBiomeModifier} - * unchanged, one per engine runtime. + * Module {@code iris:floating}: the islands of floating child biomes, their objects in the mantle after the + * dimension's other objects, their solids after smoothing and their decoration after the chunk's own. The + * mantle stage is a port of what was Iris's floating object mantle component, its work done by + * {@link FloatingObjectPlacing}, whose reach is the pack's largest floating object placement. The chunk + * stages are a thin wrapper: both run {@link IrisFloatingChildBiomeModifier} unchanged, one per engine runtime. */ public final class FloatingModule implements IrisModule { private static final String VERSION = "built-in"; @@ -42,10 +51,21 @@ public final class FloatingModule implements IrisModule { @Override public void install(StageGraph graph) { + graph.define(FloatingStages.OBJECTS).softAfter(ObjectStages.PLACE.ref()).reach(FloatingModule::objectReach) + .run(FloatingModule::objects); graph.define(FloatingStages.SOLIDS).requires(PostStages.SMOOTH).run(FloatingModule::solids); graph.define(FloatingStages.DECORATE).requires(DecorantStages.DECORATE).run(FloatingModule::decorate); } + private static void objects(MantleStageContext context) { + IrisMantleChunk chunk = IrisMantleChunk.current(); + objectPlacing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + } + + private static int objectReach(PackSettings settings) { + return objectPlacing(IrisPackSettings.of(settings).engine()).reach(); + } + private static void solids(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); islands(chunk).modify(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); @@ -56,6 +76,10 @@ public final class FloatingModule implements IrisModule { islands(chunk).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); } + private static FloatingObjectPlacing objectPlacing(Engine engine) { + return engine.getGeneration().state(FloatingObjectPlacing.class, FloatingObjectPlacing::new); + } + private static IrisFloatingChildBiomeModifier islands(IrisChunk chunk) { return chunk.state(IrisFloatingChildBiomeModifier.class, IrisFloatingChildBiomeModifier::new); } 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 index eabc3086e..981ccd8e3 100644 --- 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 @@ -1,17 +1,16 @@ 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.iris.engine.mantle.ComponentFlag; -import art.arcane.iris.engine.mantle.MantleComponent; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.io.JarScanner; import art.arcane.volmlib.util.mantle.flag.MantleFlag; -import java.util.Objects; - +/** + * What studio offers for a dimension's {@code disabledComponents}: the flags of Iris's own mantle stages, such as + * {@code CARVED} for caves. Pack mantle stages are left out: their flags follow their position in the pack's + * stage order, so a name written today could disable another stage once the pack changes. + */ public class ComponentFlagFunction implements ListFunction> { @Override public String key() { @@ -25,18 +24,6 @@ public class ComponentFlagFunction implements ListFunction> { @Override public KList apply(IrisData data) { - var engine = data.getEngine(); - if (engine != null) return engine.getMantle().getComponentFlags().toStringList(); - JarScanner scanner = new JarScanner(IrisPlatforms.get().pluginJar(), "art.arcane.iris.engine.mantle.components"); - J.attempt(scanner::scan); - return scanner.getClasses() - .stream() - .filter(c -> c.isAnnotationPresent(ComponentFlag.class)) - .filter(MantleComponent.class::isAssignableFrom) - .map(c -> c.getDeclaredAnnotation(ComponentFlag.class)) - .filter(Objects::nonNull) - .map(ComponentFlag::value) - .map(MantleFlag::toString) - .collect(KList.collector()); + return MantleStageFlags.builtIn().stream().map(MantleFlag::toString).collect(KList.collector()); } } From 544a7651372c61ab53a09c143a5431ddab0ac700 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 12:49:37 +0200 Subject: [PATCH 008/139] Describe disabledComponents by the mantle flags studio offers --- .../iris/engine/object/world/dimension/IrisDimension.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index aad10040f..8d965ce32 100644 --- 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 @@ -306,7 +306,7 @@ public class IrisDimension extends IrisRegistrant { private int caveLavaHeight = 8; @RegistryListFunction(ComponentFlagFunction.class) @ArrayType(type = String.class) - @Desc("Collection of disabled components") + @Desc("Mantle passes to skip in this dimension, by flag: CARVED (caves), OBJECT (objects), FLOATING_OBJECT (objects on floating islands) or JIGSAW (structures).") private KList disabledComponents = new KList<>(); public int getMaxHeight() { From dc07dafa1edbb8785ab1b3b4c936089e97aaf68f Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:09:03 +0200 Subject: [PATCH 009/139] Let disabledComponents name pack mantle stages by id and take plain strings --- .../annotations/functions/ComponentFlagFunction.java | 7 ++++--- .../iris/engine/object/world/dimension/IrisDimension.java | 5 ++--- 2 files changed, 6 insertions(+), 6 deletions(-) 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 index 981ccd8e3..f4d2abf51 100644 --- 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 @@ -8,8 +8,7 @@ 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. Pack mantle stages are left out: their flags follow their position in the pack's - * stage order, so a name written today could disable another stage once the pack changes. + * {@code CARVED} for caves, then the ids of the pack's mantle stages. */ public class ComponentFlagFunction implements ListFunction> { @Override @@ -24,6 +23,8 @@ public class ComponentFlagFunction implements ListFunction> { @Override public KList apply(IrisData data) { - return MantleStageFlags.builtIn().stream().map(MantleFlag::toString).collect(KList.collector()); + 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/world/dimension/IrisDimension.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java index 8d965ce32..206b1d1ee 100644 --- 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 @@ -70,7 +70,6 @@ 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.mantle.flag.MantleFlag; import art.arcane.volmlib.util.math.Position2; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.util.project.noise.CNG; @@ -306,8 +305,8 @@ public class IrisDimension extends IrisRegistrant { private int caveLavaHeight = 8; @RegistryListFunction(ComponentFlagFunction.class) @ArrayType(type = String.class) - @Desc("Mantle passes to skip in this dimension, by flag: CARVED (caves), OBJECT (objects), FLOATING_OBJECT (objects on floating islands) or JIGSAW (structures).") - private KList disabledComponents = new KList<>(); + @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(); From 991a2d133a69890cca5aca08ebc48e6e829a49ce Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:18:00 +0200 Subject: [PATCH 010/139] Port terrain shaping into the iris:terrain module and delete the terrain actuator --- .../actuator/IrisTerrainNormalActuator.java | 261 ------------------ .../iris/engine/actuator/TerrainModule.java | 228 ++++++++++++++- 2 files changed, 224 insertions(+), 265 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java diff --git a/src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java b/src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java deleted file mode 100644 index 879772ed7..000000000 --- a/src/main/java/art/arcane/iris/engine/actuator/IrisTerrainNormalActuator.java +++ /dev/null @@ -1,261 +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.actuator; - -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedActuator; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.context.ChunkedDataCache; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import lombok.Getter; - -public class IrisTerrainNormalActuator extends EngineAssignedActuator { - private static final PlatformBlockState AIR = B.getState("AIR"); - private static final PlatformBlockState BEDROCK = B.getState("BEDROCK"); - private static final PlatformBlockState LAVA = B.getState("LAVA"); - private static final PlatformBlockState GLASS = B.getState("GLASS"); - private static final PlatformBlockState CAVE_AIR = B.getState("CAVE_AIR"); - @Getter - private final RNG rng; - @Getter - private int lastBedrock = -1; - - public IrisTerrainNormalActuator(Engine engine) { - super(engine, "Terrain"); - rng = new RNG(engine.getSeedManager().getTerrain()); - } - - @BlockCoordinates - @Override - public void onActuate(int x, int z, Hunk h, boolean multicore, ChunkContext context) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - - for (int xf = 0; xf < h.getWidth(); xf++) { - terrainSliver(x, z, xf, h, context); - } - - getEngine().getMetrics().getTerrain().put(p.getMilliseconds()); - } - - /** - * This is calling 1/16th of a chunk x/z slice. It is a plane from sky to bedrock 1 thick in the x direction. - * - * @param x the chunk x in blocks - * @param z the chunk z in blocks - * @param xf the current x slice - * @param h the blockdata - */ - @BlockCoordinates - public void terrainSliver(int x, int z, int xf, Hunk h, ChunkContext context) { - terrainSliverOptimized(x, z, xf, h, context); - } - - @BlockCoordinates - private void terrainSliverOptimized(int x, int z, int xf, Hunk h, ChunkContext context) { - int chunkHeight = h.getHeight(); - int chunkDepth = h.getDepth(); - IrisDimension dimension = getDimension(); - IrisData data = getData(); - IrisComplex complex = getComplex(); - RNG localRng = rng; - int fluidHeight = dimension.getFluidHeight(); - int clampedFluidHeight = Math.min(chunkHeight, fluidHeight); - boolean bedrockEnabled = dimension.isBedrock(); - boolean hideOres = dimension.isHideOresForHiddenOre(); - ChunkedDataCache biomeCache = context.getBiome(); - ChunkedDataCache regionCache = context.getRegion(); - ChunkedDataCache fluidCache = context.getFluid(); - ChunkedDataCache rockCache = context.getRock(); - int realX = xf + x; - UpperDimensionContext upperContext = getEngine().getUpperContext(); - // Dimension-level ore lookups are chunk-invariant; resolving them per column paid - // four accessor chains times 256 per chunk for constants. - KList dimensionSurfaceOres = hideOres ? null : dimension.getSurfaceOreGenerators(); - KList dimensionUndergroundOres = hideOres ? null : dimension.getUndergroundOreGenerators(); - IrisOreGeneratorBounds dimensionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getSurfaceOreGeneratorBounds(); - IrisOreGeneratorBounds dimensionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getUndergroundOreGeneratorBounds(); - - for (int zf = 0; zf < chunkDepth; zf++) { - int realZ = zf + z; - IrisBiome biome = biomeCache.get(xf, zf); - IrisRegion region = regionCache.get(xf, zf); - int he = Math.min(chunkHeight, context.getRoundedHeight(xf, zf)); - int hf = Math.max(clampedFluidHeight, he); - if (hf < 0) { - continue; - } - - int topY = Math.min(hf, chunkHeight - 1); - PlatformBlockState fluid = fluidCache.get(xf, zf); - PlatformBlockState rock = rockCache.get(xf, zf); - PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ); - KList biomeSurfaceOres = hideOres ? null : biome.getSurfaceOreGenerators(); - KList regionSurfaceOres = hideOres ? null : region.getSurfaceOreGenerators(); - KList biomeUndergroundOres = hideOres ? null : biome.getUndergroundOreGenerators(); - KList regionUndergroundOres = hideOres ? null : region.getUndergroundOreGenerators(); - IrisOreGeneratorBounds biomeSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getSurfaceOreGeneratorBounds(); - IrisOreGeneratorBounds regionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getSurfaceOreGeneratorBounds(); - IrisOreGeneratorBounds biomeUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getUndergroundOreGeneratorBounds(); - IrisOreGeneratorBounds regionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getUndergroundOreGeneratorBounds(); - boolean hasSurfaceOres = biomeSurfaceOreBounds.hasOres() || regionSurfaceOreBounds.hasOres() || dimensionSurfaceOreBounds.hasOres(); - boolean hasUndergroundOres = biomeUndergroundOreBounds.hasOres() || regionUndergroundOreBounds.hasOres() || dimensionUndergroundOreBounds.hasOres(); - KList blocks = null; - KList fblocks = null; - - for (int i = topY; i >= 0; i--) { - if (i == 0 && bedrockEnabled) { - h.setRaw(xf, i, zf, BEDROCK); - lastBedrock = i; - continue; - } - - PlatformBlockState ore = null; - if (hasSurfaceOres) { - if (biomeSurfaceOreBounds.contains(i)) { - ore = generateOres(biomeSurfaceOres, realX, i, realZ, localRng, data); - } - if (ore == null && regionSurfaceOreBounds.contains(i)) { - ore = generateOres(regionSurfaceOres, realX, i, realZ, localRng, data); - } - if (ore == null && dimensionSurfaceOreBounds.contains(i)) { - ore = generateOres(dimensionSurfaceOres, realX, i, realZ, localRng, data); - } - } - if (ore != null) { - h.setRaw(xf, i, zf, ore); - continue; - } - - if (i > he && i <= hf) { - int fdepth = hf - i; - if (fblocks == null) { - fblocks = biome.generateSeaLayers(realX, realZ, localRng, hf - he, data); - } - - if (fblocks.hasIndex(fdepth)) { - h.setRaw(xf, i, zf, fblocks.get(fdepth)); - } else { - h.setRaw(xf, i, zf, fluid); - } - continue; - } - - if (i <= he) { - int depth = he - i; - if (depth == 0 && mappedSurfaceBlock != null) { - h.setRaw(xf, i, zf, mappedSurfaceBlock); - continue; - } - if (blocks == null) { - blocks = biome.generateLayers(dimension, realX, realZ, localRng, he, he, data, complex); - } - - if (blocks.hasIndex(depth)) { - h.setRaw(xf, i, zf, blocks.get(depth)); - continue; - } - - if (hasUndergroundOres) { - if (biomeUndergroundOreBounds.contains(i)) { - ore = generateOres(biomeUndergroundOres, realX, i, realZ, localRng, data); - } - if (ore == null && regionUndergroundOreBounds.contains(i)) { - ore = generateOres(regionUndergroundOres, realX, i, realZ, localRng, data); - } - if (ore == null && dimensionUndergroundOreBounds.contains(i)) { - ore = generateOres(dimensionUndergroundOres, realX, i, realZ, localRng, data); - } - } - - if (ore != null) { - h.setRaw(xf, i, zf, ore); - } else { - h.setRaw(xf, i, zf, rock); - } - } - } - - if (upperContext != null) { - int rawUpperSurface = upperContext.getUpperSurfaceY(realX, realZ); - int upperGap = dimension.getUpperDimensionGap(); - int upperSurfaceY = Math.max(rawUpperSurface, he + upperGap); - - if (upperSurfaceY < chunkHeight - 1) { - IrisBiome upperBiome = upperContext.getUpperBiome(realX, realZ); - PlatformBlockState upperRock = upperContext.getRockBlock(realX, realZ); - PlatformBlockState upperMappedSurface = upperContext.getSurfaceBlock(realX, realZ); - int upperThickness = chunkHeight - 1 - upperSurfaceY; - KList upperBlocks = upperBiome != null - ? upperBiome.generateLayers(upperContext.getDimension(), - realX, realZ, localRng, upperThickness, upperThickness, - upperContext.getData(), complex) - : null; - - for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { - if (y == chunkHeight - 1 && bedrockEnabled) { - h.setRaw(xf, y, zf, BEDROCK); - continue; - } - if (y == upperSurfaceY && upperMappedSurface != null) { - h.setRaw(xf, y, zf, upperMappedSurface); - continue; - } - int depthFromFace = y - upperSurfaceY; - if (upperBlocks != null && upperBlocks.hasIndex(depthFromFace)) { - h.setRaw(xf, y, zf, upperBlocks.get(depthFromFace)); - } else { - h.setRaw(xf, y, zf, upperRock); - } - } - } - } - } - } - - private PlatformBlockState generateOres(KList oreGenerators, int x, int y, int z, RNG rng, IrisData data) { - if (oreGenerators == null || oreGenerators.isEmpty()) { - return null; - } - - int oreCount = oreGenerators.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = oreGenerators.get(oreIndex); - PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); - if (ore != null) { - return ore; - } - } - - return null; - } -} diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 9bc017a6b..7b9812d60 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -19,15 +19,34 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.terrain.TerrainStages; +import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.context.ChunkedDataCache; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; /** - * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. A thin wrapper: the stage runs - * {@link IrisTerrainNormalActuator} unchanged, one per engine runtime. + * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up + * to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and + * biome replacing blocks on the way and the upper dimension's ground filled in from the top. */ public final class TerrainModule implements IrisModule { private static final String VERSION = "built-in"; @@ -44,7 +63,208 @@ public final class TerrainModule implements IrisModule { private static void shape(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - chunk.state(IrisTerrainNormalActuator.class, IrisTerrainNormalActuator::new) - .actuate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + chunk.state(TerrainShaper.class, TerrainShaper::new).shape(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); + } + + /** What shaping terrain keeps for one engine runtime: the terrain stream's random. */ + static final class TerrainShaper { + private static final PlatformBlockState BEDROCK = B.getState("BEDROCK"); + + private final Engine engine; + private final RNG rng; + + TerrainShaper(Engine engine) { + this.engine = engine; + this.rng = new RNG(engine.getSeedManager().getTerrain()); + } + + /** Fills the 16 x 16 columns of the chunk whose first block is {@code originX}, {@code originZ}, one slice along x at a time. */ + @BlockCoordinates + void shape(int originX, int originZ, Hunk blocks, ChunkContext context) { + PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); + for (int sliceX = 0; sliceX < blocks.getWidth(); sliceX++) { + shapeSliver(originX, originZ, sliceX, blocks, context); + } + engine.getMetrics().getTerrain().put(stopwatch.getMilliseconds()); + } + + /** One plane from the sky to bedrock, one block thick along x. */ + @BlockCoordinates + private void shapeSliver(int x, int z, int xf, Hunk h, ChunkContext context) { + int chunkHeight = h.getHeight(); + int chunkDepth = h.getDepth(); + IrisDimension dimension = engine.getDimension(); + IrisData data = engine.getData(); + IrisComplex complex = engine.getComplex(); + RNG localRng = rng; + int fluidHeight = dimension.getFluidHeight(); + int clampedFluidHeight = Math.min(chunkHeight, fluidHeight); + boolean bedrockEnabled = dimension.isBedrock(); + boolean hideOres = dimension.isHideOresForHiddenOre(); + ChunkedDataCache biomeCache = context.getBiome(); + ChunkedDataCache regionCache = context.getRegion(); + ChunkedDataCache fluidCache = context.getFluid(); + ChunkedDataCache rockCache = context.getRock(); + int realX = xf + x; + UpperDimensionContext upperContext = engine.getUpperContext(); + // Dimension-level ore lookups are chunk-invariant; resolving them per column paid + // four accessor chains times 256 per chunk for constants. + KList dimensionSurfaceOres = hideOres ? null : dimension.getSurfaceOreGenerators(); + KList dimensionUndergroundOres = hideOres ? null : dimension.getUndergroundOreGenerators(); + IrisOreGeneratorBounds dimensionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getSurfaceOreGeneratorBounds(); + IrisOreGeneratorBounds dimensionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getUndergroundOreGeneratorBounds(); + + for (int zf = 0; zf < chunkDepth; zf++) { + int realZ = zf + z; + IrisBiome biome = biomeCache.get(xf, zf); + IrisRegion region = regionCache.get(xf, zf); + int he = Math.min(chunkHeight, context.getRoundedHeight(xf, zf)); + int hf = Math.max(clampedFluidHeight, he); + if (hf < 0) { + continue; + } + + int topY = Math.min(hf, chunkHeight - 1); + PlatformBlockState fluid = fluidCache.get(xf, zf); + PlatformBlockState rock = rockCache.get(xf, zf); + PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ); + KList biomeSurfaceOres = hideOres ? null : biome.getSurfaceOreGenerators(); + KList regionSurfaceOres = hideOres ? null : region.getSurfaceOreGenerators(); + KList biomeUndergroundOres = hideOres ? null : biome.getUndergroundOreGenerators(); + KList regionUndergroundOres = hideOres ? null : region.getUndergroundOreGenerators(); + IrisOreGeneratorBounds biomeSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getSurfaceOreGeneratorBounds(); + IrisOreGeneratorBounds regionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getSurfaceOreGeneratorBounds(); + IrisOreGeneratorBounds biomeUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getUndergroundOreGeneratorBounds(); + IrisOreGeneratorBounds regionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getUndergroundOreGeneratorBounds(); + boolean hasSurfaceOres = biomeSurfaceOreBounds.hasOres() || regionSurfaceOreBounds.hasOres() || dimensionSurfaceOreBounds.hasOres(); + boolean hasUndergroundOres = biomeUndergroundOreBounds.hasOres() || regionUndergroundOreBounds.hasOres() || dimensionUndergroundOreBounds.hasOres(); + KList blocks = null; + KList fblocks = null; + + for (int i = topY; i >= 0; i--) { + if (i == 0 && bedrockEnabled) { + h.setRaw(xf, i, zf, BEDROCK); + continue; + } + + PlatformBlockState ore = null; + if (hasSurfaceOres) { + if (biomeSurfaceOreBounds.contains(i)) { + ore = generateOres(biomeSurfaceOres, realX, i, realZ, localRng, data); + } + if (ore == null && regionSurfaceOreBounds.contains(i)) { + ore = generateOres(regionSurfaceOres, realX, i, realZ, localRng, data); + } + if (ore == null && dimensionSurfaceOreBounds.contains(i)) { + ore = generateOres(dimensionSurfaceOres, realX, i, realZ, localRng, data); + } + } + if (ore != null) { + h.setRaw(xf, i, zf, ore); + continue; + } + + if (i > he && i <= hf) { + int fdepth = hf - i; + if (fblocks == null) { + fblocks = biome.generateSeaLayers(realX, realZ, localRng, hf - he, data); + } + + if (fblocks.hasIndex(fdepth)) { + h.setRaw(xf, i, zf, fblocks.get(fdepth)); + } else { + h.setRaw(xf, i, zf, fluid); + } + continue; + } + + if (i <= he) { + int depth = he - i; + if (depth == 0 && mappedSurfaceBlock != null) { + h.setRaw(xf, i, zf, mappedSurfaceBlock); + continue; + } + if (blocks == null) { + blocks = biome.generateLayers(dimension, realX, realZ, localRng, he, he, data, complex); + } + + if (blocks.hasIndex(depth)) { + h.setRaw(xf, i, zf, blocks.get(depth)); + continue; + } + + if (hasUndergroundOres) { + if (biomeUndergroundOreBounds.contains(i)) { + ore = generateOres(biomeUndergroundOres, realX, i, realZ, localRng, data); + } + if (ore == null && regionUndergroundOreBounds.contains(i)) { + ore = generateOres(regionUndergroundOres, realX, i, realZ, localRng, data); + } + if (ore == null && dimensionUndergroundOreBounds.contains(i)) { + ore = generateOres(dimensionUndergroundOres, realX, i, realZ, localRng, data); + } + } + + if (ore != null) { + h.setRaw(xf, i, zf, ore); + } else { + h.setRaw(xf, i, zf, rock); + } + } + } + + if (upperContext != null) { + int rawUpperSurface = upperContext.getUpperSurfaceY(realX, realZ); + int upperGap = dimension.getUpperDimensionGap(); + int upperSurfaceY = Math.max(rawUpperSurface, he + upperGap); + + if (upperSurfaceY < chunkHeight - 1) { + IrisBiome upperBiome = upperContext.getUpperBiome(realX, realZ); + PlatformBlockState upperRock = upperContext.getRockBlock(realX, realZ); + PlatformBlockState upperMappedSurface = upperContext.getSurfaceBlock(realX, realZ); + int upperThickness = chunkHeight - 1 - upperSurfaceY; + KList upperBlocks = upperBiome != null + ? upperBiome.generateLayers(upperContext.getDimension(), + realX, realZ, localRng, upperThickness, upperThickness, + upperContext.getData(), complex) + : null; + + for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { + if (y == chunkHeight - 1 && bedrockEnabled) { + h.setRaw(xf, y, zf, BEDROCK); + continue; + } + if (y == upperSurfaceY && upperMappedSurface != null) { + h.setRaw(xf, y, zf, upperMappedSurface); + continue; + } + int depthFromFace = y - upperSurfaceY; + if (upperBlocks != null && upperBlocks.hasIndex(depthFromFace)) { + h.setRaw(xf, y, zf, upperBlocks.get(depthFromFace)); + } else { + h.setRaw(xf, y, zf, upperRock); + } + } + } + } + } + } + + private PlatformBlockState generateOres(KList oreGenerators, int x, int y, int z, RNG rng, IrisData data) { + if (oreGenerators == null || oreGenerators.isEmpty()) { + return null; + } + + int oreCount = oreGenerators.size(); + for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { + IrisOreGenerator oreGenerator = oreGenerators.get(oreIndex); + PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); + if (ore != null) { + return ore; + } + } + + return null; + } } } From 713b6cd430bc3de171f79121c66dfb64d893eea8 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:24:20 +0200 Subject: [PATCH 011/139] Port decorating into the iris:decorant module and delete the decorant actuator --- .../iris/engine/actuator/DecorantModule.java | 118 ++++++++++++++- .../engine/actuator/IrisDecorantActuator.java | 143 ------------------ .../engine/modifier/IrisCarveModifier.java | 13 +- 3 files changed, 122 insertions(+), 152 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index d1a8b1b2a..1e74d2f07 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -21,14 +21,31 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.decorant.DecorantStages; import art.arcane.iris.builtin.matter.MatterStages; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.decorator.IrisCeilingDecorator; +import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; +import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; +import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineDecorator; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.context.ChunkContext; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.documentation.BlockCoordinates; +import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; +import java.util.function.Predicate; + /** - * Module {@code iris:decorant}: the biomes' decorators, placed on the surface the mantle's blocks left. A thin - * wrapper: the stage runs {@link IrisDecorantActuator} unchanged, one per engine runtime. + * Module {@code iris:decorant}: the biomes' decorators, placed on the surface the mantle's blocks left: the + * surface itself, the sea surface and floor, and the shore line. A dimension turns decorating off with + * {@code decorate}. */ public final class DecorantModule implements IrisModule { private static final String VERSION = "built-in"; @@ -45,7 +62,100 @@ public final class DecorantModule implements IrisModule { private static void decorate(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - chunk.state(IrisDecorantActuator.class, IrisDecorantActuator::new) - .actuate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + chunk.state(Decorating.class, Decorating::new).decorate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); + } + + /** What decorating keeps for one engine runtime: one decorator per kind of place. */ + static final class Decorating { + private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); + /** Decorating the cave biomes' floors and ceilings is not wired up yet, so the cave biome is never looked up. */ + private static final boolean RAY_DECORATES_CAVES = false; + + private final Engine engine; + private final IrisSurfaceDecorator surfaceDecorator; + private final IrisCeilingDecorator ceilingDecorator; + private final EngineDecorator seaSurfaceDecorator; + private final EngineDecorator seaFloorDecorator; + private final EngineDecorator shoreLineDecorator; + + Decorating(Engine engine) { + this.engine = engine; + surfaceDecorator = new IrisSurfaceDecorator(engine); + ceilingDecorator = new IrisCeilingDecorator(engine); + seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); + shoreLineDecorator = new IrisShoreLineDecorator(engine); + seaFloorDecorator = new IrisSeaFloorDecorator(engine); + } + + /** Decorates the 16 x 16 columns of the chunk whose first block is {@code x}, {@code z}, a biome's decorators on the surface its blocks left. */ + @BlockCoordinates + void decorate(int x, int z, Hunk output, ChunkContext context) { + if (!engine.getDimension().isDecorate()) { + return; + } + + PrecisionStopwatch p = PrecisionStopwatch.start(); + + for (int i = 0; i < output.getWidth(); i++) { + int height; + int realX = Math.round(x + i); + int realZ; + IrisBiome biome, cave; + for (int j = 0; j < output.getDepth(); j++) { + boolean solid; + int emptyFor = 0; + int lastSolid = 0; + realZ = Math.round(z + j); + height = context.getRoundedHeight(i, j); + biome = context.getBiome().get(i, j); + cave = RAY_DECORATES_CAVES ? context.getCave().get(i, j) : null; + + if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) { + continue; + } + + if (height < engine.getDimension().getFluidHeight() && PREDICATE_SOLID.test(output.get(i, height, j)) + && height + 1 < output.getHeight() && B.isWater(output.get(i, height + 1, j))) { + seaSurfaceDecorator.decorate(i, j, + realX, Math.round(i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + output, biome, engine.getDimension().getFluidHeight(), engine.getHeight()); + seaFloorDecorator.decorate(i, j, + realX, realZ, output, biome, height + 1, + engine.getDimension().getFluidHeight() + 1); + } + + if (height == engine.getDimension().getFluidHeight()) { + shoreLineDecorator.decorate(i, j, + realX, Math.round(x + i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + output, biome, height, engine.getHeight()); + } + + if (height >= 0 && height < output.getHeight()) { + surfaceDecorator.decorate(i, j, realX, realZ, output, biome, height, engine.getHeight() - height); + } + + if (cave != null && cave.getDecorators().isNotEmpty()) { + for (int k = Math.min(height, output.getHeight() - 1); k > 0; k--) { + solid = PREDICATE_SOLID.test(output.get(i, k, j)); + + if (solid) { + if (emptyFor > 0) { + surfaceDecorator.decorate(i, j, realX, realZ, output, cave, k, lastSolid); + ceilingDecorator.decorate(i, j, realX, realZ, output, cave, lastSolid - 1, emptyFor); + emptyFor = 0; + } + lastSolid = k; + } else { + emptyFor++; + } + } + } + } + } + + engine.getMetrics().getDecoration().put(p.getMilliseconds()); + } } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java b/src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java deleted file mode 100644 index 2160960ca..000000000 --- a/src/main/java/art/arcane/iris/engine/actuator/IrisDecorantActuator.java +++ /dev/null @@ -1,143 +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.actuator; - -import art.arcane.iris.engine.decorator.IrisCeilingDecorator; -import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; -import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; -import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; -import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedActuator; -import art.arcane.iris.engine.framework.EngineDecorator; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.Getter; - -import java.util.function.Predicate; - -public class IrisDecorantActuator extends EngineAssignedActuator { - private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); - private final RNG rng; - @Getter - private final IrisSurfaceDecorator surfaceDecorator; - @Getter - private final IrisCeilingDecorator ceilingDecorator; - @Getter - private final EngineDecorator seaSurfaceDecorator; - @Getter - private final EngineDecorator seaFloorDecorator; - @Getter - private final EngineDecorator shoreLineDecorator; - private final boolean shouldRay; - - public IrisDecorantActuator(Engine engine) { - super(engine, "Decorant"); - shouldRay = shouldRayDecorate(); - this.rng = new RNG(engine.getSeedManager().getDecorator()); - surfaceDecorator = new IrisSurfaceDecorator(getEngine()); - ceilingDecorator = new IrisCeilingDecorator(getEngine()); - seaSurfaceDecorator = new IrisSeaSurfaceDecorator(getEngine()); - shoreLineDecorator = new IrisShoreLineDecorator(getEngine()); - seaFloorDecorator = new IrisSeaFloorDecorator(getEngine()); - } - - @BlockCoordinates - @Override - public void onActuate(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - if (!getEngine().getDimension().isDecorate()) { - return; - } - - PrecisionStopwatch p = PrecisionStopwatch.start(); - - for (int i = 0; i < output.getWidth(); i++) { - int height; - int realX = Math.round(x + i); - int realZ; - IrisBiome biome, cave; - for (int j = 0; j < output.getDepth(); j++) { - boolean solid; - int emptyFor = 0; - int lastSolid = 0; - realZ = Math.round(z + j); - height = context.getRoundedHeight(i, j); - biome = context.getBiome().get(i, j); - cave = shouldRay ? context.getCave().get(i, j) : null; - - if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) { - continue; - } - - if (height < getDimension().getFluidHeight() && PREDICATE_SOLID.test(output.get(i, height, j)) - && height + 1 < output.getHeight() && B.isWater(output.get(i, height + 1, j))) { - getSeaSurfaceDecorator().decorate(i, j, - realX, Math.round(i + 1), Math.round(x + i - 1), - realZ, Math.round(z + j + 1), Math.round(z + j - 1), - output, biome, getDimension().getFluidHeight(), getEngine().getHeight()); - getSeaFloorDecorator().decorate(i, j, - realX, realZ, output, biome, height + 1, - getDimension().getFluidHeight() + 1); - } - - if (height == getDimension().getFluidHeight()) { - getShoreLineDecorator().decorate(i, j, - realX, Math.round(x + i + 1), Math.round(x + i - 1), - realZ, Math.round(z + j + 1), Math.round(z + j - 1), - output, biome, height, getEngine().getHeight()); - } - - if (height >= 0 && height < output.getHeight()) { - getSurfaceDecorator().decorate(i, j, realX, realZ, output, biome, height, getEngine().getHeight() - height); - } - - - if (cave != null && cave.getDecorators().isNotEmpty()) { - for (int k = Math.min(height, output.getHeight() - 1); k > 0; k--) { - solid = PREDICATE_SOLID.test(output.get(i, k, j)); - - if (solid) { - if (emptyFor > 0) { - getSurfaceDecorator().decorate(i, j, realX, realZ, output, cave, k, lastSolid); - getCeilingDecorator().decorate(i, j, realX, realZ, output, cave, lastSolid - 1, emptyFor); - emptyFor = 0; - } - lastSolid = k; - } else { - emptyFor++; - } - } - } - } - } - - getEngine().getMetrics().getDecoration().put(p.getMilliseconds()); - - } - - private boolean shouldRayDecorate() { - return false; // TODO CAVES - } -} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java index ec65c6323..b465463be 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java @@ -19,7 +19,8 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.actuator.IrisDecorantActuator; +import art.arcane.iris.engine.decorator.IrisCeilingDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedModifier; import art.arcane.iris.engine.object.world.biome.InferredType; @@ -60,12 +61,14 @@ public class IrisCarveModifier extends EngineAssignedModifier 0 && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { - decorant.getSurfaceDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); + surfaceDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); } IrisDecorator[] ceilingDecorators = ceilingBiome == null ? new IrisDecorator[0] : ceilingBiome.getDecoratorBucket(IrisDecorationPart.CEILING); if (ceilingDecorators.length > 0 && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { - decorant.getCeilingDecorator().decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); + ceilingDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); } } From 1802f30d8bb82f4cc6fb982ab019155f682293eb Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:26:42 +0200 Subject: [PATCH 012/139] Port post smoothing into the iris:post module as SurfaceSmoothing and delete the post modifier --- .../iris/engine/modifier/PostModule.java | 8 ++--- ...ostModifier.java => SurfaceSmoothing.java} | 29 +++++++++++-------- 2 files changed, 21 insertions(+), 16 deletions(-) rename src/main/java/art/arcane/iris/engine/modifier/{IrisPostModifier.java => SurfaceSmoothing.java} (93%) diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index f34ef829c..3a09e3381 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -27,8 +27,8 @@ import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; /** - * Module {@code iris:post}: smooths the carved surface. A thin wrapper: the stage runs {@link IrisPostModifier} - * unchanged, one per engine runtime, except while maintenance regeneration bypasses the mantle. + * Module {@code iris:post}: smooths the carved surface with {@link SurfaceSmoothing}, except while maintenance + * regeneration bypasses the mantle. */ public final class PostModule implements IrisModule { private static final String VERSION = "built-in"; @@ -48,7 +48,7 @@ public final class PostModule implements IrisModule { if (chunk.bypassesMantleStages()) { return; } - chunk.state(IrisPostModifier.class, IrisPostModifier::new) - .modify(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + chunk.state(SurfaceSmoothing.class, SurfaceSmoothing::new) + .smooth(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java similarity index 93% rename from src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java rename to src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index cf4b008af..625b59b6a 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisPostModifier.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedModifier; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; @@ -32,20 +31,26 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import art.arcane.iris.spi.PlatformBlockState; -public class IrisPostModifier extends EngineAssignedModifier { +/** + * Smooths the carved surface for {@link PostModule}: floating nibs, single-block bumps and potholes, walls under + * steep faces, slabs on steps, waterlogging and the foliage that lost its ground. One per engine runtime, + * holding the post stream's random. + */ +public class SurfaceSmoothing { private static final class States { private static final PlatformBlockState AIR = B.getState("AIR"); } + private final Engine engine; private final RNG rng; - public IrisPostModifier(Engine engine) { - super(engine, "Post"); - rng = new RNG(getEngine().getSeedManager().getPost()); + public SurfaceSmoothing(Engine engine) { + this.engine = engine; + rng = new RNG(engine.getSeedManager().getPost()); } - @Override - public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + /** Smooths the chunk whose first block is {@code x}, {@code z}. */ + public void smooth(int x, int z, Hunk output, boolean multicore, ChunkContext context) { PrecisionStopwatch p = PrecisionStopwatch.start(); // The post stage runs sequentially on production (multicore false); an uncontended // monitor per probe is still a monitor times ~10k probes per chunk. @@ -54,7 +59,7 @@ public class IrisPostModifier extends EngineAssignedModifier int depth = output.getDepth(); int planeWidth = width + 2; int[] heights = heightPlane(x, z, width, depth, planeWidth); - IrisDimension dimension = getDimension(); + IrisDimension dimension = engine.getDimension(); boolean walls = dimension.isPostProcessingWalls(); boolean slabs = dimension.isPostProcessingSlabs(); int fluidHeight = dimension.getFluidHeight(); @@ -64,7 +69,7 @@ public class IrisPostModifier extends EngineAssignedModifier } } - getEngine().getMetrics().getPost().put(p.getMilliseconds()); + engine.getMetrics().getPost().put(p.getMilliseconds()); } /** @@ -74,7 +79,7 @@ public class IrisPostModifier extends EngineAssignedModifier */ private int[] heightPlane(int x, int z, int width, int depth, int planeWidth) { int[] heights = new int[planeWidth * (depth + 2)]; - EngineMantle mantle = getEngine().getMantle(); + EngineMantle mantle = engine.getMantle(); for (int j = -1; j <= depth; j++) { boolean edge = j == -1 || j == depth; @@ -177,7 +182,7 @@ public class IrisPostModifier extends EngineAssignedModifier int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); for (int i = h; i > h - max; i--) { - PlatformBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, getData()); + PlatformBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, engine.getData()); if (d != null) { if (isAirOrWater(x, i, z, originX, originZ, currentData)) { @@ -206,7 +211,7 @@ public class IrisPostModifier extends EngineAssignedModifier //@done { IrisSlopeClip sc = biome.getSlab().getSlopeCondition(); - PlatformBlockState d = sc.isValid(getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, getData()) : null; + PlatformBlockState d = sc.isValid(engine.getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, engine.getData()) : null; if (d != null) { boolean cancel = B.isAir(d); From 3a224c6b0393f89f7f3e8961f2669b0c17e5da40 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:30:29 +0200 Subject: [PATCH 013/139] Port floating island solids and decoration into the iris:floating module as FloatingIslands and delete the child biome modifier --- .../FloatingIslandSampleResolver.java | 4 +- ...iomeModifier.java => FloatingIslands.java} | 48 +++++++++++-------- .../iris/engine/modifier/FloatingModule.java | 8 ++-- 3 files changed, 33 insertions(+), 27 deletions(-) rename src/main/java/art/arcane/iris/engine/modifier/{IrisFloatingChildBiomeModifier.java => FloatingIslands.java} (91%) diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java index 21b8ef106..b80204f93 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -22,7 +22,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.Cache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.modifier.IrisFloatingChildBiomeModifier; +import art.arcane.iris.engine.modifier.FloatingIslands; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -43,7 +43,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro this.data = engineMantle.getData(); this.engine = engineMantle.getEngine(); this.chunkHeight = engine.getHeight(); - this.baseSeed = engine.getSeedManager().getTerrain() ^ IrisFloatingChildBiomeModifier.FLOATING_BASE_SEED_SALT; + this.baseSeed = engine.getSeedManager().getTerrain() ^ FloatingIslands.FLOATING_BASE_SEED_SALT; this.boundarySampler = boundarySampler; this.sampleCache = new Long2ObjectOpenHashMap<>(); this.resolvedSamples = new LongOpenHashSet(); diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java rename to src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 0b661a9cc..4a97bcd25 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisFloatingChildBiomeModifier.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -25,7 +25,6 @@ import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.decorator.FloatingDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedModifier; import art.arcane.iris.engine.framework.EngineDecorator; import art.arcane.iris.engine.object.terrain.floating.FloatingBottomPaletteMode; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; @@ -53,10 +52,16 @@ import java.util.IdentityHashMap; import static art.arcane.iris.engine.mantle.EngineMantle.AIR; -public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier { +/** + * Fills and decorates the floating islands of the dimension's floating child biomes for {@link FloatingModule}: + * the islands' solids (top layers, bottom palette, sea surface) and, later, the decoration on their tops. One + * per engine runtime, holding the islands' random. + */ +public class FloatingIslands { public static final long FLOATING_BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; private static final Runnable NOOP_DECORATION_MISS = () -> { }; + private final Engine engine; private final RNG rng; private final EngineDecorator seaSurfaceDecorator; @@ -198,20 +203,20 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier output, boolean multicore, ChunkContext context) { + /** Fills the islands' solids into the chunk whose first block is {@code x}, {@code z}. */ + public void fillSolids(int x, int z, Hunk output, boolean multicore, ChunkContext context) { PrecisionStopwatch p = PrecisionStopwatch.start(); int chunkHeight = output.getHeight(); - IrisData data = getData(); - IrisDimension dimension = getDimension(); - IrisComplex complex = getComplex(); - long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; + IrisData data = engine.getData(); + IrisDimension dimension = engine.getDimension(); + IrisComplex complex = engine.getComplex(); + long baseSeed = engine.getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); FloatingIslandSample.clearChunkMemo(); @@ -223,7 +228,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier output, boolean multicore, ChunkContext context) { int chunkHeight = output.getHeight(); - IrisData data = getData(); - IrisComplex complex = getComplex(); - long baseSeed = getEngine().getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; + IrisData data = engine.getData(); + IrisComplex complex = engine.getComplex(); + long baseSeed = engine.getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); for (int xf = 0; xf < 16; xf++) { @@ -307,7 +313,7 @@ public class IrisFloatingChildBiomeModifier extends EngineAssignedModifier Date: Thu, 8 Oct 2026 13:32:44 +0200 Subject: [PATCH 014/139] Port custom block recording into the iris:custom module and delete the custom modifier --- .../iris/engine/modifier/CustomModule.java | 74 +++++++++++++++++-- .../engine/modifier/IrisCustomModifier.java | 64 ---------------- 2 files changed, 69 insertions(+), 69 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java diff --git a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java index 1be418b26..d59e879ea 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java @@ -20,19 +20,30 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.custom.CustomStages; import art.arcane.iris.builtin.perfection.PerfectionStages; +import art.arcane.iris.core.link.Identifier; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.parallel.BurstExecutor; +import art.arcane.iris.util.common.parallel.MultiBurst; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.mantle.flag.MantleFlag; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; /** - * Module {@code iris:custom}: records the chunk's content-plugin blocks for the server to place later. A thin - * wrapper: the stage runs {@link IrisCustomModifier} unchanged, one per engine runtime, except while - * maintenance regeneration bypasses the mantle. + * Module {@code iris:custom}: records the chunk's content-plugin blocks for the server to place later: each + * custom block's placement key goes into the mantle and the block itself is replaced by its base state. Skipped + * while maintenance regeneration bypasses the mantle. */ public final class CustomModule implements IrisModule { private static final String VERSION = "built-in"; + private static final int CHUNK_SHIFT = 4; + private static final int SECTION_MASK = 15; @Override public ModuleInfo info() { @@ -49,7 +60,60 @@ public final class CustomModule implements IrisModule { if (chunk.bypassesMantleStages()) { return; } - chunk.state(IrisCustomModifier.class, IrisCustomModifier::new) - .modify(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + chunk.state(CustomBlockRecording.class, CustomBlockRecording::new).record(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore()); + } + + /** Moves the custom blocks of a chunk into the mantle for one engine runtime. */ + static final class CustomBlockRecording { + private final Engine engine; + + CustomBlockRecording(Engine engine) { + this.engine = engine; + } + + /** Records the custom blocks of the chunk whose first block is {@code x}, {@code z}, when its mantle chunk is flagged as having some. */ + void record(int x, int z, Hunk output, boolean multicore) { + MantleChunk mc = engine.getMantle().getMantle().getChunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); + if (!mc.isFlagged(MantleFlag.CUSTOM_ACTIVE)) { + return; + } + mc.use(); + + BurstExecutor burst = MultiBurst.burst.burst(output.getHeight()); + burst.setMulticore(multicore); + // complete() must run before release() even when queueing throws — detached burst + // tasks must never write into a released chunk, and a lost permit wedges close(). + try { + for (int y = 0; y < output.getHeight(); y++) { + int finalY = y; + burst.queue(() -> { + for (int rX = 0; rX < output.getWidth(); rX++) { + for (int rZ = 0; rZ < output.getDepth(); rZ++) { + PlatformBlockState b = output.get(rX, finalY, rZ); + if (b == null || !b.isCustom()) { + continue; + } + String placementKey = b.deferredPlacementKey(); + PlatformBlockState baseState = b.placementBaseState(); + if (placementKey == null || baseState == null) { + continue; + } + + mc.getOrCreate(finalY >> CHUNK_SHIFT) + .slice(Identifier.class) + .set(rX, finalY & SECTION_MASK, rZ, Identifier.fromString(placementKey)); + output.set(rX, finalY, rZ, baseState); + } + } + }); + } + } finally { + try { + burst.complete(); + } finally { + mc.release(); + } + } + } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java deleted file mode 100644 index 328fea675..000000000 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCustomModifier.java +++ /dev/null @@ -1,64 +0,0 @@ -package art.arcane.iris.engine.modifier; - -import art.arcane.iris.core.link.Identifier; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedModifier; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.parallel.BurstExecutor; -import art.arcane.iris.util.common.parallel.MultiBurst; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.mantle.flag.MantleFlag; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; - -public class IrisCustomModifier extends EngineAssignedModifier { - public IrisCustomModifier(Engine engine) { - super(engine, "Custom"); - } - - @Override - public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - MantleChunk mc = getEngine().getMantle().getMantle().getChunk(x >> 4, z >> 4); - if (!mc.isFlagged(MantleFlag.CUSTOM_ACTIVE)) { - return; - } - mc.use(); - - BurstExecutor burst = MultiBurst.burst.burst(output.getHeight()); - burst.setMulticore(multicore); - // complete() must run before release() even when queueing throws — detached burst - // tasks must never write into a released chunk, and a lost permit wedges close(). - try { - for (int y = 0; y < output.getHeight(); y++) { - int finalY = y; - burst.queue(() -> { - for (int rX = 0; rX < output.getWidth(); rX++) { - for (int rZ = 0; rZ < output.getDepth(); rZ++) { - PlatformBlockState b = output.get(rX, finalY, rZ); - if (b == null || !b.isCustom()) { - continue; - } - String placementKey = b.deferredPlacementKey(); - PlatformBlockState baseState = b.placementBaseState(); - if (placementKey == null || baseState == null) { - continue; - } - - mc.getOrCreate(finalY >> 4) - .slice(Identifier.class) - .set(rX, finalY & 15, rZ, Identifier.fromString(placementKey)); - output.set(rX, finalY, rZ, baseState); - } - } - }); - } - } finally { - try { - burst.complete(); - } finally { - mc.release(); - } - } - } -} From 6f56e4297170672f677eafa0f5b877c4e818cc76 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:41:31 +0200 Subject: [PATCH 015/139] Port matter insertion into the iris:matter module and remove it from the engine mantle --- .../iris/engine/modifier/MatterModule.java | 64 ++++++++++++++++++- 1 file changed, 61 insertions(+), 3 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java index b36865087..baa03b22e 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -22,6 +22,13 @@ import art.arcane.iris.builtin.deposit.DepositStages; import art.arcane.iris.builtin.floating.FloatingStages; import art.arcane.iris.builtin.matter.MatterStages; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; @@ -29,12 +36,14 @@ import com.volmit.stage.StageGraph; /** * Module {@code iris:matter}: copies the blocks the mantle planned for the chunk, its objects and structures, - * into it. A thin wrapper around the engine mantle's own insertion. It orders itself after deposits without - * requiring them, since deposits run only where a level declares some. + * into it, unless the dimension turns the mantle off ({@code useMantle}). Where an upper dimension sits above, + * blocks at or above its surface are left out. It orders itself after deposits without requiring them, since + * deposits run only where a level declares some. */ public final class MatterModule implements IrisModule { private static final String VERSION = "built-in"; private static final int CHUNK_SHIFT = 4; + private static final int CHUNK_COLUMNS = 16 * 16; @Override public ModuleInfo info() { @@ -54,6 +63,55 @@ public final class MatterModule implements IrisModule { if (chunk.bypassesMantleStages()) { return; } - chunk.engine().getMantle().insertMatter(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.blocks(), chunk.multicore()); + chunk.state(MatterInsertion.class, MatterInsertion::new).insert(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.blocks()); + } + + /** Copies the mantle's blocks into chunks for one engine runtime. */ + static final class MatterInsertion { + private final Engine engine; + + MatterInsertion(Engine engine) { + this.engine = engine; + } + + /** Copies the blocks the mantle holds for chunk {@code x}, {@code z} into {@code blocks}. */ + @ChunkCoordinates + void insert(int x, int z, Hunk blocks) { + if (!engine.getDimension().isUseMantle()) { + return; + } + + UpperDimensionContext upperCtx = engine.getUpperContext(); + boolean protectUpper = upperCtx != null; + + MantleChunk chunk = engine.getMantle().getMantle().getChunk(x, z).use(); + try { + if (protectUpper) { + int chunkBlockX = x << CHUNK_SHIFT; + int chunkBlockZ = z << CHUNK_SHIFT; + int gap = engine.getDimension().getUpperDimensionGap(); + int[] upperYs = new int[CHUNK_COLUMNS]; + for (int i = 0; i < CHUNK_COLUMNS; i++) { + int lx = i >> 4; + int lz = i & 15; + int worldX = chunkBlockX + lx; + int worldZ = chunkBlockZ + lz; + int he = (int) Math.round(engine.getComplex().getHeightStream().get((double) worldX, (double) worldZ)); + int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); + upperYs[i] = Math.max(rawUpper, he + gap); + } + chunk.iterate(PlatformBlockState.class, (lx, y, lz, value) -> { + int colIdx = (lx << 4) | (lz & 15); + if (y < upperYs[colIdx]) { + blocks.set(lx, y, lz, value); + } + }); + } else { + chunk.iterate(PlatformBlockState.class, (lx, y, lz, value) -> blocks.set(lx, y, lz, value)); + } + } finally { + chunk.release(); + } + } } } From c8dd58499056e42b73a17b84bd2cb0b2b3f6002c Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 13:47:00 +0200 Subject: [PATCH 016/139] Port cave application into the iris:carve module as CaveApplying; every built-in stage is now a full port --- README.md | 7 +-- .../iris/engine/modifier/CarveModule.java | 4 +- ...isCarveModifier.java => CaveApplying.java} | 63 ++++++++++--------- 3 files changed, 39 insertions(+), 35 deletions(-) rename src/main/java/art/arcane/iris/engine/modifier/{IrisCarveModifier.java => CaveApplying.java} (92%) diff --git a/README.md b/README.md index daefa6d7c..dbb14d9f4 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,9 @@ mantle components outside the stage graph any more. Their stage constants, and t types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live beside the features they replace. -`iris:biome` and `iris:deposit` (chunk stages) and every mantle stage (caves, objects, floating objects, -structures) are full ports: the module owns its logic and per-engine state, and the mantle stages work out -their reach from the pack when it loads. The other chunk stages are thin wrappers that run the existing -actuator or modifier unchanged. +Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages +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 diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 0e6ce0642..b32ab59d9 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -34,7 +34,7 @@ import com.volmit.stage.StageGraph; * Module {@code iris:carve}: caves. A mantle stage plans them into the mantle, reaching one block into each * neighboring chunk where blended cave walls cross the border; a chunk stage later cuts them out of the chunk's * terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by - * {@link CaveCarving}, one per engine runtime. The chunk stage is a thin wrapper around {@link IrisCarveModifier}. + * {@link CaveCarving}, one per engine runtime. The chunk stage's work is done by {@link CaveApplying}. */ public final class CarveModule implements IrisModule { private static final String VERSION = "built-in"; @@ -66,7 +66,7 @@ public final class CarveModule implements IrisModule { if (chunk.bypassesMantleStages()) { return; } - chunk.state(IrisCarveModifier.class, IrisCarveModifier::new).modify(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, + chunk.state(CaveApplying.class, CaveApplying::new).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.blocks(), chunk.multicore(), chunk.context()); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java rename to src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index b465463be..8f81fa52f 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveModifier.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -22,7 +22,6 @@ import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.decorator.IrisCeilingDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedModifier; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.decoration.IrisDecorationPart; @@ -51,31 +50,37 @@ import art.arcane.iris.spi.PlatformBlockState; import java.util.Map; -public class IrisCarveModifier extends EngineAssignedModifier { +/** + * Applies the caves the mantle planned to a chunk's blocks for {@link CarveModule}: carves each cave zone, paints + * its floor and ceiling with the cave biomes' layers, fills fluids and lava and decorates the cave surfaces. + * One per engine runtime, holding the carve stream's random. + */ +public class CaveApplying { private static final byte LIQUID_FLUID = 1; private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(IrisCarveScratch::new); private static final int CAVE_BIOME_BLEND_RADIUS = 3; private static final int CAVE_BIOME_BLEND_CENTER_WEIGHT = 4; private static final int CAVE_BIOME_BLEND_TOTAL_WEIGHT = 8; private static final MatterCavern BASIC_CAVERN = new MatterCavern(true, "", (byte) 0); + private final Engine engine; private final RNG rng; private final PlatformBlockState AIR = B.getState("CAVE_AIR"); private final PlatformBlockState LAVA = B.getState("LAVA"); private final IrisSurfaceDecorator surfaceDecorator; private final IrisCeilingDecorator ceilingDecorator; - public IrisCarveModifier(Engine engine) { - super(engine, "Carve"); - rng = new RNG(getEngine().getSeedManager().getCarve()); + public CaveApplying(Engine engine) { + this.engine = engine; + rng = new RNG(engine.getSeedManager().getCarve()); surfaceDecorator = new IrisSurfaceDecorator(engine); ceilingDecorator = new IrisCeilingDecorator(engine); } - @Override + /** Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}. */ @ChunkCoordinates - public void onModify(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + public void apply(int x, int z, Hunk output, boolean multicore, ChunkContext context) { PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start(); - Mantle mantle = getEngine().getMantle().getMantle(); + Mantle mantle = engine.getMantle().getMantle(); IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(2048); IrisCarveScratch scratch = SCRATCH.get(); @@ -85,8 +90,8 @@ public class IrisCarveModifier extends EngineAssignedModifier customBiomeCache = scratch.customBiomeCache; - UpperDimensionContext upperCtx = getEngine().getUpperContext(); - boolean protectUpper = upperCtx != null && !getEngine().getDimension().isUpperDimensionCarving(); + UpperDimensionContext upperCtx = engine.getUpperContext(); + boolean protectUpper = upperCtx != null && !engine.getDimension().isUpperDimensionCarving(); int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(x); int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(z); @@ -98,7 +103,7 @@ public class IrisCarveModifier extends EngineAssignedModifier mantleChunk = mantle.getChunk(x, z).use(); try { PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); - int worldHeightSpan = getEngine().getWorld().maxHeight() - getEngine().getWorld().minHeight(); - int caveLavaHeight = getEngine().getDimension().getCaveLavaHeight(); + int worldHeightSpan = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); + int caveLavaHeight = engine.getDimension().getCaveLavaHeight(); mantleChunk.iterate(MatterCavern.class, (xx, yy, zz, cavern) -> { if (cavern == null) { return; @@ -159,7 +164,7 @@ public class IrisCarveModifier extends EngineAssignedModifier= 0) { - if (y <= getEngine().getHeight()) { + if (y <= engine.getHeight()) { if (y == buf + 1) { buf = y; zone.ceiling = buf; } else { - if (zone.isValid(getEngine())) { + if (zone.isValid(engine)) { processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache); } zone = new CaveZone(); @@ -443,7 +448,7 @@ public class IrisCarveModifier extends EngineAssignedModifier floorLayers = floorBiome.generateLayers( - getDimension(), worldX, worldZ, rng, 3, zoneFloor, getData(), getComplex()); + engine.getDimension(), worldX, worldZ, rng, 3, zoneFloor, engine.getData(), engine.getComplex()); for (int i = 0; i < zoneFloor - 1; i++) { if (!floorLayers.hasIndex(i)) { break; @@ -534,9 +539,9 @@ public class IrisCarveModifier extends EngineAssignedModifier ceilingLayers = ceilingBiome.generateCeilingLayers( - getDimension(), worldX, worldZ, rng, 3, zoneCeiling, getData(), getComplex()); + engine.getDimension(), worldX, worldZ, rng, 3, zoneCeiling, engine.getData(), engine.getComplex()); for (int i = 0; i < ceilingLayers.size(); i++) { int ceilingY = zoneCeiling + i + 1; if (ceilingY >= worldMaxY) { @@ -561,7 +566,7 @@ public class IrisCarveModifier extends EngineAssignedModifier>> 30)) * 0xBF58476D1CE4E5B9L; h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; h ^= h >>> 31; @@ -597,7 +602,7 @@ public class IrisCarveModifier extends EngineAssignedModifier floorBlocks = floorBiome.generateLayers(getDimension(), xx, zz, rng, 3, zone.floor, getData(), getComplex()); + KList floorBlocks = floorBiome.generateLayers(engine.getDimension(), xx, zz, rng, 3, zone.floor, engine.getData(), engine.getComplex()); for (int i = 0; i < zone.floor - 1; i++) { if (!floorBlocks.hasIndex(i)) { break; @@ -617,7 +622,7 @@ public class IrisCarveModifier extends EngineAssignedModifier ceilingBlocks = ceilingBiome.generateCeilingLayers(getDimension(), xx, zz, rng, 3, zone.ceiling, getData(), getComplex()); + KList ceilingBlocks = ceilingBiome.generateCeilingLayers(engine.getDimension(), xx, zz, rng, 3, zone.ceiling, engine.getData(), engine.getComplex()); for (int i = 0; i < ceilingBlocks.size(); i++) { int cy = zone.ceiling + i + 1; if (cy >= maxY) { @@ -743,7 +748,7 @@ public class IrisCarveModifier extends EngineAssignedModifier Date: Thu, 8 Oct 2026 15:18:34 +0200 Subject: [PATCH 017/139] Delete the decorant's cave branch, which a constant kept switched off, and the constant --- .../iris/engine/actuator/DecorantModule.java | 30 ++----------------- 1 file changed, 2 insertions(+), 28 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 1e74d2f07..26725b972 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.decorant.DecorantStages; import art.arcane.iris.builtin.matter.MatterStages; import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.decorator.IrisCeilingDecorator; import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; @@ -68,12 +67,9 @@ public final class DecorantModule implements IrisModule { /** What decorating keeps for one engine runtime: one decorator per kind of place. */ static final class Decorating { private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); - /** Decorating the cave biomes' floors and ceilings is not wired up yet, so the cave biome is never looked up. */ - private static final boolean RAY_DECORATES_CAVES = false; private final Engine engine; private final IrisSurfaceDecorator surfaceDecorator; - private final IrisCeilingDecorator ceilingDecorator; private final EngineDecorator seaSurfaceDecorator; private final EngineDecorator seaFloorDecorator; private final EngineDecorator shoreLineDecorator; @@ -81,7 +77,6 @@ public final class DecorantModule implements IrisModule { Decorating(Engine engine) { this.engine = engine; surfaceDecorator = new IrisSurfaceDecorator(engine); - ceilingDecorator = new IrisCeilingDecorator(engine); seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); shoreLineDecorator = new IrisShoreLineDecorator(engine); seaFloorDecorator = new IrisSeaFloorDecorator(engine); @@ -100,17 +95,13 @@ public final class DecorantModule implements IrisModule { int height; int realX = Math.round(x + i); int realZ; - IrisBiome biome, cave; + IrisBiome biome; for (int j = 0; j < output.getDepth(); j++) { - boolean solid; - int emptyFor = 0; - int lastSolid = 0; realZ = Math.round(z + j); height = context.getRoundedHeight(i, j); biome = context.getBiome().get(i, j); - cave = RAY_DECORATES_CAVES ? context.getCave().get(i, j) : null; - if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) { + if (biome.getDecorators().isEmpty()) { continue; } @@ -135,23 +126,6 @@ public final class DecorantModule implements IrisModule { if (height >= 0 && height < output.getHeight()) { surfaceDecorator.decorate(i, j, realX, realZ, output, biome, height, engine.getHeight() - height); } - - if (cave != null && cave.getDecorators().isNotEmpty()) { - for (int k = Math.min(height, output.getHeight() - 1); k > 0; k--) { - solid = PREDICATE_SOLID.test(output.get(i, k, j)); - - if (solid) { - if (emptyFor > 0) { - surfaceDecorator.decorate(i, j, realX, realZ, output, cave, k, lastSolid); - ceilingDecorator.decorate(i, j, realX, realZ, output, cave, lastSolid - 1, emptyFor); - emptyFor = 0; - } - lastSolid = k; - } else { - emptyFor++; - } - } - } } } From 162d4d0be8d542f6d796f556f22e8772eb820ae6 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 15:25:58 +0200 Subject: [PATCH 018/139] Clamp vacuum targets to the dimension's own heights instead of Minecraft's range, so terrain can be raised past Y 256 in a dimension that starts at -64 --- .../iris/engine/object/placement/IrisObjectVacuum.java | 7 +++++++ .../iris/engine/object/placement/VacuumModule.java | 10 +++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java index 82d5cc89d..b10b38e87 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -93,6 +93,13 @@ public final class IrisObjectVacuum { return 0; } + /** The lowest height vacuum may target, one above the dimension's bottom (placer heights start at 0 there). */ + public static final int LOWEST_TARGET_Y = 1; + + public static int clampTargetY(int targetY, int lowestY, int highestY) { + return Math.max(lowestY, Math.min(highestY, targetY)); + } + public static int columnTargetY(int dx, int dz, int lowX, int highX, int lowZ, int highZ, double effectiveRadius, double falloff, int originalY, int meetY) { double factor = columnInfluence( diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 929060a14..d7d08ae17 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -84,8 +84,8 @@ public final class VacuumModule implements IrisModule { private final double waveAmplitude; private final double waveScale; private final SimplexNoise waves; - private final int worldMin; - private final int worldMax; + private final int lowestY; + private final int highestY; private Bend(PlacementStageContext context, PreparedPlacement prepared, Engine engine) { ObjectPlaceMode mode = prepared.mode(); @@ -101,8 +101,8 @@ public final class VacuumModule implements IrisModule { this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); this.waves = mode == ObjectPlaceMode.VACUUM_WAVY && waveAmplitude > 0 ? new SimplexNoise(WAVE_SEED) : null; - this.worldMin = engine.getMinHeight(); - this.worldMax = worldMin + engine.getHeight() - 1; + this.lowestY = IrisObjectVacuum.LOWEST_TARGET_Y; + this.highestY = engine.getHeight() - 1; } private void apply(int baseY, int topY) { @@ -124,7 +124,7 @@ public final class VacuumModule implements IrisModule { if (targetY == originalY) { return; } - targetY = Math.max(worldMin + 1, Math.min(worldMax, targetY)); + targetY = IrisObjectVacuum.clampTargetY(targetY, lowestY, highestY); if (targetY > originalY) { raise(x, z, originalY, targetY); } else if (targetY < originalY) { From 7a9ea0ca5aff9d85a715185948b7931e35430aec Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 15:30:38 +0200 Subject: [PATCH 019/139] Ask the platform whether a block has gravity in cave application instead of keeping a list of block keys --- .../arcane/iris/engine/modifier/CaveApplying.java | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 8f81fa52f..67b9ac805 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -27,7 +27,6 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.decoration.IrisDecorationPart; import art.arcane.iris.engine.object.decoration.IrisDecorator; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.documentation.ChunkCoordinates; @@ -697,16 +696,7 @@ public class CaveApplying { } static boolean isGravityAffected(PlatformBlockState state) { - if (state == null) { - return false; - } - String key = IrisProceduralBlocks.materialKey(state); - return key.equals("minecraft:sand") - || key.equals("minecraft:red_sand") - || key.equals("minecraft:gravel") - || key.equals("minecraft:suspicious_sand") - || key.equals("minecraft:suspicious_gravel") - || key.endsWith("_concrete_powder"); + return state != null && state.hasGravity(); } private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) { From f71346d235924b0ff178647a3db2ef3bc600df67 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 16:19:31 +0200 Subject: [PATCH 020/139] Gather built-in stage constants in one IrisStages catalogue The 20 per-module *Stages holders become nested classes of art.arcane.iris.builtin.IrisStages, listed in pipeline order, so one file shows every built-in stage. Settings and output types stay in their per-module subpackages. --- .../art/arcane/iris/builtin/IrisStages.java | 242 ++++++++++++++++++ .../iris/builtin/anchor/AnchorStages.java | 33 --- .../iris/builtin/biome/BiomeStages.java | 31 --- .../iris/builtin/blocks/BlocksStages.java | 36 --- .../arcane/iris/builtin/bore/BoreStages.java | 30 --- .../iris/builtin/carve/CarveStages.java | 34 --- .../iris/builtin/custom/CustomStages.java | 31 --- .../iris/builtin/decorant/DecorantStages.java | 31 --- .../iris/builtin/deposit/DepositStages.java | 34 --- .../iris/builtin/floating/FloatingStages.java | 36 --- .../iris/builtin/matter/MatterStages.java | 31 --- .../iris/builtin/objects/ObjectStages.java | 31 --- .../art/arcane/iris/builtin/package-info.java | 10 +- .../builtin/perfection/PerfectionStages.java | 31 --- .../arcane/iris/builtin/post/PostStages.java | 31 --- .../iris/builtin/prepare/PrepareStages.java | 35 --- .../arcane/iris/builtin/snow/SnowStages.java | 30 --- .../iris/builtin/stilt/StiltStages.java | 34 --- .../builtin/structure/StructureStages.java | 31 --- .../iris/builtin/terrain/TerrainStages.java | 31 --- .../iris/builtin/vacuum/VacuumStages.java | 30 --- .../iris/builtin/validate/ValidateStages.java | 37 --- .../iris/engine/actuator/BiomeModule.java | 4 +- .../iris/engine/actuator/DecorantModule.java | 5 +- .../iris/engine/actuator/TerrainModule.java | 4 +- .../mantle/components/ObjectModule.java | 5 +- .../mantle/components/StructureModule.java | 6 +- .../iris/engine/modifier/CarveModule.java | 7 +- .../iris/engine/modifier/CustomModule.java | 5 +- .../iris/engine/modifier/DepositModule.java | 10 +- .../iris/engine/modifier/FloatingModule.java | 11 +- .../iris/engine/modifier/MatterModule.java | 10 +- .../engine/modifier/PerfectionModule.java | 5 +- .../iris/engine/modifier/PostModule.java | 5 +- .../engine/object/placement/AnchorModule.java | 16 +- .../engine/object/placement/BlocksModule.java | 25 +- .../engine/object/placement/BoreModule.java | 13 +- .../object/placement/PrepareModule.java | 10 +- .../engine/object/placement/SnowModule.java | 16 +- .../engine/object/placement/StiltModule.java | 24 +- .../engine/object/placement/VacuumModule.java | 12 +- .../object/placement/ValidateModule.java | 36 ++- 42 files changed, 344 insertions(+), 785 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/IrisStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/bore/BoreStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/carve/CarveStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/custom/CustomStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/matter/MatterStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/post/PostStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/snow/SnowStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java delete mode 100644 src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java diff --git a/src/main/java/art/arcane/iris/builtin/IrisStages.java b/src/main/java/art/arcane/iris/builtin/IrisStages.java new file mode 100644 index 000000000..c22aedd5e --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/IrisStages.java @@ -0,0 +1,242 @@ +/* + * 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.builtin; + +import art.arcane.iris.builtin.anchor.AnchorHeight; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.stilt.StiltLayers; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.PreparedPlacement; +import com.volmit.stage.BlockStage; +import com.volmit.stage.ChunkStage; +import com.volmit.stage.MantleStage; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** + * Every stage of Iris's built-in modules, one nested class per module. Modules are listed in the order their + * pipelines run them: placement, then mantle, then chunk; a module with stages in several pipelines is listed + * where its first stage runs. The stage graph decides the actual order. + */ +public final class IrisStages { + private IrisStages() { + } + + /** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ + public static final class Prepare { + /** The settings the placement uses: the requested ones, turned downhill when they ask to face the slope. Rejects {@code slope}. */ + public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", IrisObjectPlacement.class); + /** The random rotation, translation and height offset, chosen once per placement. */ + public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); + + private Prepare() { + } + } + + /** Module {@code iris:anchor}: the height an object is placed at. */ + public static final class Anchor { + /** The requested or sampled height the checks judge. Rejects {@code carving-anchor}. */ + public static final PlacementStage HEIGHT = Stage.placement("iris:anchor/height", AnchorHeight.class); + /** The height the object's blocks are written at: the checked height plus the random offset. */ + public static final PlacementStage FINAL = Stage.placement("iris:anchor/final", AnchorHeight.class); + + private Anchor() { + } + } + + /** Module {@code iris:validate}: the checks that reject a placement before anything is written, in this order. */ + public static final class Validate { + /** Rejects {@code bedrock-anchor} and {@code surface-support}. */ + public static final PlacementStage SURFACE = Stage.placement("iris:validate/surface"); + /** Rejects {@code underwater-anchor}, {@code cave-clearance}, {@code fluid-height} and {@code height-clamp}. */ + public static final PlacementStage LIMITS = Stage.placement("iris:validate/limits"); + /** Rejects {@code native-structure}, even for placements that force their way past the other checks. */ + public static final PlacementStage STRUCTURES = Stage.placement("iris:validate/structures"); + /** Rejects {@code object-collision}. */ + public static final PlacementStage COLLISIONS = Stage.placement("iris:validate/collisions"); + + private Validate() { + } + } + + /** Module {@code iris:bore}: clearing the object's volume before its blocks are written. */ + public static final class Bore { + public static final PlacementStage CLEAR = Stage.placement("iris:bore/clear"); + + private Bore() { + } + } + + /** Module {@code iris:blocks}: writing the object's blocks. */ + public static final class Blocks { + /** Writes each object block where the placement puts it. */ + public static final BlockStage WRITE = Stage.placementBlock("iris:blocks/write", WrittenBlocks.class); + /** Marks some written blocks with the placement's markers. */ + public static final PlacementStage MARKERS = Stage.placement("iris:blocks/markers"); + /** Milestone: stages requiring it run after the object and its markers are written. */ + public static final PlacementStage COMPLETE = Stage.placement("iris:blocks/complete"); + + private Blocks() { + } + } + + /** Module {@code iris:stilt}: the stilts of the stilt and ceiling placement modes. */ + public static final class Stilt { + /** Finds the layers to repeat. */ + public static final BlockStage LAYERS = Stage.placementBlock("iris:stilt/layers", StiltLayers.class); + /** Grows the stilt once the object is written. */ + public static final PlacementStage FILL = Stage.placement("iris:stilt/fill"); + + private Stilt() { + } + } + + /** Module {@code iris:vacuum}: bending the terrain to meet objects of the vacuum placement modes. */ + public static final class Vacuum { + public static final PlacementStage TERRAIN = Stage.placement("iris:vacuum/terrain"); + + private Vacuum() { + } + } + + /** Module {@code iris:snow}: snow on the object, after its stilt or terrain bend. */ + public static final class Snow { + public static final PlacementStage COVER = Stage.placement("iris:snow/cover"); + + private Snow() { + } + } + + /** Module {@code iris:carve}: caves, planned in the mantle and cut into each chunk's terrain. */ + public static final class Carve { + /** Plans the caves of the dimension's cave profiles into the mantle, one block into each neighbor. */ + public static final MantleStage CAVES = Stage.mantle("iris:carve/caves"); + /** Cuts the planned caves out of the chunk's terrain and decorates their floors and ceilings. */ + public static final ChunkStage APPLY = Stage.chunk("iris:carve/apply"); + + private Carve() { + } + } + + /** Module {@code iris:objects}: the objects the dimension's regions and biomes place. */ + public static final class Objects { + /** Places surface, cave and upper-dimension objects into the mantle, after the caves they anchor in. */ + public static final MantleStage PLACE = Stage.mantle("iris:objects/place"); + + private Objects() { + } + } + + /** Module {@code iris:floating}: the floating islands of floating child biomes. */ + public static final class Floating { + /** Places the objects on and under the islands into the mantle, after the dimension's other objects. */ + public static final MantleStage OBJECTS = Stage.mantle("iris:floating/objects"); + /** Writes the islands' solid blocks. */ + public static final ChunkStage SOLIDS = Stage.chunk("iris:floating/solids"); + /** Decorates the islands' tops and bottoms once the chunk's own decoration is done. */ + public static final ChunkStage DECORATE = Stage.chunk("iris:floating/decorate"); + + private Floating() { + } + } + + /** Module {@code iris:structure}: Iris structures, assembled from pieces. */ + public static final class Structure { + /** Places the structures of the dimension, its regions and biomes into the mantle, after objects and floating objects. */ + public static final MantleStage PLACE = Stage.mantle("iris:structure/place"); + + private Structure() { + } + } + + /** Module {@code iris:biome}: the biomes a chunk reports to the server. */ + public static final class Biome { + /** Writes every column's biome, sky biome or custom biome, into the chunk. */ + public static final ChunkStage WRITE = Stage.chunk("iris:biome/write"); + + private Biome() { + } + } + + /** Module {@code iris:terrain}: the solid ground, fluids and biome layers of a chunk. */ + public static final class Terrain { + /** Fills each column from bedrock up to its height and the fluid height, with its biome's layers. */ + public static final ChunkStage SHAPE = Stage.chunk("iris:terrain/shape"); + + private Terrain() { + } + } + + /** Module {@code iris:post}: smoothing a chunk's surface after carving. */ + public static final class Post { + /** Fills single-block holes, places slabs and walls on steps and settles snow. */ + public static final ChunkStage SMOOTH = Stage.chunk("iris:post/smooth"); + + private Post() { + } + } + + /** Module {@code iris:deposit}: ores and other deposits. */ + public static final class Deposit { + /** + * Places the deposits every level declares at the chunk's centre column, the dimension's, the region's and + * the biome's, each with its own clumps. Active where any column of the chunk has deposits. + */ + public static final ChunkStage ORES = Stage.chunk("iris:deposit/ores"); + + private Deposit() { + } + } + + /** Module {@code iris:matter}: the blocks the mantle planned for a chunk, such as objects and structures. */ + public static final class Matter { + /** Copies the chunk's planned mantle blocks into it. */ + public static final ChunkStage INSERT = Stage.chunk("iris:matter/insert"); + + private Matter() { + } + } + + /** Module {@code iris:decorant}: the decorators of biomes, such as grass, flowers and cave ceilings. */ + public static final class Decorant { + /** Places every column's surface, sea, shore and cave decorators. */ + public static final ChunkStage DECORATE = Stage.chunk("iris:decorant/decorate"); + + private Decorant() { + } + } + + /** Module {@code iris:perfection}: the last touches on an overworld chunk's blocks. */ + public static final class Perfection { + /** Hides ores when the dimension asks, then removes decorations that nothing holds up. */ + public static final ChunkStage SURFACE = Stage.chunk("iris:perfection/surface"); + + private Perfection() { + } + } + + /** Module {@code iris:custom}: blocks of content plugins, which the server places after generation. */ + public static final class Custom { + /** Records the chunk's custom blocks so the server can place them once the chunk exists. */ + public static final ChunkStage BLOCKS = Stage.chunk("iris:custom/blocks"); + + private Custom() { + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java b/src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java deleted file mode 100644 index 06a08a51a..000000000 --- a/src/main/java/art/arcane/iris/builtin/anchor/AnchorStages.java +++ /dev/null @@ -1,33 +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.builtin.anchor; - -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:anchor}: the height an object is placed at. */ -public final class AnchorStages { - /** The requested or sampled height the checks judge. Rejects {@code carving-anchor}. */ - public static final PlacementStage HEIGHT = Stage.placement("iris:anchor/height", AnchorHeight.class); - /** The height the object's blocks are written at: the checked height plus the random offset. */ - public static final PlacementStage FINAL = Stage.placement("iris:anchor/final", AnchorHeight.class); - - private AnchorStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java b/src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java deleted file mode 100644 index c83b8efc0..000000000 --- a/src/main/java/art/arcane/iris/builtin/biome/BiomeStages.java +++ /dev/null @@ -1,31 +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.builtin.biome; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:biome}: the biomes a chunk reports to the server. */ -public final class BiomeStages { - /** Writes every column's biome, sky biome or custom biome, into the chunk. */ - public static final ChunkStage WRITE = Stage.chunk("iris:biome/write"); - - private BiomeStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java b/src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java deleted file mode 100644 index 615043113..000000000 --- a/src/main/java/art/arcane/iris/builtin/blocks/BlocksStages.java +++ /dev/null @@ -1,36 +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.builtin.blocks; - -import com.volmit.stage.BlockStage; -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:blocks}: writing the object's blocks. */ -public final class BlocksStages { - /** Writes each object block where the placement puts it. */ - public static final BlockStage WRITE = Stage.placementBlock("iris:blocks/write", WrittenBlocks.class); - /** Marks some written blocks with the placement's markers. */ - public static final PlacementStage MARKERS = Stage.placement("iris:blocks/markers"); - /** Milestone: stages requiring it run after the object and its markers are written. */ - public static final PlacementStage COMPLETE = Stage.placement("iris:blocks/complete"); - - private BlocksStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/bore/BoreStages.java b/src/main/java/art/arcane/iris/builtin/bore/BoreStages.java deleted file mode 100644 index 3d7357387..000000000 --- a/src/main/java/art/arcane/iris/builtin/bore/BoreStages.java +++ /dev/null @@ -1,30 +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.builtin.bore; - -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:bore}: clearing the object's volume before its blocks are written. */ -public final class BoreStages { - public static final PlacementStage CLEAR = Stage.placement("iris:bore/clear"); - - private BoreStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarveStages.java b/src/main/java/art/arcane/iris/builtin/carve/CarveStages.java deleted file mode 100644 index d63809438..000000000 --- a/src/main/java/art/arcane/iris/builtin/carve/CarveStages.java +++ /dev/null @@ -1,34 +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.builtin.carve; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.MantleStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:carve}: caves, planned in the mantle and cut into each chunk's terrain. */ -public final class CarveStages { - /** Plans the caves of the dimension's cave profiles into the mantle, one block into each neighbor. */ - public static final MantleStage CAVES = Stage.mantle("iris:carve/caves"); - /** Cuts the planned caves out of the chunk's terrain and decorates their floors and ceilings. */ - public static final ChunkStage APPLY = Stage.chunk("iris:carve/apply"); - - private CarveStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/custom/CustomStages.java b/src/main/java/art/arcane/iris/builtin/custom/CustomStages.java deleted file mode 100644 index c7ca96c7b..000000000 --- a/src/main/java/art/arcane/iris/builtin/custom/CustomStages.java +++ /dev/null @@ -1,31 +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.builtin.custom; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:custom}: blocks of content plugins, which the server places after generation. */ -public final class CustomStages { - /** Records the chunk's custom blocks so the server can place them once the chunk exists. */ - public static final ChunkStage BLOCKS = Stage.chunk("iris:custom/blocks"); - - private CustomStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java deleted file mode 100644 index 1158ada20..000000000 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecorantStages.java +++ /dev/null @@ -1,31 +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.builtin.decorant; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:decorant}: the decorators of biomes, such as grass, flowers and cave ceilings. */ -public final class DecorantStages { - /** Places every column's surface, sea, shore and cave decorators. */ - public static final ChunkStage DECORATE = Stage.chunk("iris:decorant/decorate"); - - private DecorantStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java deleted file mode 100644 index e61abc3ca..000000000 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositStages.java +++ /dev/null @@ -1,34 +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.builtin.deposit; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:deposit}: ores and other deposits. */ -public final class DepositStages { - /** - * Places the deposits every level declares at the chunk's centre column, the dimension's, the region's and - * the biome's, each with its own clumps. Active where any column of the chunk has deposits. - */ - public static final ChunkStage ORES = Stage.chunk("iris:deposit/ores"); - - private DepositStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java deleted file mode 100644 index 19f1282e9..000000000 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingStages.java +++ /dev/null @@ -1,36 +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.builtin.floating; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.MantleStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:floating}: the floating islands of floating child biomes. */ -public final class FloatingStages { - /** Places the objects on and under the islands into the mantle, after the dimension's other objects. */ - public static final MantleStage OBJECTS = Stage.mantle("iris:floating/objects"); - /** Writes the islands' solid blocks. */ - public static final ChunkStage SOLIDS = Stage.chunk("iris:floating/solids"); - /** Decorates the islands' tops and bottoms once the chunk's own decoration is done. */ - public static final ChunkStage DECORATE = Stage.chunk("iris:floating/decorate"); - - private FloatingStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/matter/MatterStages.java b/src/main/java/art/arcane/iris/builtin/matter/MatterStages.java deleted file mode 100644 index 8becc062b..000000000 --- a/src/main/java/art/arcane/iris/builtin/matter/MatterStages.java +++ /dev/null @@ -1,31 +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.builtin.matter; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:matter}: the blocks the mantle planned for a chunk, such as objects and structures. */ -public final class MatterStages { - /** Copies the chunk's planned mantle blocks into it. */ - public static final ChunkStage INSERT = Stage.chunk("iris:matter/insert"); - - private MatterStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java deleted file mode 100644 index 9917dd1ab..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectStages.java +++ /dev/null @@ -1,31 +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.builtin.objects; - -import com.volmit.stage.MantleStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:objects}: the objects the dimension's regions and biomes place. */ -public final class ObjectStages { - /** Places surface, cave and upper-dimension objects into the mantle, after the caves they anchor in. */ - public static final MantleStage PLACE = Stage.mantle("iris:objects/place"); - - private ObjectStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index a21ac18f4..49b8bca4e 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -17,15 +17,15 @@ */ /** - * The public face of Iris's built-in modules: their stage constants and the settings and output types - * of those stages. {@link art.arcane.iris.core.modules.IrisModuleHost} exposes this package, with its + * The public face of Iris's built-in modules: every stage constant, in {@link art.arcane.iris.builtin.IrisStages}, + * and the settings and output types of those stages. {@link art.arcane.iris.core.modules.IrisModuleHost} exposes this package, with its * subpackages, to pack modules, so a pack jar can {@code requires(...)} a built-in stage and read its * output. Everything here is part of what packs compile against. *

* Keep implementation out of it: stage bodies and anything that uses Iris internals live in the - * built-in module classes outside this package, which packs cannot see. One subpackage per built-in - * module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} for - * {@code iris:deposit}. + * built-in module classes outside this package, which packs cannot see. Settings and output types go in one + * subpackage per built-in module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} + * for {@code iris:deposit}. *

* Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A * pack module can require such a stage to run after it, but cannot read its output: the pack load rejects diff --git a/src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java b/src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java deleted file mode 100644 index d20a500f3..000000000 --- a/src/main/java/art/arcane/iris/builtin/perfection/PerfectionStages.java +++ /dev/null @@ -1,31 +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.builtin.perfection; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:perfection}: the last touches on an overworld chunk's blocks. */ -public final class PerfectionStages { - /** Hides ores when the dimension asks, then removes decorations that nothing holds up. */ - public static final ChunkStage SURFACE = Stage.chunk("iris:perfection/surface"); - - private PerfectionStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/post/PostStages.java b/src/main/java/art/arcane/iris/builtin/post/PostStages.java deleted file mode 100644 index 8c45102c1..000000000 --- a/src/main/java/art/arcane/iris/builtin/post/PostStages.java +++ /dev/null @@ -1,31 +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.builtin.post; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:post}: smoothing a chunk's surface after carving. */ -public final class PostStages { - /** Fills single-block holes, places slabs and walls on steps and settles snow. */ - public static final ChunkStage SMOOTH = Stage.chunk("iris:post/smooth"); - - private PostStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java b/src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java deleted file mode 100644 index 47a67271d..000000000 --- a/src/main/java/art/arcane/iris/builtin/prepare/PrepareStages.java +++ /dev/null @@ -1,35 +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.builtin.prepare; - -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.PreparedPlacement; -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ -public final class PrepareStages { - /** The settings the placement uses: the requested ones, turned downhill when they ask to face the slope. Rejects {@code slope}. */ - public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", IrisObjectPlacement.class); - /** The random rotation, translation and height offset, chosen once per placement. */ - public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); - - private PrepareStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/snow/SnowStages.java b/src/main/java/art/arcane/iris/builtin/snow/SnowStages.java deleted file mode 100644 index 2a51efd05..000000000 --- a/src/main/java/art/arcane/iris/builtin/snow/SnowStages.java +++ /dev/null @@ -1,30 +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.builtin.snow; - -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:snow}: snow on the object, after its stilt or terrain bend. */ -public final class SnowStages { - public static final PlacementStage COVER = Stage.placement("iris:snow/cover"); - - private SnowStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java b/src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java deleted file mode 100644 index a3f9a78f8..000000000 --- a/src/main/java/art/arcane/iris/builtin/stilt/StiltStages.java +++ /dev/null @@ -1,34 +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.builtin.stilt; - -import com.volmit.stage.BlockStage; -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:stilt}: the stilts of the stilt and ceiling placement modes. */ -public final class StiltStages { - /** Finds the layers to repeat. */ - public static final BlockStage LAYERS = Stage.placementBlock("iris:stilt/layers", StiltLayers.class); - /** Grows the stilt once the object is written. */ - public static final PlacementStage FILL = Stage.placement("iris:stilt/fill"); - - private StiltStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureStages.java b/src/main/java/art/arcane/iris/builtin/structure/StructureStages.java deleted file mode 100644 index 5ea26c630..000000000 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureStages.java +++ /dev/null @@ -1,31 +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.builtin.structure; - -import com.volmit.stage.MantleStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:structure}: Iris structures, assembled from pieces. */ -public final class StructureStages { - /** Places the structures of the dimension, its regions and biomes into the mantle, after objects and floating objects. */ - public static final MantleStage PLACE = Stage.mantle("iris:structure/place"); - - private StructureStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java deleted file mode 100644 index da7131982..000000000 --- a/src/main/java/art/arcane/iris/builtin/terrain/TerrainStages.java +++ /dev/null @@ -1,31 +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.builtin.terrain; - -import com.volmit.stage.ChunkStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:terrain}: the solid ground, fluids and biome layers of a chunk. */ -public final class TerrainStages { - /** Fills each column from bedrock up to its height and the fluid height, with its biome's layers. */ - public static final ChunkStage SHAPE = Stage.chunk("iris:terrain/shape"); - - private TerrainStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java deleted file mode 100644 index 2c23b4b73..000000000 --- a/src/main/java/art/arcane/iris/builtin/vacuum/VacuumStages.java +++ /dev/null @@ -1,30 +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.builtin.vacuum; - -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:vacuum}: bending the terrain to meet objects of the vacuum placement modes. */ -public final class VacuumStages { - public static final PlacementStage TERRAIN = Stage.placement("iris:vacuum/terrain"); - - private VacuumStages() { - } -} diff --git a/src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java b/src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java deleted file mode 100644 index 3446c39bc..000000000 --- a/src/main/java/art/arcane/iris/builtin/validate/ValidateStages.java +++ /dev/null @@ -1,37 +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.builtin.validate; - -import com.volmit.stage.PlacementStage; -import com.volmit.stage.Stage; - -/** Module {@code iris:validate}: the checks that reject a placement before anything is written, in this order. */ -public final class ValidateStages { - /** Rejects {@code bedrock-anchor} and {@code surface-support}. */ - public static final PlacementStage SURFACE = Stage.placement("iris:validate/surface"); - /** Rejects {@code underwater-anchor}, {@code cave-clearance}, {@code fluid-height} and {@code height-clamp}. */ - public static final PlacementStage LIMITS = Stage.placement("iris:validate/limits"); - /** Rejects {@code native-structure}, even for placements that force their way past the other checks. */ - public static final PlacementStage STRUCTURES = Stage.placement("iris:validate/structures"); - /** Rejects {@code object-collision}. */ - public static final PlacementStage COLLISIONS = Stage.placement("iris:validate/collisions"); - - private ValidateStages() { - } -} diff --git a/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java b/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java index 1ef7c0591..429052981 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.biome.BiomeStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -55,7 +55,7 @@ public final class BiomeModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(BiomeStages.WRITE).run(BiomeModule::write); + graph.define(IrisStages.Biome.WRITE).run(BiomeModule::write); } private static void write(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 26725b972..25647cc71 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.decorant.DecorantStages; -import art.arcane.iris.builtin.matter.MatterStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; @@ -56,7 +55,7 @@ public final class DecorantModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(DecorantStages.DECORATE).requires(MatterStages.INSERT).run(DecorantModule::decorate); + graph.define(IrisStages.Decorant.DECORATE).requires(IrisStages.Matter.INSERT).run(DecorantModule::decorate); } private static void decorate(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 7b9812d60..4693cb44b 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.terrain.TerrainStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.IrisComplex; @@ -58,7 +58,7 @@ public final class TerrainModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(TerrainStages.SHAPE).run(TerrainModule::shape); + graph.define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); } private static void shape(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index b1b1734fc..9bd2a2fce 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.carve.CarveStages; -import art.arcane.iris.builtin.objects.ObjectStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; @@ -44,7 +43,7 @@ public final class ObjectModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(ObjectStages.PLACE).requires(CarveStages.CAVES).reach(ObjectModule::reach).run(ObjectModule::place); + graph.define(IrisStages.Objects.PLACE).requires(IrisStages.Carve.CAVES).reach(ObjectModule::reach).run(ObjectModule::place); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 5915045a2..1c606762c 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -18,9 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.floating.FloatingStages; -import art.arcane.iris.builtin.objects.ObjectStages; -import art.arcane.iris.builtin.structure.StructureStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; @@ -45,7 +43,7 @@ public final class StructureModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(StructureStages.PLACE).requires(ObjectStages.PLACE).softAfter(FloatingStages.OBJECTS.ref()) + graph.define(IrisStages.Structure.PLACE).requires(IrisStages.Objects.PLACE).softAfter(IrisStages.Floating.OBJECTS.ref()) .reach(StructureModule::reach).run(StructureModule::place); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index b32ab59d9..2cb64c468 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.carve.CarveStages; -import art.arcane.iris.builtin.terrain.TerrainStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.engine.mantle.components.CaveCarving; @@ -49,8 +48,8 @@ public final class CarveModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(CarveStages.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); - graph.define(CarveStages.APPLY).requires(TerrainStages.SHAPE).run(CarveModule::applyCaves); + graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); + graph.define(IrisStages.Carve.APPLY).requires(IrisStages.Terrain.SHAPE).run(CarveModule::applyCaves); } private static void planCaves(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java index d59e879ea..a88cf7566 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.custom.CustomStages; -import art.arcane.iris.builtin.perfection.PerfectionStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.link.Identifier; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.framework.Engine; @@ -52,7 +51,7 @@ public final class CustomModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(CustomStages.BLOCKS).requires(PerfectionStages.SURFACE).run(CustomModule::record); + graph.define(IrisStages.Custom.BLOCKS).requires(IrisStages.Perfection.SURFACE).run(CustomModule::record); } private static void record(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index cdbc14311..e4116ad37 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -18,10 +18,8 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.deposit.DepositSettings; -import art.arcane.iris.builtin.deposit.DepositStages; -import art.arcane.iris.builtin.floating.FloatingStages; -import art.arcane.iris.builtin.terrain.TerrainStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import com.volmit.IrisModule; @@ -52,10 +50,10 @@ public final class DepositModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(DepositStages.ORES) + graph.define(IrisStages.Deposit.ORES) .when(DepositSettings.class) - .requires(TerrainStages.SHAPE) - .softAfter(FloatingStages.SOLIDS.ref()) + .requires(IrisStages.Terrain.SHAPE) + .softAfter(IrisStages.Floating.SOLIDS.ref()) .run(DepositModule::place); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index def0ddae0..61687340b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -18,10 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.decorant.DecorantStages; -import art.arcane.iris.builtin.floating.FloatingStages; -import art.arcane.iris.builtin.objects.ObjectStages; -import art.arcane.iris.builtin.post.PostStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; @@ -51,10 +48,10 @@ public final class FloatingModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(FloatingStages.OBJECTS).softAfter(ObjectStages.PLACE.ref()).reach(FloatingModule::objectReach) + graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE.ref()).reach(FloatingModule::objectReach) .run(FloatingModule::objects); - graph.define(FloatingStages.SOLIDS).requires(PostStages.SMOOTH).run(FloatingModule::solids); - graph.define(FloatingStages.DECORATE).requires(DecorantStages.DECORATE).run(FloatingModule::decorate); + graph.define(IrisStages.Floating.SOLIDS).requires(IrisStages.Post.SMOOTH).run(FloatingModule::solids); + graph.define(IrisStages.Floating.DECORATE).requires(IrisStages.Decorant.DECORATE).run(FloatingModule::decorate); } private static void objects(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java index baa03b22e..4bbb8e0cc 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -18,9 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.deposit.DepositStages; -import art.arcane.iris.builtin.floating.FloatingStages; -import art.arcane.iris.builtin.matter.MatterStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.framework.Engine; @@ -52,9 +50,9 @@ public final class MatterModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(MatterStages.INSERT) - .requires(FloatingStages.SOLIDS) - .softAfter(DepositStages.ORES.ref()) + graph.define(IrisStages.Matter.INSERT) + .requires(IrisStages.Floating.SOLIDS) + .softAfter(IrisStages.Deposit.ORES.ref()) .run(MatterModule::insert); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index 2019f94f0..6e45f193f 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.floating.FloatingStages; -import art.arcane.iris.builtin.perfection.PerfectionStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; @@ -60,7 +59,7 @@ public final class PerfectionModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(PerfectionStages.SURFACE).requires(FloatingStages.DECORATE).run(PerfectionModule::perfect); + graph.define(IrisStages.Perfection.SURFACE).requires(IrisStages.Floating.DECORATE).run(PerfectionModule::perfect); } private static void perfect(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index 3a09e3381..a39f8546f 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.carve.CarveStages; -import art.arcane.iris.builtin.post.PostStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -40,7 +39,7 @@ public final class PostModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(PostStages.SMOOTH).requires(CarveStages.APPLY).run(PostModule::smooth); + graph.define(IrisStages.Post.SMOOTH).requires(IrisStages.Carve.APPLY).run(PostModule::smooth); } private static void smooth(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index 4f48b0b8d..4a1afbbbd 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -18,10 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.AnchorHeight; -import art.arcane.iris.builtin.anchor.AnchorStages; -import art.arcane.iris.builtin.prepare.PrepareStages; -import art.arcane.iris.builtin.validate.ValidateStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.terrain.carving.CarvingMode; @@ -46,17 +44,17 @@ public final class AnchorModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(AnchorStages.HEIGHT) - .requires(PrepareStages.TRANSFORMS) + graph.define(IrisStages.Anchor.HEIGHT) + .requires(IrisStages.Prepare.TRANSFORMS) .produce(AnchorModule::height); - graph.define(AnchorStages.FINAL) - .requires(AnchorStages.HEIGHT, ValidateStages.COLLISIONS) + graph.define(IrisStages.Anchor.FINAL) + .requires(IrisStages.Anchor.HEIGHT, IrisStages.Validate.COLLISIONS) .produce(AnchorModule::finalHeight); } private static AnchorHeight height(PlacementStageContext context) { IrisPlacement placement = IrisPlacement.current(); - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); boolean structurePiece = prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE; if (!config.isFromBottom() && placement.requestedY() < 0) { @@ -80,7 +78,7 @@ public final class AnchorModule implements IrisModule { } private static AnchorHeight finalHeight(PlacementStageContext context) { - int y = context.output(AnchorStages.HEIGHT).y() + context.output(PrepareStages.TRANSFORMS).randomY(); + int y = context.output(IrisStages.Anchor.HEIGHT).y() + context.output(IrisStages.Prepare.TRANSFORMS).randomY(); IrisPlacement.current().anchoredAt(y); return new AnchorHeight(y); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 2a87834b2..95acd4342 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,12 +18,9 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.AnchorStages; -import art.arcane.iris.builtin.blocks.BlocksStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.builtin.bore.BoreStages; -import art.arcane.iris.builtin.prepare.PrepareStages; import art.arcane.iris.core.modules.BlockEntities; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.object.marker.IrisMarker; @@ -70,26 +67,26 @@ public final class BlocksModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(BlocksStages.WRITE) - .requires(PrepareStages.TRANSFORMS, AnchorStages.FINAL, BoreStages.CLEAR) + graph.define(IrisStages.Blocks.WRITE) + .requires(IrisStages.Prepare.TRANSFORMS, IrisStages.Anchor.FINAL, IrisStages.Bore.CLEAR) .accumulate(WrittenBlocks::new, BlocksModule::write); - graph.define(BlocksStages.MARKERS) - .requires(BlocksStages.WRITE, PrepareStages.TRANSFORMS) + graph.define(IrisStages.Blocks.MARKERS) + .requires(IrisStages.Blocks.WRITE, IrisStages.Prepare.TRANSFORMS) .run(BlocksModule::placeMarkers); - graph.define(BlocksStages.COMPLETE) - .requires(BlocksStages.WRITE, BlocksStages.MARKERS) + graph.define(IrisStages.Blocks.COMPLETE) + .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.MARKERS) .run(context -> { }); } private static void write(BlockStageContext context, WrittenBlocks written) { IrisPlacement placement = IrisPlacement.current(); - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); PlacementWorld world = new PlacementWorld(context.access(), placement.states()); ObjectBlock block = context.block(); BlockPosition offset = prepared.transform(block.position()); - int anchorY = context.output(AnchorStages.FINAL).y(); + int anchorY = context.output(IrisStages.Anchor.FINAL).y(); PlatformBlockState data = sourceState(block, placement, prepared); TileData tile = block.blockEntity().map(BlockEntities::tileOf).orElse(null); if (!config.getEdit().isEmpty()) { @@ -189,12 +186,12 @@ public final class BlocksModule implements IrisModule { */ private static void placeMarkers(PlacementStageContext context) { IrisPlacement placement = IrisPlacement.current(); - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); if (config.getMarkers().isEmpty() || prepared.terrain().getEngine() == null) { return; } - WrittenBlocks written = context.output(BlocksStages.WRITE); + WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); PlacementWorld world = new PlacementWorld(context.access(), placement.states()); RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java index cb8d8dbab..838153804 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -18,10 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.AnchorStages; -import art.arcane.iris.builtin.bore.BoreStages; -import art.arcane.iris.builtin.prepare.PrepareStages; -import art.arcane.iris.builtin.validate.ValidateStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; import com.volmit.IrisModule; @@ -38,19 +35,19 @@ public final class BoreModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(BoreStages.CLEAR) - .requires(AnchorStages.FINAL, ValidateStages.COLLISIONS) + graph.define(IrisStages.Bore.CLEAR) + .requires(IrisStages.Anchor.FINAL, IrisStages.Validate.COLLISIONS) .run(BoreModule::clear); } private static void clear(PlacementStageContext context) { - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); if (!config.isBore()) { return; } IrisPlacement placement = IrisPlacement.current(); - WorldVolume volume = WorldVolume.of(placement, prepared, context.output(AnchorStages.FINAL).y()); + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.FINAL).y()); PlacementWorld world = new PlacementWorld(context.access(), placement.states()); for (int x = volume.minX(); x <= volume.maxX(); x++) { for (int y = volume.minY() - config.getBoreExtendMinY(); y <= volume.maxY() + config.getBoreExtendMaxY(); y++) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index f4b2c725f..6d1ed38ab 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; @@ -54,9 +54,9 @@ public final class PrepareModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(PrepareStages.SLOPE).produce(PrepareModule::slope); - graph.define(PrepareStages.TRANSFORMS) - .requires(PrepareStages.SLOPE) + graph.define(IrisStages.Prepare.SLOPE).produce(PrepareModule::slope); + graph.define(IrisStages.Prepare.TRANSFORMS) + .requires(IrisStages.Prepare.SLOPE) .produce(PrepareModule::transforms); } @@ -107,7 +107,7 @@ public final class PrepareModule implements IrisModule { private static PreparedPlacement transforms(PlacementStageContext context) { IrisPlacement placement = IrisPlacement.current(); - IrisObjectPlacement config = context.output(PrepareStages.SLOPE); + IrisObjectPlacement config = context.output(IrisStages.Prepare.SLOPE); IrisObject object = placement.object(); RNG rng = new RNG(context.random().nextLong()); IObjectPlacer terrain = config.getHeightmap() == null ? placement.placer() diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java index 40dfa641e..839c1ab0d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -18,12 +18,8 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.blocks.BlocksStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.builtin.prepare.PrepareStages; -import art.arcane.iris.builtin.snow.SnowStages; -import art.arcane.iris.builtin.stilt.StiltStages; -import art.arcane.iris.builtin.vacuum.VacuumStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.volmlib.util.math.RNG; @@ -51,15 +47,15 @@ public final class SnowModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(SnowStages.COVER) - .requires(BlocksStages.WRITE, BlocksStages.COMPLETE, PrepareStages.TRANSFORMS) - .softAfter(StiltStages.FILL.ref(), VacuumStages.TERRAIN.ref()) + graph.define(IrisStages.Snow.COVER) + .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) + .softAfter(IrisStages.Stilt.FILL.ref(), IrisStages.Vacuum.TERRAIN.ref()) .run(SnowModule::cover); } private static void cover(PlacementStageContext context) { - double snow = context.output(PrepareStages.TRANSFORMS).config().getSnow(); - WrittenBlocks written = context.output(BlocksStages.WRITE); + double snow = context.output(IrisStages.Prepare.TRANSFORMS).config().getSnow(); + WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); if (!(snow > 0) || written.isEmpty()) { return; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 096920cf2..eee31d184 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -18,12 +18,8 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.AnchorStages; -import art.arcane.iris.builtin.blocks.BlocksStages; -import art.arcane.iris.builtin.bore.BoreStages; -import art.arcane.iris.builtin.prepare.PrepareStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.stilt.StiltLayers; -import art.arcane.iris.builtin.stilt.StiltStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.object.prefab.IrisObjectShaping; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; @@ -70,18 +66,18 @@ public final class StiltModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(StiltStages.LAYERS) - .requires(PrepareStages.TRANSFORMS) + graph.define(IrisStages.Stilt.LAYERS) + .requires(IrisStages.Prepare.TRANSFORMS) // Ordered after boring only so it shares the block pass that writes the object. - .softAfter(BoreStages.CLEAR.ref()) + .softAfter(IrisStages.Bore.CLEAR.ref()) .accumulate(StiltLayers::new, StiltModule::collectLayer); - graph.define(StiltStages.FILL) - .requires(StiltStages.LAYERS, AnchorStages.FINAL, BlocksStages.COMPLETE) + graph.define(IrisStages.Stilt.FILL) + .requires(IrisStages.Stilt.LAYERS, IrisStages.Anchor.FINAL, IrisStages.Blocks.COMPLETE) .run(StiltModule::fill); } private static void collectLayer(BlockStageContext context, StiltLayers layers) { - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); if (prepared.mode().stilt() == StiltShape.NONE) { return; } @@ -93,9 +89,9 @@ public final class StiltModule implements IrisModule { } private static void fill(PlacementStageContext context) { - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); StiltShape shape = prepared.mode().stilt(); - StiltLayers layers = context.output(StiltStages.LAYERS); + StiltLayers layers = context.output(IrisStages.Stilt.LAYERS); if (shape == StiltShape.NONE || layers.isEmpty()) { return; } @@ -127,7 +123,7 @@ public final class StiltModule implements IrisModule { this.shape = prepared.mode().stilt(); this.world = new PlacementWorld(context.access(), placement.states()); this.rng = new RNG(context.random().nextLong()); - this.anchorY = context.output(AnchorStages.FINAL).y(); + this.anchorY = context.output(IrisStages.Anchor.FINAL).y(); this.layerY = shape == StiltShape.CEILING ? layers.topY() : layers.bottomY(); this.erode = shape == StiltShape.ERODE ? ErodeShape.of(layers.bottom()) : null; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index d7d08ae17..2865cc31a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -18,10 +18,8 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.blocks.BlocksStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.builtin.prepare.PrepareStages; -import art.arcane.iris.builtin.vacuum.VacuumStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; @@ -53,15 +51,15 @@ public final class VacuumModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(VacuumStages.TERRAIN) - .requires(BlocksStages.WRITE, BlocksStages.COMPLETE, PrepareStages.TRANSFORMS) + graph.define(IrisStages.Vacuum.TERRAIN) + .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) .reach(IrisObjectVacuum.MAX_RADIUS_BLOCKS) .run(VacuumModule::bendTerrain); } private static void bendTerrain(PlacementStageContext context) { - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); - WrittenBlocks written = context.output(BlocksStages.WRITE); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); Engine engine = prepared.terrain().getEngine(); if (!prepared.mode().isVacuum() || written.isEmpty() || engine == null) { return; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 5e4f0ef66..915094e2f 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,9 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.AnchorStages; -import art.arcane.iris.builtin.prepare.PrepareStages; -import art.arcane.iris.builtin.validate.ValidateStages; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.NativeStructureVolume; @@ -57,29 +55,29 @@ public final class ValidateModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(ValidateStages.SURFACE) - .requires(AnchorStages.HEIGHT) + graph.define(IrisStages.Validate.SURFACE) + .requires(IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkSurface); - graph.define(ValidateStages.LIMITS) - .requires(ValidateStages.SURFACE, AnchorStages.HEIGHT) + graph.define(IrisStages.Validate.LIMITS) + .requires(IrisStages.Validate.SURFACE, IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkLimits); - graph.define(ValidateStages.STRUCTURES) - .requires(ValidateStages.LIMITS, AnchorStages.HEIGHT) + graph.define(IrisStages.Validate.STRUCTURES) + .requires(IrisStages.Validate.LIMITS, IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkNativeStructures); - graph.define(ValidateStages.COLLISIONS) - .requires(ValidateStages.STRUCTURES, AnchorStages.HEIGHT) + graph.define(IrisStages.Validate.COLLISIONS) + .requires(IrisStages.Validate.STRUCTURES, IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkCollisions); } private static void checkSurface(PlacementStageContext context) { IrisPlacement placement = IrisPlacement.current(); - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); if (config.isForcePlace() || config.isFromBottom() || prepared.mode() == ObjectPlaceMode.FLOATING || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { return; } - int y = context.output(AnchorStages.HEIGHT).y(); + int y = context.output(IrisStages.Anchor.HEIGHT).y(); boolean sampled = placement.requestedY() < 0; if (sampled && config.getCarvingSupport().supportsSurface() && isOnBedrock(prepared, y)) { warnImplausibleBedrockPlacement(placement, config, y); @@ -109,12 +107,12 @@ public final class ValidateModule implements IrisModule { private static void checkLimits(PlacementStageContext context) { IrisPlacement placement = IrisPlacement.current(); - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); if (config.isForcePlace() || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { return; } - int y = context.output(AnchorStages.HEIGHT).y(); + int y = context.output(IrisStages.Anchor.HEIGHT).y(); int rotated = prepared.rotatedCenterY(); int translated = prepared.translatedCenterY(); if (placement.requestedY() < 0 && prepared.mode() != ObjectPlaceMode.FLOATING && !config.isUnderwater() @@ -131,11 +129,11 @@ public final class ValidateModule implements IrisModule { } private static void checkNativeStructures(PlacementStageContext context) { - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); if (prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { return; } - int y = context.output(AnchorStages.HEIGHT).y() + prepared.randomY(); + int y = context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY(); if (meetsNativeStructure(context, IrisPlacement.current(), prepared, y)) { context.reject("native-structure"); } @@ -200,7 +198,7 @@ public final class ValidateModule implements IrisModule { private static void checkCollisions(PlacementStageContext context) { IrisPlacement placement = IrisPlacement.current(); - PreparedPlacement prepared = context.output(PrepareStages.TRANSFORMS); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); if (config.isForcePlace() || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { @@ -210,7 +208,7 @@ public final class ValidateModule implements IrisModule { if (engine == null) { throw new IllegalStateException("Object placement requires active Iris data for collision settings."); } - WorldVolume volume = WorldVolume.of(placement, prepared, context.output(AnchorStages.HEIGHT).y() + prepared.randomY()); + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY()); if (collidesWithForbiddenObject(engine, config, volume)) { context.reject("object-collision"); } From 98562bf9622b5a275b0b2ba78493e46f44dad835 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 20:36:10 +0200 Subject: [PATCH 021/139] Own structures, jigsaw pools and pieces as resource kinds of iris:structure and check them with its validator, which takes over Iris's structure graph and native replacement checks --- README.md | 5 + .../framework/IrisStructureLocator.java | 9 +- .../NativeReplacementValidation.java | 393 ++++++++++++++++++ .../structure/StructureGraphResolver.java | 4 +- .../structure/StructureGraphValidation.java | 324 +++++++++++++++ .../structure/StructureResources.java | 94 +++++ .../structure/StructureValidator.java | 92 ++++ .../mantle/components/StructureModule.java | 13 + .../mantle/components/StructurePlacing.java | 3 +- 9 files changed, 930 insertions(+), 7 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java diff --git a/README.md b/README.md index dbb14d9f4..c2b3b66e1 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,11 @@ mantle components outside the stage graph any more. Their stage constants, and t types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live beside the features they replace. +Built-in modules also own pack resources and checks of their own. `iris:structure` reads structures, jigsaw +pools and jigsaw pieces as resource kinds (`StructureResources`), from the folders and files packs have always +used, and checks them with its validator (`StructureValidator`: assembly samples and vanilla structure +replacement) wherever Iris validates a pack; Iris core has no loader or validator of its own for them any more. + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index b6975b753..a3e1672bb 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.framework; +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; @@ -502,7 +503,7 @@ public final class IrisStructureLocator { if (selectedKey == null || selectedKey.isBlank()) { throw new IllegalStateException("Iris structure placement selected a blank structure key"); } - IrisStructure structure = engine.getData().load(IrisStructure.class, selectedKey, false); + IrisStructure structure = StructureResources.structure(engine.getData(), selectedKey); if (structure == null) { throw new IllegalStateException("Iris structure placement references missing structure '" + selectedKey + "'"); @@ -1024,7 +1025,7 @@ public final class IrisStructureLocator { if (structureKey == null || structureKey.isBlank()) { continue; } - IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { continue; } @@ -1085,7 +1086,7 @@ public final class IrisStructureLocator { continue; } for (String structureKey : placement.getStructures()) { - IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { throw new IllegalStateException( "Iris structure placement references missing structure '" + structureKey + "'"); @@ -1208,7 +1209,7 @@ public final class IrisStructureLocator { ? "REPLACE_SOURCE contains a blank Iris structure reference" : "Iris structure placement contains a blank structure reference"); } - IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { throw new IllegalStateException((replacesNative ? "REPLACE_SOURCE references missing Iris structure '" 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 new file mode 100644 index 000000000..22cc602f9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java @@ -0,0 +1,393 @@ +/* + * 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.pack.PackValidationIo; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +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 == ObjectPlaceMode.STRUCTURE_PIECE + || placeMode == ObjectPlaceMode.FLOATING; + if (!exactY) { + continue; + } + + long minimumYOffset = sampled.minimumYOffset(); + long maximumYOffset = sampled.maximumYOffset(); + boolean surfaceAligned = !placementBounds.underground() + && sampled.pieceCount() > 1 + && placeMode != ObjectPlaceMode.STRUCTURE_PIECE + && placeMode != ObjectPlaceMode.FLOATING; + 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/StructureGraphResolver.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java index e9688dcea..5b96dd060 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java @@ -32,12 +32,12 @@ final class IrisDataStructureGraphResolver implements StructureGraphResolver { @Override public IrisJigsawPool loadPool(String key) { - return data.load(IrisJigsawPool.class, key, false); + return StructureResources.pool(data, key); } @Override public IrisJigsawPiece loadPiece(String key) { - return data.load(IrisJigsawPiece.class, key, false); + return StructureResources.piece(data, key); } @Override 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 new file mode 100644 index 000000000..715215451 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java @@ -0,0 +1,324 @@ +/* + * 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(IrisStructure.class)) { + 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/StructureResources.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java new file mode 100644 index 000000000..e4f22b51e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -0,0 +1,94 @@ +/* + * 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.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kinds of module {@code iris:structure}, 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/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/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/piece", "jigsaw-pieces", IrisJigsawPiece.class); + + private StructureResources() { + } + + /** Every resource kind of the structure module. */ + 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 keys(data, 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.key(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 data.getPackResources().ids(kind.type()).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 new file mode 100644 index 000000000..d98603420 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java @@ -0,0 +1,92 @@ +/* + * 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/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 1c606762c..8611724c6 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -22,6 +22,9 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.framework.structure.StructureValidator; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.PackSettings; @@ -32,6 +35,10 @@ import com.volmit.stage.StageGraph; * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear * where they intersect, and after floating objects. A port of what was Iris's structure mantle component, its * work done by {@link StructurePlacing}, one per engine runtime. Its reach is the pack's largest structure. + *

+ * The module owns the pack's structures, jigsaw pools and jigsaw pieces as resource kinds + * ({@link StructureResources}), read from the folders packs have always used, and checks them with + * {@link StructureValidator} wherever Iris validates a pack. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; @@ -47,6 +54,12 @@ public final class StructureModule implements IrisModule { .reach(StructureModule::reach).run(StructureModule::place); } + @Override + public void register(FeatureRegistry registry) { + StructureResources.kinds().forEach(registry::registerResourceKind); + registry.registerValidator(new StructureValidator()); + } + private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); 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 index fede31277..c09f31c7a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.mantle.components; +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.iris.core.loader.IrisData; @@ -608,7 +609,7 @@ public class StructurePlacing { || terrain.resolvedMode() == IrisStructureTerrainMode.BORE ? Math.max(0, terrain.getHorizontalPadding()) : 0; for (String key : placement.getStructures()) { - IrisStructure structure = engine.getData().load(IrisStructure.class, key, false); + IrisStructure structure = StructureResources.structure(engine.getData(), key); if (structure != null) { max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding); } From f69d9128d51a7233e439af95e1c56bda27870cab Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 14:32:17 +0200 Subject: [PATCH 022/139] Make deposit settings IrisApi types only: DepositGenerator and its enums in the builtin package with BlockSpec palettes, the palette, ore, replace and clump logic in ResolvedDeposit, and IrisDepositGenerator deleted --- README.md | 5 + .../builtin/deposit/DepositBiomeScope.java | 29 + .../builtin/deposit/DepositGenerator.java | 227 ++++++++ .../deposit/DepositHeightDistribution.java | 31 ++ .../deposit/DepositPlacementScope.java | 31 ++ .../iris/builtin/deposit/DepositSettings.java | 10 +- .../iris/builtin/deposit/DepositShape.java | 31 ++ .../iris/engine/modifier/DepositModule.java | 6 +- .../iris/engine/modifier/DepositPlacer.java | 67 ++- .../iris/engine/modifier/ResolvedDeposit.java | 408 ++++++++++++++ .../deposit/IrisDepositBiomeScope.java | 11 - .../terrain/deposit/IrisDepositGenerator.java | 525 ------------------ .../IrisDepositHeightDistribution.java | 13 - .../deposit/IrisDepositPlacementScope.java | 13 - .../terrain/deposit/IrisDepositShape.java | 13 - 15 files changed, 808 insertions(+), 612 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java diff --git a/README.md b/README.md index c2b3b66e1..14f5443ee 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,11 @@ pools and jigsaw pieces as resource kinds (`StructureResources`), from the folde used, and checks them with its validator (`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris validates a pack; Iris core has no loader or validator of its own for them any more. +Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types +only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in +`art.arcane.iris.builtin.deposit`), and packs write the same `deposits` JSON as before. What needs Iris (resolving the +palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java new file mode 100644 index 000000000..ec7e9cb86 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java @@ -0,0 +1,29 @@ +/* + * 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.builtin.deposit; + +import com.volmit.config.Desc; + +@Desc("Selects which biome identity is checked by a deposit's include and exclude filters.") +public enum DepositBiomeScope { + @Desc("Checks the surface biome selected for the deposit column.") + SURFACE, + @Desc("Checks the cave biome selected at the deposit origin.") + CAVE +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java new file mode 100644 index 000000000..ce176754c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java @@ -0,0 +1,227 @@ +/* + * 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.builtin.deposit; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** + * One kind of deposit a dimension, region or biome generates, as packs write it in {@code "deposits": [...]} or under + * {@code snippet/deposit/}: how many clumps of which blocks, how large, at which heights and in which biomes. A value + * of IrisApi types only; the deposit module builds the clumps and resolves the blocks. + */ +@Snippet("deposit") +@Desc("Creates ore & other block deposits underground") +public final class DepositGenerator { + private static final int MAX_CLUMP_DIMENSION = 11; + + @Required + @MinNumber(-8192) + @MaxNumber(8192) + @Desc("The inclusive minimum origin height in engine-local Y, where 0 is the bottom of the dimension. Negative values let an unclipped vanilla distribution taper into the world floor.") + private int minHeight = 1; + + @Required + @MinNumber(-8192) + @MaxNumber(8192) + @Desc("The inclusive maximum origin height in engine-local Y, where 0 is the bottom of the dimension.") + private int maxHeight = 75; + + @Desc("How origin heights are sampled. CLIPPED_UNIFORM preserves Iris behavior by clipping the band to terrain; UNIFORM and TRIANGLE sample the authored band first and discard cells outside terrain or build height.") + private DepositHeightDistribution heightDistribution = DepositHeightDistribution.CLIPPED_UNIFORM; + + @Desc("TERRAIN places below the generated surface. ABOVE_TERRAIN places only in existing solid hosts above it. FULL_HEIGHT permits existing solid hosts anywhere in the dimension.") + private DepositPlacementScope placementScope = DepositPlacementScope.TERRAIN; + + @MinNumber(0) + @MaxNumber(256) + @Desc("Solid blocks kept between a deposit and the terrain surface. Vanilla-like deposits use 0; the Iris default remains 7.") + private int surfaceClearance = 7; + + @Required + @MinNumber(0) + @MaxNumber(8192) + @Desc("The minimum Iris block count or vanilla configured vein size, selected according to shape.") + private int minSize = 0; + + @Required + @MinNumber(0) + @MaxNumber(8192) + @Desc("The maximum Iris block count or vanilla configured vein size, selected according to shape.") + private int maxSize = 128; + + @Desc("IRIS places a fixed-count cube clump. VANILLA_ELLIPSOID uses Minecraft's chained ellipsoid geometry. VANILLA_SCATTERED uses Minecraft's sparse candidate offsets.") + private DepositShape shape = DepositShape.IRIS; + + @Required + @MinNumber(0) + @MaxNumber(2048) + @Desc("The maximum amount of clumps per chunk") + private int maxPerChunk = 3; + + @Required + @MinNumber(0) + @MaxNumber(2048) + @Desc("The minimum amount of clumps per chunk") + private int minPerChunk = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance of the deposit spawning in a chunk") + private double spawnChance = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance of each individual clump spawning in a chunk") + private double perClumpSpawnChance = 1; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Chance to discard a candidate ore block when it touches air. This matches vanilla ore exposure reduction.") + private double discardChanceOnAirExposure = 0; + + @Required + @Desc("The palette of blocks to be used in this deposit generator. Each entry is picked uniformly; the per-entry weight field is ignored here.") + private List palette = List.of(); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Ore varience is how many different objects clumps iris will create") + private int varience = 3; + + @Desc("Optional block ids this deposit may replace. An empty list retains Iris's any-solid behavior.") + private List replaceableBlocks = List.of(); + + @Desc("Chooses whether includedBiomes and excludedBiomes inspect the surface biome or the cave biome at the deposit origin.") + private DepositBiomeScope biomeScope = DepositBiomeScope.CAVE; + + @Desc("Optional Iris biome keys or vanilla derivative ids allowed for this deposit.") + private List includedBiomes = List.of(); + + @Desc("Optional Iris biome keys or vanilla derivative ids denied for this deposit.") + private List excludedBiomes = List.of(); + + @Desc("If set to true, this deposit will replace bedrock") + private boolean replaceBedrock = false; + + /** A generator with every option at its default, as packs get it from {@code {}}. */ + public DepositGenerator() { + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public DepositHeightDistribution heightDistribution() { + return heightDistribution == null ? DepositHeightDistribution.CLIPPED_UNIFORM : heightDistribution; + } + + public DepositPlacementScope placementScope() { + return placementScope == null ? DepositPlacementScope.TERRAIN : placementScope; + } + + public int surfaceClearance() { + return surfaceClearance; + } + + public int minSize() { + return minSize; + } + + public int maxSize() { + return maxSize; + } + + public DepositShape shape() { + return shape == null ? DepositShape.IRIS : shape; + } + + public int maxPerChunk() { + return maxPerChunk; + } + + public int minPerChunk() { + return minPerChunk; + } + + public double spawnChance() { + return spawnChance; + } + + public double perClumpSpawnChance() { + return perClumpSpawnChance; + } + + public double discardChanceOnAirExposure() { + return discardChanceOnAirExposure; + } + + public List palette() { + return listOrEmpty(palette); + } + + public int varience() { + return varience; + } + + public List replaceableBlocks() { + return listOrEmpty(replaceableBlocks); + } + + public DepositBiomeScope biomeScope() { + return biomeScope == null ? DepositBiomeScope.CAVE : biomeScope; + } + + public List includedBiomes() { + return listOrEmpty(includedBiomes); + } + + public List excludedBiomes() { + return listOrEmpty(excludedBiomes); + } + + public boolean replaceBedrock() { + return replaceBedrock; + } + + /** The edge of the cube an {@link DepositShape#IRIS} clump of {@link #maxSize()} blocks fills, at most 11. */ + public int maxDimension() { + return Math.min(MAX_CLUMP_DIMENSION, (int) Math.ceil(Math.cbrt(maxSize))); + } + + /** Whether the biome filters need the cave biome at the deposit's origin. */ + public boolean usesCaveBiomeFilter() { + return biomeScope() == DepositBiomeScope.CAVE && (!includedBiomes().isEmpty() || !excludedBiomes().isEmpty()); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java new file mode 100644 index 000000000..74c41f61f --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.deposit; + +import com.volmit.config.Desc; + +@Desc("Controls how a deposit chooses its origin height within the configured vertical band.") +public enum DepositHeightDistribution { + @Desc("Samples uniformly after clipping the configured band to the terrain and build-height bounds.") + CLIPPED_UNIFORM, + @Desc("Samples uniformly from the configured band, then rejects origins outside the terrain or build-height bounds.") + UNIFORM, + @Desc("Samples toward the middle of the configured band with a triangular distribution, then rejects invalid origins.") + TRIANGLE +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java new file mode 100644 index 000000000..5a9541033 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.deposit; + +import com.volmit.config.Desc; + +@Desc("Controls which vertical part of the world may contain a deposit origin.") +public enum DepositPlacementScope { + @Desc("Places in solid terrain below the generated surface while preserving the configured surface clearance.") + TERRAIN, + @Desc("Places only in existing solid hosts above the generated terrain surface.") + ABOVE_TERRAIN, + @Desc("Places in existing solid hosts anywhere within the dimension build height.") + FULL_HEIGHT +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java index c9901093e..a6017142b 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java @@ -18,7 +18,6 @@ package art.arcane.iris.builtin.deposit; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.config.Desc; @@ -28,22 +27,23 @@ import java.util.List; /** * The deposits one dimension, region or biome declares, written as {@code "deposits": [...]}. Levels stack: - * a chunk gets the deposits of its dimension, its centre column's region and that column's biome. + * a chunk gets the deposits of its dimension, its centre column's region and that column's biome. IrisApi types only, + * like {@link DepositGenerator}. */ @Desc("Ores and other deposits generated in every chunk where this applies") @Feature(id = "iris:deposit", name = "Deposits", alias = "deposits", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) public final class DepositSettings implements IrisFeature { @Desc("Define deposit generators that this applies to chunks") - private List generators = List.of(); + private List generators = List.of(); public DepositSettings() { } - public DepositSettings(List generators) { + public DepositSettings(List generators) { this.generators = List.copyOf(generators); } - public List generators() { + public List generators() { return generators; } } diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java new file mode 100644 index 000000000..72c3e3022 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.deposit; + +import com.volmit.config.Desc; + +@Desc("Selects the geometry used to build each deposit clump.") +public enum DepositShape { + @Desc("Builds the traditional Iris fixed-block-count cube clump.") + IRIS, + @Desc("Builds a chain of overlapping ellipsoids matching Minecraft's ordinary ore-vein geometry.") + VANILLA_ELLIPSOID, + @Desc("Builds sparse candidate offsets matching Minecraft's scattered-ore geometry.") + VANILLA_SCATTERED +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index e4116ad37..f2889714b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -19,9 +19,9 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositSettings; import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.FeatureSettings; @@ -59,7 +59,7 @@ public final class DepositModule implements IrisModule { private static void place(ChunkStageContext context, List> inChunk) { IrisChunk chunk = IrisChunk.current(); - List generators = generatorsAtCentre(context.settings(), context.originX(), context.originZ()); + List generators = generatorsAtCentre(context.settings(), context.originX(), context.originZ()); if (generators.isEmpty() || chunk.bypassesMantleStages()) { return; } @@ -68,7 +68,7 @@ public final class DepositModule implements IrisModule { } /** Every level's generators at the centre column of the chunk whose first block is {@code originX}, {@code originZ}, in level order. */ - static List generatorsAtCentre(FeatureSettings settings, int originX, int originZ) { + static List generatorsAtCentre(FeatureSettings settings, int originX, int originZ) { return settings.at(DepositSettings.class, originX + CHUNK_CENTRE, originZ + CHUNK_CENTRE).stream() .flatMap(entry -> entry.value().generators().stream()) .toList(); diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 21e944c01..ff3844442 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.deposit.DepositGenerator; +import art.arcane.iris.builtin.deposit.DepositHeightDistribution; +import art.arcane.iris.builtin.deposit.DepositPlacementScope; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedComponent; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositGenerator; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositHeightDistribution; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositPlacementScope; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; @@ -42,13 +42,17 @@ import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * Places deposit clumps into one chunk for {@link DepositModule}: one per engine runtime, holding the deposit - * stream's random. Each generator gets its own random, derived from the chunk and its position in the list. + * stream's random and each generator made ready for this engine ({@link ResolvedDeposit}: resolved blocks and clump + * shapes). Each generator gets its own random, derived from the chunk and its position in the list. */ public class DepositPlacer extends EngineAssignedComponent { private final RNG rng; + private final Map resolved = new ConcurrentHashMap<>(); public DepositPlacer(Engine engine) { super(engine, "Deposit"); @@ -56,14 +60,14 @@ public class DepositPlacer extends EngineAssignedComponent { } /** Runs {@code generators}, in order, on the chunk at chunk coordinates {@code x}, {@code z}. */ - public void generate(List generators, Hunk terrain, int x, int z, boolean multicore, + public void generate(List generators, Hunk terrain, int x, int z, boolean multicore, ChunkContext context) { PrecisionStopwatch p = PrecisionStopwatch.start(); generateDeposits(generators, terrain, x, z, multicore, context); getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); } - private void generateDeposits(List generators, Hunk terrain, int x, int z, + private void generateDeposits(List generators, Hunk terrain, int x, int z, boolean multicore, ChunkContext context) { BurstExecutor burst = burst().burst(multicore); @@ -71,7 +75,7 @@ public class DepositPlacer extends EngineAssignedComponent { long mask = 0; MantleChunk chunk = getEngine().getMantle().getMantle().getChunk(x, z).use(); try { - for (IrisDepositGenerator k : generators) { + for (DepositGenerator k : generators) { long finalSeed = seed * ++mask; burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); } @@ -86,20 +90,21 @@ public class DepositPlacer extends EngineAssignedComponent { } } - public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, ChunkContext context) { + public void generate(DepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, ChunkContext context) { generate(k, chunk, data, rng, cx, cz, safe, null, context); } - public void generate(IrisDepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) { + public void generate(DepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) { IrisDimensionCarvingResolver.State carvingState = new IrisDimensionCarvingResolver.State(); - if (k.getSpawnChance() < rng.d()) + ResolvedDeposit deposit = resolved(k); + if (k.spawnChance() < rng.d()) return; - for (int l = 0; l < rng.i(k.getMinPerChunk(), k.getMaxPerChunk() + 1); l++) { - if (k.getPerClumpSpawnChance() < rng.d()) + for (int l = 0; l < rng.i(k.minPerChunk(), k.maxPerChunk() + 1); l++) { + if (k.perClumpSpawnChance() < rng.d()) continue; - IrisObject clump = k.getClump(getEngine(), rng, getData()); + IrisObject clump = deposit.clump(rng); int dim = clump.getW(); int min = dim / 2; @@ -113,8 +118,8 @@ public class DepositPlacer extends EngineAssignedComponent { int x = rng.i(min, max + 1); int z = rng.i(min, max + 1); int terrainSurface = getDepositTerrainSurface(cx, cz, x, z, he, context); - int height = k.getPlacementScope() == IrisDepositPlacementScope.TERRAIN - ? depositSurfaceLimit(terrainSurface, k.getSurfaceClearance()) + int height = k.placementScope() == DepositPlacementScope.TERRAIN + ? depositSurfaceLimit(terrainSurface, k.surfaceClearance()) : getEngine().getHeight() - 1; if (height < 0) { @@ -122,24 +127,24 @@ public class DepositPlacer extends EngineAssignedComponent { } int y = sampleHeight( - k.getHeightDistribution(), rng, k.getMinHeight(), k.getMaxHeight(), + k.heightDistribution(), rng, k.minHeight(), k.maxHeight(), Math.min(height, getEngine().getHeight() - 1)); if (y == Integer.MIN_VALUE) { continue; } - boolean clippedHeight = k.getHeightDistribution() == IrisDepositHeightDistribution.CLIPPED_UNIFORM; + boolean clippedHeight = k.heightDistribution() == DepositHeightDistribution.CLIPPED_UNIFORM; if (clippedHeight && y > height - 2) continue; int biomeY = Math.max(0, Math.min(getEngine().getHeight() - 1, y)); - boolean oreDeposit = k.isOre(getData()); + boolean oreDeposit = deposit.isOre(); IrisBiome surfaceBiome = context.getBiome().get(x, z); IrisBiome depositBiome = oreDeposit || k.usesCaveBiomeFilter() ? getEngine().getCaveBiome( (cx << 4) + x, biomeY, (cz << 4) + z, carvingState) : null; - if (!k.matchesBiome(surfaceBiome, depositBiome)) { + if (!deposit.matchesBiome(surfaceBiome, depositBiome)) { continue; } @@ -153,7 +158,7 @@ public class DepositPlacer extends EngineAssignedComponent { double sizeMultiplier = depositBiome.getOreDepositSizeMultiplier(); if (sizeMultiplier != 1D) { - IrisObject scaledClump = k.getClump(getEngine(), rng, getData(), sizeMultiplier); + IrisObject scaledClump = deposit.clump(rng, sizeMultiplier); int scaledDimension = scaledClump.getW(); x = clampDepositCenter(x, scaledDimension, 16); if (clippedHeight) { @@ -177,7 +182,7 @@ public class DepositPlacer extends EngineAssignedComponent { } int columnSurface = getDepositTerrainSurface(cx, cz, nx, nz, he, context); if (!placementSurfaceAllows( - k.getPlacementScope(), ny, columnSurface, k.getSurfaceClearance())) { + k.placementScope(), ny, columnSurface, k.surfaceClearance())) { continue; } @@ -185,14 +190,14 @@ public class DepositPlacer extends EngineAssignedComponent { if (!canReplaceDepositTarget(current)) { continue; } - if (!k.canReplace(current)) { + if (!deposit.canReplace(current)) { continue; } - if (!k.isReplaceBedrock() && IrisProceduralBlocks.materialKey(current).equals("minecraft:bedrock")) { + if (!k.replaceBedrock() && IrisProceduralBlocks.materialKey(current).equals("minecraft:bedrock")) { continue; } if (shouldDiscardExposed( - k.getDiscardChanceOnAirExposure(), rng.d(), isAdjacentToAir(data, nx, ny, nz))) { + k.discardChanceOnAirExposure(), rng.d(), isAdjacentToAir(data, nx, ny, nz))) { continue; } @@ -209,6 +214,10 @@ public class DepositPlacer extends EngineAssignedComponent { } } + private ResolvedDeposit resolved(DepositGenerator generator) { + return resolved.computeIfAbsent(generator, ignored -> ResolvedDeposit.of(generator, getEngine())); + } + private int getDepositTerrainSurface( int cx, int cz, int localX, int localZ, HeightMap heightMap, ChunkContext context) { @@ -226,7 +235,7 @@ public class DepositPlacer extends EngineAssignedComponent { } static boolean placementSurfaceAllows( - IrisDepositPlacementScope scope, int candidateY, int surfaceY, int surfaceClearance) { + DepositPlacementScope scope, int candidateY, int surfaceY, int surfaceClearance) { int clearance = Math.max(0, surfaceClearance); return switch (scope) { case ABOVE_TERRAIN -> candidateY > surfaceY + clearance; @@ -244,12 +253,12 @@ public class DepositPlacer extends EngineAssignedComponent { } static int sampleHeight( - IrisDepositHeightDistribution distribution, RNG rng, + DepositHeightDistribution distribution, RNG rng, int configuredMinimum, int configuredMaximum, int clippedMaximum) { - int minimum = distribution == IrisDepositHeightDistribution.CLIPPED_UNIFORM + int minimum = distribution == DepositHeightDistribution.CLIPPED_UNIFORM ? Math.max(0, configuredMinimum) : configuredMinimum; - int maximum = distribution == IrisDepositHeightDistribution.CLIPPED_UNIFORM + int maximum = distribution == DepositHeightDistribution.CLIPPED_UNIFORM ? Math.min(clippedMaximum, configuredMaximum) : configuredMaximum; if (minimum > maximum) { @@ -258,7 +267,7 @@ public class DepositPlacer extends EngineAssignedComponent { if (minimum == maximum) { return minimum; } - if (distribution != IrisDepositHeightDistribution.TRIANGLE) { + if (distribution != DepositHeightDistribution.TRIANGLE) { return minimum + rng.nextInt(maximum - minimum + 1); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java new file mode 100644 index 000000000..1aaf2d4e5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java @@ -0,0 +1,408 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.deposit.DepositBiomeScope; +import art.arcane.iris.builtin.deposit.DepositGenerator; +import art.arcane.iris.builtin.deposit.DepositShape; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.collection.KSet; +import art.arcane.volmlib.util.math.BlockPosition; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * One {@link DepositGenerator} made ready for one engine: its palette resolved to the platform's blocks, whether it is + * an ore deposit, the blocks it may replace, and the clump shapes it places, built once per size. What the settings + * describe stays in the settings; everything that needs the platform, the pack or the world seed is here. + */ +final class ResolvedDeposit { + private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; + private static final long FNV_PRIME = 0x100000001b3L; + private static final int MAX_CLUMP_DIMENSION = 11; + private static final int MAX_DEPOSIT_SIZE = 8192; + private static final int VARIANT_SEED_STEP = 2349; + private static final int VARIANT_SEED_OFFSET = 3598; + private static final int MAX_SCATTER_MAGNITUDE = 7; + private static final String MINECRAFT_NAMESPACE = "minecraft:"; + + private final DepositGenerator generator; + private final long depositSeed; + private final List palette; + private final boolean ore; + private final Set replaceableMaterials; + private final Map> clumps = new ConcurrentHashMap<>(); + + /** @param palette the generator's palette as the platform's blocks, in order */ + ResolvedDeposit(DepositGenerator generator, long depositSeed, List palette) { + this.generator = generator; + this.depositSeed = depositSeed; + this.palette = List.copyOf(palette); + this.ore = palette.stream().anyMatch(PlatformBlockState::isOre); + this.replaceableMaterials = replaceableMaterials(generator.replaceableBlocks()); + } + + /** {@code generator} ready for {@code engine}: its blocks resolved through the pack, clumps seeded from the world's deposit seed. */ + static ResolvedDeposit of(DepositGenerator generator, Engine engine) { + BlockRegistry blocks = engine.getData().getPackResources().blocks(); + List palette = generator.palette().stream() + .map(spec -> B.getState(blocks.resolve(spec).key())) + .toList(); + return new ResolvedDeposit(generator, engine.getSeedManager().getDeposit(), palette); + } + + DepositGenerator generator() { + return generator; + } + + /** Whether any block of the palette is an ore: ore deposits follow the cave biome's ore tuning. */ + boolean isOre() { + return ore; + } + + /** Whether the deposit may replace {@code state}: any block when it names none, otherwise only the named ones. */ + boolean canReplace(PlatformBlockState state) { + return generator.replaceableBlocks().isEmpty() || replaceableMaterials.contains(IrisProceduralBlocks.materialKey(state)); + } + + /** Whether the biome the generator's scope picks passes its include and exclude filters. */ + boolean matchesBiome(IrisBiome surfaceBiome, IrisBiome caveBiome) { + IrisBiome selected = generator.biomeScope() == DepositBiomeScope.SURFACE ? surfaceBiome : caveBiome; + if (!generator.includedBiomes().isEmpty() && !matchesAnyBiome(selected, generator.includedBiomes())) { + return false; + } + return generator.excludedBiomes().isEmpty() || !matchesAnyBiome(selected, generator.excludedBiomes()); + } + + /** One clump to place, picked with {@code rng}. */ + IrisObject clump(RNG rng) { + return clump(rng, generator.minSize(), generator.maxSize(), 0L); + } + + /** One clump to place with every size scaled by {@code sizeMultiplier}, as a biome's ore size tuning asks. */ + IrisObject clump(RNG rng, double sizeMultiplier) { + if (sizeMultiplier == 1D) { + return clump(rng); + } + int minSize = scaledDepositSize(generator.minSize(), sizeMultiplier); + int maxSize = scaledDepositSize(generator.maxSize(), sizeMultiplier); + long sizeSeed = ((long) minSize << 32) ^ (maxSize & 0xffffffffL); + return clump(rng, minSize, maxSize, sizeSeed); + } + + private IrisObject clump(RNG rng, int minSize, int maxSize, long sizeSeed) { + if (generator.shape() != DepositShape.IRIS) { + return configuredClump(rng, minSize, maxSize); + } + List variants = clumps.computeIfAbsent(new ClumpSizes(minSize, maxSize), sizes -> { + RNG variantRng = new RNG(depositSeed + stableClumpSalt() + sizeSeed); + List built = new ArrayList<>(); + for (int i = 0; i < generator.varience(); i++) { + built.add(irisClump(variantRng.nextParallelRNG(VARIANT_SEED_STEP * i + VARIANT_SEED_OFFSET), sizes.minSize(), sizes.maxSize())); + } + return List.copyOf(built); + }); + return variants.get(rng.i(0, variants.size())); + } + + static int scaledDepositSize(int size, double multiplier) { + return Math.max(0, Math.min(MAX_DEPOSIT_SIZE, (int) Math.round(size * multiplier))); + } + + /** A hash of everything the generator describes and its resolved palette, so equal generators share clump shapes. */ + long stableClumpSalt() { + long hash = FNV_OFFSET_BASIS; + hash = mix(hash, generator.minHeight()); + hash = mix(hash, generator.maxHeight()); + hash = mixEnum(hash, generator.heightDistribution()); + hash = mixEnum(hash, generator.placementScope()); + hash = mix(hash, generator.surfaceClearance()); + hash = mix(hash, generator.minSize()); + hash = mix(hash, generator.maxSize()); + hash = mixEnum(hash, generator.shape()); + hash = mix(hash, generator.maxPerChunk()); + hash = mix(hash, generator.minPerChunk()); + hash = mix(hash, Double.doubleToLongBits(generator.spawnChance())); + hash = mix(hash, Double.doubleToLongBits(generator.perClumpSpawnChance())); + hash = mix(hash, Double.doubleToLongBits(generator.discardChanceOnAirExposure())); + hash = mix(hash, palette.size()); + for (PlatformBlockState block : palette) { + hash = mixString(hash, block == null ? null : block.key()); + } + hash = mix(hash, generator.varience()); + hash = mixStrings(hash, generator.replaceableBlocks()); + hash = mixEnum(hash, generator.biomeScope()); + hash = mixStrings(hash, generator.includedBiomes()); + hash = mixStrings(hash, generator.excludedBiomes()); + return mix(hash, generator.replaceBedrock() ? 1L : 0L); + } + + private static long mix(long hash, long value) { + return (hash ^ value) * FNV_PRIME; + } + + private static long mixEnum(long hash, Enum value) { + return mixString(hash, value == null ? null : value.name()); + } + + private static long mixString(long hash, String value) { + if (value == null) { + return mix(hash, -1L); + } + long mixed = mix(hash, value.length()); + for (int i = 0; i < value.length(); i++) { + mixed = mix(mixed, value.charAt(i)); + } + return mixed; + } + + private static long mixStrings(long hash, List values) { + long mixed = mix(hash, values.size()); + for (String value : values) { + mixed = mixString(mixed, value); + } + return mixed; + } + + private IrisObject configuredClump(RNG rng, int minSize, int maxSize) { + int size = rng.i(minSize, maxSize + 1); + return switch (generator.shape()) { + case VANILLA_ELLIPSOID -> vanillaEllipsoid(rng, size); + case VANILLA_SCATTERED -> vanillaScattered(rng, size); + case IRIS -> irisClump(rng, minSize, maxSize); + }; + } + + /** Minecraft's ordinary ore vein: a chain of overlapping ellipsoids whose reach grows with {@code size}. */ + IrisObject vanillaEllipsoid(RNG rng, int size) { + if (size <= 0) { + return new IrisObject(1, 1, 1); + } + + float angle = rng.nextFloat() * (float) Math.PI; + float reach = size / 8F; + double startX = Math.sin(angle) * reach; + double endX = -Math.sin(angle) * reach; + double startZ = Math.cos(angle) * reach; + double endZ = -Math.cos(angle) * reach; + double startY = rng.nextInt(3) - 2; + double endY = rng.nextInt(3) - 2; + double[] nodes = new double[size * 4]; + + for (int i = 0; i < size; i++) { + float progress = (float) i / size; + double radiusNoise = rng.nextDouble() * size / 16D; + nodes[i * 4] = startX + (endX - startX) * progress; + nodes[i * 4 + 1] = startY + (endY - startY) * progress; + nodes[i * 4 + 2] = startZ + (endZ - startZ) * progress; + nodes[i * 4 + 3] = ((Math.sin(Math.PI * progress) + 1D) * radiusNoise + 1D) / 2D; + } + + for (int i = 0; i < size - 1; i++) { + if (nodes[i * 4 + 3] <= 0D) { + continue; + } + for (int j = i + 1; j < size; j++) { + if (nodes[j * 4 + 3] <= 0D) { + continue; + } + double dx = nodes[i * 4] - nodes[j * 4]; + double dy = nodes[i * 4 + 1] - nodes[j * 4 + 1]; + double dz = nodes[i * 4 + 2] - nodes[j * 4 + 2]; + double dr = nodes[i * 4 + 3] - nodes[j * 4 + 3]; + if (dr * dr <= dx * dx + dy * dy + dz * dz) { + continue; + } + if (dr > 0D) { + nodes[j * 4 + 3] = -1D; + } else { + nodes[i * 4 + 3] = -1D; + } + } + } + + KSet cells = new KSet<>(); + for (int i = 0; i < size; i++) { + double radius = nodes[i * 4 + 3]; + if (radius < 0D) { + continue; + } + double centerX = nodes[i * 4]; + double centerY = nodes[i * 4 + 1]; + double centerZ = nodes[i * 4 + 2]; + int minX = (int) Math.floor(centerX - radius); + int maxX = Math.max((int) Math.floor(centerX + radius), minX); + int minY = (int) Math.floor(centerY - radius); + int maxY = Math.max((int) Math.floor(centerY + radius), minY); + int minZ = (int) Math.floor(centerZ - radius); + int maxZ = Math.max((int) Math.floor(centerZ + radius), minZ); + + for (int x = minX; x <= maxX; x++) { + double nx = (x + 0.5D - centerX) / radius; + if (nx * nx >= 1D) { + continue; + } + for (int y = minY; y <= maxY; y++) { + double ny = (y + 0.5D - centerY) / radius; + if (nx * nx + ny * ny >= 1D) { + continue; + } + for (int z = minZ; z <= maxZ; z++) { + double nz = (z + 0.5D - centerZ) / radius; + if (nx * nx + ny * ny + nz * nz < 1D) { + cells.add(new BlockPosition(x, y, z)); + } + } + } + } + } + + return objectFromCells(cells, rng); + } + + /** Minecraft's scattered ore: up to {@code size} candidate offsets, the later ones further from the centre. */ + IrisObject vanillaScattered(RNG rng, int size) { + KSet cells = new KSet<>(); + int candidates = rng.nextInt(Math.max(0, size) + 1); + for (int i = 0; i < candidates; i++) { + int magnitude = Math.min(i, MAX_SCATTER_MAGNITUDE); + cells.add(new BlockPosition( + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), + Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude))); + } + return objectFromCells(cells, rng); + } + + private IrisObject objectFromCells(KSet cells, RNG rng) { + if (cells.isEmpty()) { + return new IrisObject(1, 1, 1); + } + + 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 (BlockPosition cell : cells) { + minX = Math.min(minX, cell.getX()); + minY = Math.min(minY, cell.getY()); + minZ = Math.min(minZ, cell.getZ()); + maxX = Math.max(maxX, cell.getX()); + maxY = Math.max(maxY, cell.getY()); + maxZ = Math.max(maxZ, cell.getZ()); + } + + int extentX = Math.max(Math.abs(minX), Math.abs(maxX)); + int extentY = Math.max(Math.abs(minY), Math.abs(maxY)); + int extentZ = Math.max(Math.abs(minZ), Math.abs(maxZ)); + IrisObject object = new IrisObject(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1); + for (BlockPosition cell : cells) { + object.setUnsigned(cell.getX() + extentX, cell.getY() + extentY, cell.getZ() + extentZ, nextBlock(rng)); + } + return object; + } + + /** The traditional Iris clump: a cube just large enough for the block count, filled at random cells. */ + private IrisObject irisClump(RNG rng, int minSize, int maxSize) { + int remaining = rng.i(minSize, maxSize + 1); + if (remaining == 1) { + IrisObject single = new IrisObject(1, 1, 1); + Vector3i center = single.getCenter(); + single.getBlocks().put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), nextBlock(rng)); + return single; + } + + int dimension = Math.min(MAX_CLUMP_DIMENSION, (int) Math.ceil(Math.cbrt(remaining))); + IrisObject clump = new IrisObject(dimension, dimension, dimension); + if (remaining >= dimension * dimension * dimension) { + fillCube(clump, dimension, rng); + return clump; + } + + KSet filled = new KSet<>(); + while (remaining > 0) { + BlockPosition cell = new BlockPosition(rng.i(0, dimension), rng.i(0, dimension), rng.i(0, dimension)); + if (!filled.add(cell)) { + continue; + } + remaining--; + clump.setUnsigned(cell.getX(), cell.getY(), cell.getZ(), nextBlock(rng)); + } + return clump; + } + + private void fillCube(IrisObject clump, int dimension, RNG rng) { + for (int z = 0; z < dimension; z++) { + for (int y = 0; y < dimension; y++) { + for (int x = 0; x < dimension; x++) { + clump.setUnsigned(x, y, z, nextBlock(rng)); + } + } + } + } + + private PlatformBlockState nextBlock(RNG rng) { + return palette.get(rng.i(0, palette.size())); + } + + private static Set replaceableMaterials(List keys) { + Set materials = new KSet<>(); + for (String key : keys) { + PlatformBlockState state = B.getStateOrNull(key, false); + if (state != null) { + materials.add(IrisProceduralBlocks.materialKey(state)); + } + } + return materials; + } + + private static boolean matchesAnyBiome(IrisBiome biome, List configuredBiomes) { + if (biome == null) { + return false; + } + for (String configured : configuredBiomes) { + String namespaced = configured.contains(":") ? configured : MINECRAFT_NAMESPACE + configured; + if (configured.equals(biome.getLoadKey()) + || namespaced.equals(biome.getDerivativeKey()) + || namespaced.equals(biome.getVanillaDerivativeKey())) { + return true; + } + } + return false; + } + + /** The sizes one set of clump variants is built for: the generator's own, or scaled by a biome's ore tuning. */ + record ClumpSizes(int minSize, int maxSize) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java deleted file mode 100644 index 1f9c6ace1..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositBiomeScope.java +++ /dev/null @@ -1,11 +0,0 @@ -package art.arcane.iris.engine.object.terrain.deposit; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Selects which biome identity is checked by a deposit's include and exclude filters.") -public enum IrisDepositBiomeScope { - @Desc("Checks the surface biome selected for the deposit column.") - SURFACE, - @Desc("Checks the cave biome selected at the deposit origin.") - CAVE -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java deleted file mode 100644 index c900f3b70..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositGenerator.java +++ /dev/null @@ -1,525 +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.deposit; - -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -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.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.Vector3i; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KSet; -import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.RNG; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("deposit") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Creates ore & other block deposits underground") -@Data -public class IrisDepositGenerator { - private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; - private static final long FNV_PRIME = 0x100000001b3L; - - private final transient ConcurrentMap> objects = new ConcurrentHashMap<>(); - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache ore = new AtomicCache<>(); - private final transient AtomicCache> replaceableBlockData = new AtomicCache<>(); - private final transient ConcurrentMap> scaledObjects = new ConcurrentHashMap<>(); - @Required - @MinNumber(-8192) - @MaxNumber(8192) - @Desc("The inclusive minimum origin height in engine-local Y, where 0 is the bottom of the dimension. Negative values let an unclipped vanilla distribution taper into the world floor.") - private int minHeight = 1; - @Required - @MinNumber(-8192) - @MaxNumber(8192) - @Desc("The inclusive maximum origin height in engine-local Y, where 0 is the bottom of the dimension.") - private int maxHeight = 75; - @Desc("How origin heights are sampled. CLIPPED_UNIFORM preserves Iris behavior by clipping the band to terrain; UNIFORM and TRIANGLE sample the authored band first and discard cells outside terrain or build height.") - private IrisDepositHeightDistribution heightDistribution = IrisDepositHeightDistribution.CLIPPED_UNIFORM; - @Desc("TERRAIN places below the generated surface. ABOVE_TERRAIN places only in existing solid hosts above it. FULL_HEIGHT permits existing solid hosts anywhere in the dimension.") - private IrisDepositPlacementScope placementScope = IrisDepositPlacementScope.TERRAIN; - @MinNumber(0) - @MaxNumber(256) - @Desc("Solid blocks kept between a deposit and the terrain surface. Vanilla-like deposits use 0; the Iris default remains 7.") - private int surfaceClearance = 7; - @Required - @MinNumber(0) - @MaxNumber(8192) - @Desc("The minimum Iris block count or vanilla configured vein size, selected according to shape.") - private int minSize = 0; - @Required - @MinNumber(0) - @MaxNumber(8192) - @Desc("The maximum Iris block count or vanilla configured vein size, selected according to shape.") - private int maxSize = 128; - @Desc("IRIS places a fixed-count cube clump. VANILLA_ELLIPSOID uses Minecraft's chained ellipsoid geometry. VANILLA_SCATTERED uses Minecraft's sparse candidate offsets.") - private IrisDepositShape shape = IrisDepositShape.IRIS; - @Required - @MinNumber(0) - @MaxNumber(2048) - @Desc("The maximum amount of clumps per chunk") - private int maxPerChunk = 3; - @Required - @MinNumber(0) - @MaxNumber(2048) - @Desc("The minimum amount of clumps per chunk") - private int minPerChunk = 0; - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance of the deposit spawning in a chunk") - private double spawnChance = 1; - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance of each individual clump spawning in a chunk") - private double perClumpSpawnChance = 1; - @MinNumber(0) - @MaxNumber(1) - @Desc("Chance to discard a candidate ore block when it touches air. This matches vanilla ore exposure reduction.") - private double discardChanceOnAirExposure = 0; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to be used in this deposit generator. Each entry is picked uniformly; the per-entry weight field is ignored here.") - private KList palette = new KList<>(); - @MinNumber(1) - @MaxNumber(64) - @Desc("Ore varience is how many different objects clumps iris will create") - private int varience = 3; - @ArrayType(min = 1, type = String.class) - @Desc("Optional block ids this deposit may replace. An empty list retains Iris's any-solid behavior.") - private KList replaceableBlocks = new KList<>(); - @Desc("Chooses whether includedBiomes and excludedBiomes inspect the surface biome or the cave biome at the deposit origin.") - private IrisDepositBiomeScope biomeScope = IrisDepositBiomeScope.CAVE; - @ArrayType(min = 1, type = String.class) - @Desc("Optional Iris biome keys or vanilla derivative ids allowed for this deposit.") - private KList includedBiomes = new KList<>(); - @ArrayType(min = 1, type = String.class) - @Desc("Optional Iris biome keys or vanilla derivative ids denied for this deposit.") - private KList excludedBiomes = new KList<>(); - @Desc("If set to true, this deposit will replace bedrock") - private boolean replaceBedrock = false; - - public IrisObject getClump(Engine engine, RNG rng, IrisData rdata) { - if (shape != IrisDepositShape.IRIS) { - return generateConfiguredClumpObject(rng, rdata, minSize, maxSize); - } - - ClumpCacheKey cacheKey = new ClumpCacheKey(engine.getSeedManager().getDeposit(), minSize, maxSize); - KList objects = this.objects.computeIfAbsent(cacheKey, key -> { - RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata)); - KList objectsf = new KList<>(); - - for (int i = 0; i < varience; i++) { - objectsf.add(generateClumpObject( - rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize())); - } - - return objectsf; - }); - return objects.get(rng.i(0, objects.size())); - } - - public IrisObject getClump(Engine engine, RNG rng, IrisData rdata, double sizeMultiplier) { - if (sizeMultiplier == 1D) { - return getClump(engine, rng, rdata); - } - - int scaledMinSize = scaledDepositSize(minSize, sizeMultiplier); - int scaledMaxSize = scaledDepositSize(maxSize, sizeMultiplier); - if (shape != IrisDepositShape.IRIS) { - return generateConfiguredClumpObject(rng, rdata, scaledMinSize, scaledMaxSize); - } - - ClumpCacheKey cacheKey = new ClumpCacheKey( - engine.getSeedManager().getDeposit(), scaledMinSize, scaledMaxSize); - KList objects = scaledObjects.computeIfAbsent(cacheKey, key -> { - long sizeSeed = ((long) key.minSize() << 32) ^ (key.maxSize() & 0xffffffffL); - RNG rngv = new RNG(key.depositSeed() + stableClumpSalt(rdata) + sizeSeed); - KList generated = new KList<>(); - - for (int i = 0; i < varience; i++) { - generated.add(generateClumpObject( - rngv.nextParallelRNG(2349 * i + 3598), rdata, key.minSize(), key.maxSize())); - } - - return generated; - }); - return objects.get(rng.i(0, objects.size())); - } - - public int getMaxDimension() { - return Math.min(11, (int) Math.ceil(Math.cbrt(maxSize))); - } - - static int scaledDepositSize(int size, double multiplier) { - return Math.max(0, Math.min(8192, (int) Math.round(size * multiplier))); - } - - long stableClumpSalt(IrisData rdata) { - long hash = FNV_OFFSET_BASIS; - hash = mix(hash, minHeight); - hash = mix(hash, maxHeight); - hash = mixEnum(hash, heightDistribution); - hash = mixEnum(hash, placementScope); - hash = mix(hash, surfaceClearance); - hash = mix(hash, minSize); - hash = mix(hash, maxSize); - hash = mixEnum(hash, shape); - hash = mix(hash, maxPerChunk); - hash = mix(hash, minPerChunk); - hash = mix(hash, Double.doubleToLongBits(spawnChance)); - hash = mix(hash, Double.doubleToLongBits(perClumpSpawnChance)); - hash = mix(hash, Double.doubleToLongBits(discardChanceOnAirExposure)); - KList resolvedPalette = getBlockData(rdata); - hash = mix(hash, resolvedPalette.size()); - for (PlatformBlockState block : resolvedPalette) { - hash = mixString(hash, block == null ? null : block.key()); - } - hash = mix(hash, varience); - hash = mixStrings(hash, replaceableBlocks); - hash = mixEnum(hash, biomeScope); - hash = mixStrings(hash, includedBiomes); - hash = mixStrings(hash, excludedBiomes); - return mix(hash, replaceBedrock ? 1L : 0L); - } - - private static long mix(long hash, long value) { - return (hash ^ value) * FNV_PRIME; - } - - private static long mixEnum(long hash, Enum value) { - return mixString(hash, value == null ? null : value.name()); - } - - private static long mixString(long hash, String value) { - if (value == null) { - return mix(hash, -1L); - } - long mixed = mix(hash, value.length()); - for (int i = 0; i < value.length(); i++) { - mixed = mix(mixed, value.charAt(i)); - } - return mixed; - } - - private static long mixStrings(long hash, KList values) { - if (values == null) { - return mix(hash, -1L); - } - long mixed = mix(hash, values.size()); - for (String value : values) { - mixed = mixString(mixed, value); - } - return mixed; - } - - private IrisObject generateConfiguredClumpObject(RNG rng, IrisData rdata, int clumpMinSize, int clumpMaxSize) { - int size = rng.i(clumpMinSize, clumpMaxSize + 1); - return switch (shape) { - case VANILLA_ELLIPSOID -> generateVanillaEllipsoid(rng, rdata, size); - case VANILLA_SCATTERED -> generateVanillaScattered(rng, rdata, size); - case IRIS -> generateClumpObject(rng, rdata, clumpMinSize, clumpMaxSize); - }; - } - - IrisObject generateVanillaEllipsoid(RNG rng, IrisData rdata, int size) { - if (size <= 0) { - return new IrisObject(1, 1, 1); - } - - float angle = rng.nextFloat() * (float) Math.PI; - float reach = size / 8F; - double startX = Math.sin(angle) * reach; - double endX = -Math.sin(angle) * reach; - double startZ = Math.cos(angle) * reach; - double endZ = -Math.cos(angle) * reach; - double startY = rng.nextInt(3) - 2; - double endY = rng.nextInt(3) - 2; - double[] nodes = new double[size * 4]; - - for (int i = 0; i < size; i++) { - float progress = (float) i / size; - double radiusNoise = rng.nextDouble() * size / 16D; - nodes[i * 4] = startX + (endX - startX) * progress; - nodes[i * 4 + 1] = startY + (endY - startY) * progress; - nodes[i * 4 + 2] = startZ + (endZ - startZ) * progress; - nodes[i * 4 + 3] = ((Math.sin(Math.PI * progress) + 1D) * radiusNoise + 1D) / 2D; - } - - for (int i = 0; i < size - 1; i++) { - if (nodes[i * 4 + 3] <= 0D) { - continue; - } - for (int j = i + 1; j < size; j++) { - if (nodes[j * 4 + 3] <= 0D) { - continue; - } - double dx = nodes[i * 4] - nodes[j * 4]; - double dy = nodes[i * 4 + 1] - nodes[j * 4 + 1]; - double dz = nodes[i * 4 + 2] - nodes[j * 4 + 2]; - double dr = nodes[i * 4 + 3] - nodes[j * 4 + 3]; - if (dr * dr <= dx * dx + dy * dy + dz * dz) { - continue; - } - if (dr > 0D) { - nodes[j * 4 + 3] = -1D; - } else { - nodes[i * 4 + 3] = -1D; - } - } - } - - KSet cells = new KSet<>(); - for (int i = 0; i < size; i++) { - double radius = nodes[i * 4 + 3]; - if (radius < 0D) { - continue; - } - double centerX = nodes[i * 4]; - double centerY = nodes[i * 4 + 1]; - double centerZ = nodes[i * 4 + 2]; - int minX = (int) Math.floor(centerX - radius); - int maxX = Math.max((int) Math.floor(centerX + radius), minX); - int minY = (int) Math.floor(centerY - radius); - int maxY = Math.max((int) Math.floor(centerY + radius), minY); - int minZ = (int) Math.floor(centerZ - radius); - int maxZ = Math.max((int) Math.floor(centerZ + radius), minZ); - - for (int x = minX; x <= maxX; x++) { - double nx = (x + 0.5D - centerX) / radius; - if (nx * nx >= 1D) { - continue; - } - for (int y = minY; y <= maxY; y++) { - double ny = (y + 0.5D - centerY) / radius; - if (nx * nx + ny * ny >= 1D) { - continue; - } - for (int z = minZ; z <= maxZ; z++) { - double nz = (z + 0.5D - centerZ) / radius; - if (nx * nx + ny * ny + nz * nz < 1D) { - cells.add(new BlockPosition(x, y, z)); - } - } - } - } - } - - return objectFromCells(cells, rng, rdata); - } - - IrisObject generateVanillaScattered(RNG rng, IrisData rdata, int size) { - KSet cells = new KSet<>(); - int candidates = rng.nextInt(Math.max(0, size) + 1); - for (int i = 0; i < candidates; i++) { - int magnitude = Math.min(i, 7); - cells.add(new BlockPosition( - Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), - Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), - Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude))); - } - return objectFromCells(cells, rng, rdata); - } - - private IrisObject objectFromCells(KSet cells, RNG rng, IrisData rdata) { - if (cells.isEmpty()) { - return new IrisObject(1, 1, 1); - } - - 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 (BlockPosition cell : cells) { - minX = Math.min(minX, cell.getX()); - minY = Math.min(minY, cell.getY()); - minZ = Math.min(minZ, cell.getZ()); - maxX = Math.max(maxX, cell.getX()); - maxY = Math.max(maxY, cell.getY()); - maxZ = Math.max(maxZ, cell.getZ()); - } - - int extentX = Math.max(Math.abs(minX), Math.abs(maxX)); - int extentY = Math.max(Math.abs(minY), Math.abs(maxY)); - int extentZ = Math.max(Math.abs(minZ), Math.abs(maxZ)); - IrisObject object = new IrisObject(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1); - for (BlockPosition cell : cells) { - object.setUnsigned( - cell.getX() + extentX, - cell.getY() + extentY, - cell.getZ() + extentZ, - nextBlock(rng, rdata)); - } - return object; - } - - private IrisObject generateClumpObject(RNG rngv, IrisData rdata, int clumpMinSize, int clumpMaxSize) { - int s = rngv.i(clumpMinSize, clumpMaxSize + 1); - if (s == 1) { - IrisObject o = new IrisObject(1, 1, 1); - Vector3i center = o.getCenter(); - o.getBlocks().put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), nextBlock(rngv, rdata)); - return o; - } - - int dim = Math.min(11, (int) Math.ceil(Math.cbrt(s))); - IrisObject o = new IrisObject(dim, dim, dim); - - int volume = dim * dim * dim; - if (s >= volume) { - int x = 0, y = 0, z = 0; - - while (z < dim) { - o.setUnsigned(x++, y, z, nextBlock(rngv, rdata)); - - if (x == dim) { - x = 0; - y++; - } - - if (y == dim) { - y = 0; - z++; - } - } - return o; - } - - KSet set = new KSet<>(); - while (s > 0) { - BlockPosition ang = new BlockPosition( - rngv.i(0, dim), - rngv.i(0, dim), - rngv.i(0, dim) - ); - if (!set.add(ang)) continue; - - s--; - o.setUnsigned(ang.getX(), ang.getY(), ang.getZ(), nextBlock(rngv, rdata)); - } - - return o; - } - - private PlatformBlockState nextBlock(RNG rngv, IrisData rdata) { - return getBlockData(rdata).get(rngv.i(0, getBlockData(rdata).size())); - } - - public KList getBlockData(IrisData rdata) { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - - for (IrisBlockData ix : palette) { - PlatformBlockState bx = ix.getBlockData(rdata); - - if (bx != null) { - blockData.add(bx); - } - } - - return blockData; - }); - } - - public boolean isOre(IrisData rdata) { - return ore.aquire(() -> { - for (PlatformBlockState block : getBlockData(rdata)) { - if (block.isOre()) { - return true; - } - } - - return false; - }); - } - - public boolean canReplace(PlatformBlockState state) { - if (replaceableBlocks == null || replaceableBlocks.isEmpty()) { - return true; - } - return replaceableBlockData.aquire(this::resolveReplaceableBlocks) - .contains(IrisProceduralBlocks.materialKey(state)); - } - - public boolean matchesBiome(IrisBiome surfaceBiome, IrisBiome caveBiome) { - IrisBiome selected = biomeScope == IrisDepositBiomeScope.SURFACE ? surfaceBiome : caveBiome; - if (includedBiomes != null && !includedBiomes.isEmpty() && !matchesAnyBiome(selected, includedBiomes)) { - return false; - } - return excludedBiomes == null || excludedBiomes.isEmpty() || !matchesAnyBiome(selected, excludedBiomes); - } - - public boolean usesCaveBiomeFilter() { - return biomeScope == IrisDepositBiomeScope.CAVE - && ((includedBiomes != null && !includedBiomes.isEmpty()) - || (excludedBiomes != null && !excludedBiomes.isEmpty())); - } - - private KSet resolveReplaceableBlocks() { - KSet resolved = new KSet<>(); - for (String key : replaceableBlocks) { - PlatformBlockState state = B.getStateOrNull(key, false); - if (state != null) { - resolved.add(IrisProceduralBlocks.materialKey(state)); - } - } - return resolved; - } - - private boolean matchesAnyBiome(IrisBiome biome, KList configuredBiomes) { - if (biome == null) { - return false; - } - for (String configured : configuredBiomes) { - String namespaced = configured.contains(":") ? configured : "minecraft:" + configured; - if (configured.equals(biome.getLoadKey()) - || namespaced.equals(biome.getDerivativeKey()) - || namespaced.equals(biome.getVanillaDerivativeKey())) { - return true; - } - } - return false; - } - - record ClumpCacheKey(long depositSeed, int minSize, int maxSize) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java deleted file mode 100644 index 57d9cf943..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositHeightDistribution.java +++ /dev/null @@ -1,13 +0,0 @@ -package art.arcane.iris.engine.object.terrain.deposit; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Controls how a deposit chooses its origin height within the configured vertical band.") -public enum IrisDepositHeightDistribution { - @Desc("Samples uniformly after clipping the configured band to the terrain and build-height bounds.") - CLIPPED_UNIFORM, - @Desc("Samples uniformly from the configured band, then rejects origins outside the terrain or build-height bounds.") - UNIFORM, - @Desc("Samples toward the middle of the configured band with a triangular distribution, then rejects invalid origins.") - TRIANGLE -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java deleted file mode 100644 index 9fd557476..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositPlacementScope.java +++ /dev/null @@ -1,13 +0,0 @@ -package art.arcane.iris.engine.object.terrain.deposit; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Controls which vertical part of the world may contain a deposit origin.") -public enum IrisDepositPlacementScope { - @Desc("Places in solid terrain below the generated surface while preserving the configured surface clearance.") - TERRAIN, - @Desc("Places only in existing solid hosts above the generated terrain surface.") - ABOVE_TERRAIN, - @Desc("Places in existing solid hosts anywhere within the dimension build height.") - FULL_HEIGHT -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java deleted file mode 100644 index f8d2d1ea2..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositShape.java +++ /dev/null @@ -1,13 +0,0 @@ -package art.arcane.iris.engine.object.terrain.deposit; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Selects the geometry used to build each deposit clump.") -public enum IrisDepositShape { - @Desc("Builds the traditional Iris fixed-block-count cube clump.") - IRIS, - @Desc("Builds a chain of overlapping ellipsoids matching Minecraft's ordinary ore-vein geometry.") - VANILLA_ELLIPSOID, - @Desc("Builds sparse candidate offsets matching Minecraft's scattered-ore geometry.") - VANILLA_SCATTERED -} From 5a99c2e70cc1c3d9f2bf9bd2324c2f2d675c53fe Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 14:33:08 +0200 Subject: [PATCH 023/139] Build the built-in modules as a pack module jar from a list of module classes and check it with IrisApi's pack class checks builtinModulesJar packages the classes listed in builtin-modules.txt from Iris core's compiled output, writes the module entry points, runs ModuleJarCheck on the result and only then puts build/libs/iris-builtins.jar in place. Nothing is listed yet. --- README.md | 11 +++++ build.gradle.kts | 112 +++++++++++++++++++++++++++++++++++++++++++- builtin-modules.txt | 16 +++++++ 3 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 builtin-modules.txt diff --git a/README.md b/README.md index c2b3b66e1..b58978283 100644 --- a/README.md +++ b/README.md @@ -37,3 +37,14 @@ core against the existing allowlist. 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. + +## Built-in modules as a pack module jar + +`./gradlew builtinModulesJar` builds `build/libs/iris-builtins.jar`, the built-in modules as an ordinary pack +module jar for a pack's `modules/` folder. `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 classes come from Iris core's compiled output, which the task builds first. +Before the jar lands in `build/libs`, `ModuleJarCheck` of IrisApi runs the class checks of a pack load on it, +with `art.arcane.iris.builtin` as the only exposed Iris package; a listed class that uses Iris internals fails +the task naming the class and what it uses. `check` runs the task. Nothing is ported yet, so the jar is empty +and not loadable as a pack module (a pack module jar must name at least one module). diff --git a/build.gradle.kts b/build.gradle.kts index eae86dccb..17cf1bfd4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,9 @@ import org.gradle.jvm.tasks.Jar +import java.io.ByteArrayOutputStream plugins { base + `java-base` } group = "art.arcane" @@ -33,8 +35,116 @@ val checkBuiltins = tasks.register("checkBuiltins") { ) } +// The built-ins as a pack module jar, to put into a pack's modules/ folder. What goes in is listed in builtin-modules.txt. + +/** What [builtinModulesFile] lists: module classes (the jar's entry points) and further class patterns. */ +data class BuiltinModuleList(val moduleClasses: List, val classPatterns: List) { + /** Ant patterns, relative to the class root, of every class the jar takes from Iris's compiled classes. */ + fun packagedClassPatterns(): List = + moduleClasses.flatMap { listOf(it.replace('.', '/') + ".class", it.replace('.', '/') + "$*.class") } + classPatterns +} + +fun readBuiltinModuleList(file: File): BuiltinModuleList { + val moduleClasses = mutableListOf() + val classPatterns = mutableListOf() + file.readLines().map { it.substringBefore('#').trim() }.filter { it.isNotEmpty() }.forEach { line -> + val (keyword, value) = line.split(Regex("\\s+"), limit = 2).let { it[0] to it.getOrElse(1) { "" }.trim() } + require(value.isNotEmpty()) { "${file.name}: '$line' needs a value after '$keyword'" } + when (keyword) { + "module" -> moduleClasses += value + "include" -> classPatterns += value + else -> throw GradleException("${file.name}: unknown line '$line'; start it with 'module' or 'include'") + } + } + return BuiltinModuleList(moduleClasses, classPatterns) +} + +val builtinModulesFile = layout.projectDirectory.file("builtin-modules.txt").asFile +val builtinModuleList = readBuiltinModuleList(builtinModulesFile) +val builtinModulesJarName = "iris-builtins.jar" +val builtinModuleEntryFile = "com.volmit.IrisModule" + +/** Host packages pack modules may use besides the IrisApi. Keep in step with IrisModuleHost.BUILT_IN_API_PACKAGE in Iris. */ +val exposedHostPackages = listOf("art.arcane.iris.builtin") +val irisClasses = irisRoot.resolve("core/build/classes/java/main") +val builtinModulesBuild = layout.buildDirectory.dir("builtin-modules") +val checkedJarsDirectory = layout.buildDirectory.dir("libs") + +val irisApiForChecks by configurations.creating { + isCanBeConsumed = false + attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) +} + +dependencies { + irisApiForChecks("com.volmit:IrisApi") +} + +val compileBuiltins = tasks.register("compileBuiltins") { + description = "Compiles Iris core together with the built-in sources, which is where the jar's classes come from." + workingDir(irisRoot) + val offline = if (gradle.startParameter.isOffline) listOf("--offline") else emptyList() + commandLine(listOf("./gradlew", ":core:compileJava", "-PincludeModdedAdapters=false", "--console=plain") + offline) +} + +val writeBuiltinModuleEntries = tasks.register("writeBuiltinModuleEntries") { + description = "Writes the 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 { + entries.get().asFile.apply { parentFile.mkdirs() }.writeText(builtinModuleList.moduleClasses.joinToString("\n", postfix = "\n")) + } +} + +val packageBuiltinModules = tasks.register("packageBuiltinModules") { + description = "Packages the listed built-in modules and classes before they are checked." + dependsOn(compileBuiltins) + archiveFileName.set(builtinModulesJarName) + destinationDirectory.set(builtinModulesBuild.map { it.dir("unchecked") }) + inputs.file(builtinModulesFile) + val patterns = builtinModuleList.packagedClassPatterns() + // An empty include list would take every class of Iris. + if (patterns.isNotEmpty()) { + from(irisClasses) { include(patterns) } + from(writeBuiltinModuleEntries) { into("META-INF/services") } + } +} + +val checkBuiltinModulesJar = tasks.register("checkBuiltinModulesJar") { + description = "Runs IrisApi's pack class and reference checks on the packaged jar, as a pack load would." + dependsOn(packageBuiltinModules) + // A jar without module entries is not a loadable pack module; there is nothing to check until a module is listed. + onlyIf { builtinModuleList.moduleClasses.isNotEmpty() } + val packaged = packageBuiltinModules.flatMap { it.archiveFile } + classpath = irisApiForChecks + files(irisClasses) + mainClass.set("com.volmit.host.ModuleJarCheck") + javaLauncher.set(javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(25)) }) + argumentProviders.add(CommandLineArgumentProvider { listOf(packaged.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. + checkedJarsDirectory.get().file(builtinModulesJarName).asFile.delete() + } + doLast { + if (executionResult.get().exitValue == 0) return@doLast + 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.") + } +} + +tasks.register("builtinModulesJar") { + group = "build" + description = "Builds build/libs/$builtinModulesJarName, the built-in modules as a pack module jar for a pack's modules/ folder." + dependsOn(checkBuiltinModulesJar) + from(packageBuiltinModules.flatMap { it.archiveFile }) + into(checkedJarsDirectory) +} + tasks.named("check") { - dependsOn(checkBuiltins, "builtinSourcesJar") + dependsOn(checkBuiltins, "builtinSourcesJar", "builtinModulesJar") } tasks.named("assemble") { diff --git a/builtin-modules.txt b/builtin-modules.txt new file mode 100644 index 000000000..71a8684bd --- /dev/null +++ b/builtin-modules.txt @@ -0,0 +1,16 @@ +# What goes into build/libs/iris-builtins.jar, the built-in modules as a pack module jar. +# +# A line is one of (blank lines and # comments are ignored): +# +# module an IrisModule class. It is listed in META-INF/services/com.volmit.IrisModule, +# and its nested classes are packaged with it. +# include more classes for the jar, as an Ant pattern relative to the class root, such as +# art/arcane/iris/engine/modifier/carve/** Settings types, helpers and stage +# constants a listed module owns go here. +# +# A class here must be one a pack module may have: it may use only the IrisApi, the packages Iris exposes +# (art.arcane.iris.builtin), the JDK and the other classes of the jar. `./gradlew builtinModulesJar` checks +# that with IrisApi's pack class checks and fails naming the class and what it uses. +# +# Moving a module here means removing it from IrisModuleHost.generationModules() or PlacementModules.all() in Iris. +# Nothing is ported yet. From 03f7d20e1a8b280e88ad88f929cfe9c6b752bd48 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 14:35:34 +0200 Subject: [PATCH 024/139] Provide ObjectsAt from iris:objects and StructureLocator from iris:structure (StructureLocating), drop a world's structure index when it stops, and keep iris:decorant's Decorating in the world's state store --- README.md | 8 +++ .../iris/engine/actuator/DecorantModule.java | 15 ++++- .../structure/StructureLocating.java | 63 +++++++++++++++++++ .../structure/StructureResources.java | 14 ++++- .../mantle/components/ObjectModule.java | 21 ++++++- .../mantle/components/StructureModule.java | 20 +++++- 6 files changed, 133 insertions(+), 8 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java diff --git a/README.md b/README.md index c2b3b66e1..1a2932660 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,14 @@ pools and jigsaw pieces as resource kinds (`StructureResources`), from the folde used, and checks them with its validator (`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris validates a pack; Iris core has no loader or validator of its own for them any more. +Built-in modules answer Iris through IrisApi services instead of Iris reading their features: `iris:objects` +provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure` +provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a +world places, and their nearest start for the find commands). `iris:structure` also has a lifecycle hook that drops a +world's structure index when the world stops, which includes every reload of the pack's structure files. +`iris:decorant` keeps its per-world `Decorating` in the world's state store (`context.world().state(...)`); the other +built-ins still reach the same store through `IrisChunk.state(...)` / `engine.getGeneration().state(...)`. + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 25647cc71..1bd6b4195 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -20,6 +20,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; @@ -37,6 +38,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; import java.util.function.Predicate; @@ -60,10 +62,15 @@ public final class DecorantModule implements IrisModule { private static void decorate(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - chunk.state(Decorating.class, Decorating::new).decorate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); + decorating(context.world()).decorate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); } - /** What decorating keeps for one engine runtime: one decorator per kind of place. */ + /** The world's decorating, kept in its state store. */ + static Decorating decorating(PackWorld world) { + return world.state(Decorating.class, Decorating::new); + } + + /** What decorating keeps for one world: one decorator per kind of place. */ static final class Decorating { private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); @@ -73,6 +80,10 @@ public final class DecorantModule implements IrisModule { private final EngineDecorator seaFloorDecorator; private final EngineDecorator shoreLineDecorator; + Decorating(PackWorld world) { + this(IrisPackWorld.of(world).engine()); + } + Decorating(Engine engine) { this.engine = engine; surfaceDecorator = new IrisSurfaceDecorator(engine); 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 new file mode 100644 index 000000000..3f45eb15b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java @@ -0,0 +1,63 @@ +/* + * 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.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.IrisStructureLocator; +import com.volmit.resource.PackResources; +import com.volmit.service.LocateResult; +import com.volmit.service.StructureLocator; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import java.util.LinkedHashSet; +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}. Vanilla structures that Iris places through native placements are not among them; the + * host's vanilla structure handling finds those. + */ +public final class StructureLocating implements StructureLocator { + @Override + public Set structures(PackResources pack) { + return new LinkedHashSet<>(StructureResources.structureKeysOf(pack)); + } + + @Override + public Set locatable(PackWorld world) { + return IrisStructureLocator.locatableEditableKeys(engine(world)); + } + + @Override + public LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks) { + Engine engine = engine(world); + 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 IrisPackWorld.of(world).engine(); + } +} 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 index e4f22b51e..1ed3beebf 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -23,6 +23,7 @@ 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; @@ -67,7 +68,12 @@ public final class StructureResources { /** The key of every structure of the pack, in key order. */ public static List structureKeys(IrisData data) { - return keys(data, STRUCTURES); + 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. */ @@ -89,6 +95,10 @@ public final class StructureResources { /** 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 data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); + return keys(data.getPackResources(), kind); + } + + private static List keys(PackResources pack, ResourceKind kind) { + return pack.ids(kind.type()).stream().map(ResourceId::path).toList(); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 9bd2a2fce..6e7b4fd5e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -21,17 +21,24 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; +import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.PackSettings; +import com.volmit.service.ObjectsAt; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; + +import java.util.Set; /** * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work - * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. + * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells + * Iris which objects a chunk would get ({@link ObjectsAt}), for the object search and studio tools. */ public final class ObjectModule implements IrisModule { private static final String VERSION = "built-in"; @@ -46,6 +53,11 @@ public final class ObjectModule implements IrisModule { graph.define(IrisStages.Objects.PLACE).requires(IrisStages.Carve.CAVES).reach(ObjectModule::reach).run(ObjectModule::place); } + @Override + public void register(FeatureRegistry registry) { + registry.registerService(ObjectsAt.class, ObjectModule::objectsAt); + } + private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); @@ -55,7 +67,12 @@ public final class ObjectModule implements IrisModule { return placing(IrisPackSettings.of(settings).engine()).reach(); } - /** The engine runtime's object placing, which {@link Engine#getObjectsAt} also asks. */ + /** The keys of the objects the surface placements of the chunk's biome and region would place, guessed without generating it. */ + private static Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return placing(IrisPackWorld.of(world).engine()).guess(chunkX, chunkZ); + } + + /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks. */ public static ObjectPlacing placing(Engine engine) { return engine.getGeneration().state(ObjectPlacing.class, ObjectPlacing::new); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 8611724c6..f1aa7f19b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -21,15 +21,21 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; +import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.IrisStructureLocator; +import art.arcane.iris.engine.framework.structure.StructureLocating; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.framework.structure.StructureValidator; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; import com.volmit.config.PackSettings; +import com.volmit.service.StructureLocator; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; /** * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear @@ -38,9 +44,11 @@ import com.volmit.stage.StageGraph; *

* The module owns the pack's structures, jigsaw pools and jigsaw pieces as resource kinds * ({@link StructureResources}), read from the folders packs have always used, and checks them with - * {@link StructureValidator} wherever Iris validates a pack. + * {@link StructureValidator} wherever Iris validates a pack. It lets Iris find its structures through + * {@link StructureLocating}, and forgets a world's structure index when the world stops, which includes every reload of + * the pack's structure files. */ -public final class StructureModule implements IrisModule { +public final class StructureModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @Override @@ -58,6 +66,14 @@ public final class StructureModule implements IrisModule { public void register(FeatureRegistry registry) { StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new StructureValidator()); + registry.registerService(StructureLocator.class, new StructureLocating()); + registry.registerLifecycle(this); + } + + /** The structure index is still kept per engine rather than in the world's state, so a stopping world drops it. */ + @Override + public void worldStopped(PackWorld world) { + IrisStructureLocator.invalidate(IrisPackWorld.of(world).engine()); } private static void place(MantleStageContext context) { From 182fea6002dd03fa702bb2cf3e86e0ec164bc18c Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 14:41:06 +0200 Subject: [PATCH 025/139] Decide over vanilla structures through the structure module's vanilla structure hook: REPLACE where an Iris structure placement replaces the structure, ALSO_PLACE where a placement places it --- .../mantle/components/StructureModule.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 8611724c6..3c5c5d034 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -22,14 +22,18 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.framework.structure.StructureValidator; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.PackSettings; +import com.volmit.resource.ResourceId; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; +import com.volmit.vanilla.VanillaStructureContext; +import com.volmit.vanilla.VanillaStructureRule; /** * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear @@ -39,6 +43,9 @@ import com.volmit.stage.StageGraph; * The module owns the pack's structures, jigsaw pools and jigsaw pieces as resource kinds * ({@link StructureResources}), read from the folders packs have always used, and checks them with * {@link StructureValidator} wherever Iris validates a pack. + *

+ * It decides over the platform's own structures through its vanilla structure hook ({@link #vanillaRule}): a structure + * an Iris structure replaces is blocked, and one a structure placement of the pack places is reported as placed here. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; @@ -58,6 +65,21 @@ public final class StructureModule implements IrisModule { public void register(FeatureRegistry registry) { StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new StructureValidator()); + registry.registerVanillaStructureHook(StructureModule::vanillaRule); + } + + /** + * {@link VanillaStructureRule#REPLACE} for a platform structure that an Iris structure of the world's placements + * replaces (its {@code vanillaSource} with native suppression), {@link VanillaStructureRule#ALSO_PLACE} for one + * a placement of the world places itself, {@link VanillaStructureRule#GENERATE} otherwise. + */ + static VanillaStructureRule vanillaRule(ResourceId structure, VanillaStructureContext context) { + Engine engine = IrisPackSettings.of(context.settings()).engine(); + String key = structure.toString(); + if (IrisStructureLocator.suppressesVanilla(engine, key)) { + return VanillaStructureRule.REPLACE; + } + return IrisStructureLocator.isPlaced(engine, key) ? VanillaStructureRule.ALSO_PLACE : VanillaStructureRule.GENERATE; } private static void place(MantleStageContext context) { From 04ce02c042324ed85f5fe4ebf0b35280f9c9330d Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:21:14 +0200 Subject: [PATCH 026/139] iris:deposit is written under its feature id only; drop the deposits alias --- README.md | 2 +- .../art/arcane/iris/builtin/deposit/DepositGenerator.java | 2 +- .../java/art/arcane/iris/builtin/deposit/DepositSettings.java | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index fab47dd64..8de696f27 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ built-ins still reach the same store through `IrisChunk.state(...)` / `engine.ge Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in -`art.arcane.iris.builtin.deposit`), and packs write the same `deposits` JSON as before. What needs Iris (resolving the +`art.arcane.iris.builtin.deposit`), and packs write `"iris:deposit": {"generators": [...]}` (the old `"deposits": [...]` is converted by the pack migration script). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java index ce176754c..1a49e9109 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java @@ -29,7 +29,7 @@ import java.util.Collections; import java.util.List; /** - * One kind of deposit a dimension, region or biome generates, as packs write it in {@code "deposits": [...]} or under + * One kind of deposit a dimension, region or biome generates, as packs write it in the {@code generators} of {@code "iris:deposit"} or under * {@code snippet/deposit/}: how many clumps of which blocks, how large, at which heights and in which biomes. A value * of IrisApi types only; the deposit module builds the clumps and resolves the blocks. */ diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java index a6017142b..8da34c2ce 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java @@ -26,12 +26,12 @@ import com.volmit.config.Feature; import java.util.List; /** - * The deposits one dimension, region or biome declares, written as {@code "deposits": [...]}. Levels stack: + * The deposits one dimension, region or biome declares, written as {@code "iris:deposit": {"generators": [...]}}. Levels stack: * a chunk gets the deposits of its dimension, its centre column's region and that column's biome. IrisApi types only, * like {@link DepositGenerator}. */ @Desc("Ores and other deposits generated in every chunk where this applies") -@Feature(id = "iris:deposit", name = "Deposits", alias = "deposits", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:deposit", name = "Deposits", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) public final class DepositSettings implements IrisFeature { @Desc("Define deposit generators that this applies to chunks") private List generators = List.of(); From c1f23830a296dbdd2ba885f7d8d31728c4c04408 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:27:12 +0200 Subject: [PATCH 027/139] Put @MinItems(1) back on the deposit generator's palette and biome lists --- .../art/arcane/iris/builtin/deposit/DepositGenerator.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java index 1a49e9109..843f5757b 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java @@ -21,6 +21,7 @@ package art.arcane.iris.builtin.deposit; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -104,6 +105,7 @@ public final class DepositGenerator { private double discardChanceOnAirExposure = 0; @Required + @MinItems(1) @Desc("The palette of blocks to be used in this deposit generator. Each entry is picked uniformly; the per-entry weight field is ignored here.") private List palette = List.of(); @@ -112,15 +114,18 @@ public final class DepositGenerator { @Desc("Ore varience is how many different objects clumps iris will create") private int varience = 3; + @MinItems(1) @Desc("Optional block ids this deposit may replace. An empty list retains Iris's any-solid behavior.") private List replaceableBlocks = List.of(); @Desc("Chooses whether includedBiomes and excludedBiomes inspect the surface biome or the cave biome at the deposit origin.") private DepositBiomeScope biomeScope = DepositBiomeScope.CAVE; + @MinItems(1) @Desc("Optional Iris biome keys or vanilla derivative ids allowed for this deposit.") private List includedBiomes = List.of(); + @MinItems(1) @Desc("Optional Iris biome keys or vanilla derivative ids denied for this deposit.") private List excludedBiomes = List.of(); From 63bd3e3de8e38ff40016fe74ad39f47656552df6 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:45:00 +0200 Subject: [PATCH 028/139] Keep the object scale cache in world state and the structure graph catalog per resource snapshot IrisObjectScale takes the engine and keeps its scaled variants in the world's state store; the structure graph catalog is keyed by the pack's resource snapshot. Both are rebuilt when a resource reload starts a new world or snapshot, so IrisData no longer invalidates them by hand. --- .../structure/StructureGraphCatalog.java | 20 +++-- .../components/FloatingObjectPlacing.java | 12 +-- .../mantle/components/ObjectPlacing.java | 8 +- .../engine/object/prefab/IrisObjectScale.java | 79 +++++-------------- 4 files changed, 40 insertions(+), 79 deletions(-) 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 index 42e00e57d..9b6a46333 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java @@ -1,6 +1,7 @@ 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; @@ -14,10 +15,14 @@ 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 = + private static final Cache> CACHE = Caffeine.newBuilder().weakKeys().build(); - private static final Cache> RUNTIME_OUTPUT = + 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); @@ -33,17 +38,10 @@ public final class StructureGraphCatalog { return compileAndReport(activeData, activeStructure); } ConcurrentMap catalog = CACHE.get( - activeData, ignored -> new ConcurrentHashMap<>()); + activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure)); } - public static void invalidate(IrisData data) { - if (data != null) { - CACHE.invalidate(data); - RUNTIME_OUTPUT.invalidate(data); - } - } - public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure) { IrisData activeData = Objects.requireNonNull(data); IrisStructure activeStructure = Objects.requireNonNull(structure); @@ -55,7 +53,7 @@ public final class StructureGraphCatalog { return sampleRuntimeAssembly(activeData, activeStructure); } ConcurrentMap catalog = RUNTIME_OUTPUT.get( - activeData, ignored -> new ConcurrentHashMap<>()); + activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); return catalog.computeIfAbsent( structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure)); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 249c80a13..d949e55a1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -184,12 +184,12 @@ public class FloatingObjectPlacing { if (raw == null) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw); + IrisObject obj0 = placement.getScale().get(rng, raw, engine); if (obj0 == null) { continue; } if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0); + obj0 = entry.getShrinkScale().get(rng, obj0, engine); if (obj0 == null) { continue; } @@ -232,12 +232,12 @@ public class FloatingObjectPlacing { if (raw == null) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw); + IrisObject obj0 = placement.getScale().get(rng, raw, engine); if (obj0 == null) { continue; } if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0); + obj0 = entry.getShrinkScale().get(rng, obj0, engine); if (obj0 == null) { continue; } @@ -317,12 +317,12 @@ public class FloatingObjectPlacing { if (raw == null) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw); + IrisObject obj0 = placement.getScale().get(rng, raw, engine); if (obj0 == null) { continue; } if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0); + obj0 = entry.getShrinkScale().get(rng, obj0, engine); if (obj0 == null) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 8702ababf..7d510ce9a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -663,7 +663,7 @@ public class ObjectPlacing { for (int i = 0; i < density; i++) { attempts++; - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); if (v == null) { nullObjects++; if (traceRegen) { @@ -801,7 +801,7 @@ public class ObjectPlacing { for (int i = 0; i < density; i++) { attempts++; - IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); if (object == null) { nullObjects++; if (traceRegen) { @@ -1034,7 +1034,7 @@ public class ObjectPlacing { int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); for (int i = 0; i < density; i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng)); + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); if (v == null) { continue; } @@ -1419,7 +1419,7 @@ public class ObjectPlacing { private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { Set f = new KSet<>(); for (int i = 0; i < objectPlacement.getDensity(rng, x, z, engine.getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng)); + IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng), engine); if (v == null) { continue; } 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 index b49d6de06..be7afb455 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.prefab; -import art.arcane.iris.core.loader.IrisData; +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; @@ -49,11 +49,6 @@ public class IrisObjectScale { 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; - private static final ScaleCache CACHE = new ScaleCache(resolveCacheMaximumEstimatedBytes()); - - public static void invalidate(IrisData owner) { - CACHE.invalidate(owner); - } @MinNumber(0.01) @MaxNumber(50) @@ -99,7 +94,8 @@ public class IrisObjectScale { return Math.max(minimumScale, maximumScale); } - public IrisObject get(RNG rng, IrisObject origin) { + /** 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; } @@ -110,40 +106,33 @@ public class IrisObjectScale { } int variantIndex = request.selectVariant(rng); - CacheKey key = CACHE.key(origin, request, variantIndex); - CacheLookup lookup = CACHE.lookup(key); - if (lookup.variant() != null) { - return lookup.variant(); + 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)) { - CacheLookup afterWait = CACHE.lookup(key); - if (afterWait.variant() != null) { - return afterWait.variant(); + 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.putIfCurrent(key, variant, estimatedBytes, lookup.generation()); + 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; } - static int cacheEntryCount() { - return CACHE.size(); - } - - static long cacheEstimatedBytes() { - return CACHE.estimatedBytes(); - } - - static boolean isOriginCached(IrisObject origin) { - return CACHE.containsOrigin(origin); - } - private ScaleRequest snapshotRequest() { IrisObjectPlacementScaleInterpolator configuredInterpolation = interpolation == null ? IrisObjectPlacementScaleInterpolator.NONE @@ -217,7 +206,6 @@ public class IrisObjectScale { } static final class CacheKey extends WeakReference { - private final IrisData owner; private final ScaleRequest request; private final int variantIndex; private final int originRevision; @@ -231,22 +219,16 @@ public class IrisObjectScale { CacheKey(IrisObject origin, ScaleRequest request, int variantIndex, ReferenceQueue collectedOrigins) { super(origin, collectedOrigins); - this.owner = origin.getLoader(); this.request = request; this.variantIndex = variantIndex; this.originRevision = originRevision(origin); int result = System.identityHashCode(origin); - result = (31 * result) + System.identityHashCode(owner); result = (31 * result) + originRevision; result = (31 * result) + request.hashCode(); this.loadHashCode = result; this.hashCode = (31 * result) + variantIndex; } - boolean belongsTo(IrisData candidate) { - return owner == candidate; - } - boolean hasOrigin(IrisObject candidate) { return get() == candidate; } @@ -262,7 +244,6 @@ public class IrisObjectScale { IrisObject origin = get(); return origin != null && origin == other.get() - && owner == other.owner && originRevision == other.originRevision && request.equals(other.request) && variantIndex == other.variantIndex; @@ -300,16 +281,12 @@ public class IrisObjectScale { } } - record CacheLookup(IrisObject variant, long generation) { - } - static final class ScaleCache { private final long maximumEstimatedBytes; private final LinkedHashMap entries; private final Object[] loadLocks; private final ReferenceQueue collectedOrigins; private long estimatedBytes; - private long generation; ScaleCache(long maximumEstimatedBytes) { if (maximumEstimatedBytes <= 0L) { @@ -332,20 +309,19 @@ public class IrisObjectScale { return loadLocks[key.loadHashCode() & (loadLocks.length - 1)]; } - synchronized CacheLookup lookup(CacheKey key) { + synchronized IrisObject lookup(CacheKey key) { drainCollectedOrigins(); CacheValue value = entries.get(key); - return new CacheLookup(value == null ? null : value.variant(), generation); + return value == null ? null : value.variant(); } - synchronized IrisObject putIfCurrent(CacheKey key, IrisObject variant, - long entryEstimatedBytes, long expectedGeneration) { + synchronized IrisObject putIfAbsent(CacheKey key, IrisObject variant, long entryEstimatedBytes) { drainCollectedOrigins(); CacheValue present = entries.get(key); if (present != null) { return present.variant(); } - if (generation != expectedGeneration || entryEstimatedBytes > maximumEstimatedBytes) { + if (entryEstimatedBytes > maximumEstimatedBytes) { return variant; } @@ -355,19 +331,6 @@ public class IrisObjectScale { return variant; } - synchronized void invalidate(IrisData owner) { - drainCollectedOrigins(); - generation++; - Iterator> iterator = entries.entrySet().iterator(); - while (iterator.hasNext()) { - Map.Entry entry = iterator.next(); - if (entry.getKey().belongsTo(owner)) { - estimatedBytes -= entry.getValue().estimatedBytes(); - iterator.remove(); - } - } - } - synchronized int size() { drainCollectedOrigins(); return entries.size(); From 37bc1a0e70c823ce99a94d9f4a32d55086b52c9d Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 20:51:05 +0200 Subject: [PATCH 029/139] ObjectLocating: iris:objects names the biomes and regions that place an object --- .../mantle/components/ObjectLocating.java | 55 +++++++++++++++++++ .../mantle/components/ObjectModule.java | 14 +---- 2 files changed, 58 insertions(+), 11 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java new file mode 100644 index 000000000..2f002ae1e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -0,0 +1,55 @@ +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import com.volmit.service.ObjectsAt; +import com.volmit.world.PackWorld; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * How {@code iris:objects} tells Iris where its objects are: the objects the biome and region of a chunk would place, + * and the biomes and regions whose surface placements name an object. + */ +public final class ObjectLocating implements ObjectsAt { + @Override + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return ObjectModule.placing(engine(world)).guess(chunkX, chunkZ); + } + + @Override + public PlacedBy placedBy(PackWorld world, String objectKey) { + Engine engine = engine(world); + Set biomes = new LinkedHashSet<>(); + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { + if (biome != null && placesObject(biome.getSurfaceObjects(), objectKey)) { + biomes.add(biome.getLoadKey()); + } + } + + Set regions = new LinkedHashSet<>(); + for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { + if (region != null && placesObject(region.getSurfaceObjects(), objectKey)) { + regions.add(region.getLoadKey()); + } + } + return new PlacedBy(biomes, regions); + } + + private static boolean placesObject(List placements, String objectKey) { + for (IrisObjectPlacement placement : placements) { + if (placement != null && placement.getPlace().contains(objectKey)) { + return true; + } + } + return false; + } + + private static Engine engine(PackWorld world) { + return IrisPackWorld.of(world).engine(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 6e7b4fd5e..c39b696bf 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; @@ -30,15 +29,13 @@ import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; -import com.volmit.world.PackWorld; - -import java.util.Set; /** * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells - * Iris which objects a chunk would get ({@link ObjectsAt}), for the object search and studio tools. + * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the + * object search and studio tools. */ public final class ObjectModule implements IrisModule { private static final String VERSION = "built-in"; @@ -55,7 +52,7 @@ public final class ObjectModule implements IrisModule { @Override public void register(FeatureRegistry registry) { - registry.registerService(ObjectsAt.class, ObjectModule::objectsAt); + registry.registerService(ObjectsAt.class, new ObjectLocating()); } private static void place(MantleStageContext context) { @@ -67,11 +64,6 @@ public final class ObjectModule implements IrisModule { return placing(IrisPackSettings.of(settings).engine()).reach(); } - /** The keys of the objects the surface placements of the chunk's biome and region would place, guessed without generating it. */ - private static Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return placing(IrisPackWorld.of(world).engine()).guess(chunkX, chunkZ); - } - /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks. */ public static ObjectPlacing placing(Engine engine) { return engine.getGeneration().state(ObjectPlacing.class, ObjectPlacing::new); From 587c24deb508b82f8339bedf6e55ace3af4a2d40 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 21:59:43 +0200 Subject: [PATCH 030/139] Decorators become iris:decorant settings of IrisApi types; the decorant module keeps the resolved decorators per world Decorator, DecorationPart, DecoratorSlope and DecorantSettings (iris:decorant, biome level) replace IrisDecorator and IrisDecorationPart. ResolvedDecorator holds the blocks and noise, BiomeDecorators the per-world buckets, warm-up and load figures. Ore and object warm-up move into the terrain and objects modules' warmUp. --- .../builtin/decorant/DecorantSettings.java | 51 +++ .../decorant/DecorationPart.java} | 10 +- .../iris/builtin/decorant/Decorator.java | 202 ++++++++++ .../iris/builtin/decorant/DecoratorSlope.java | 64 ++++ .../iris/engine/actuator/DecorantModule.java | 27 +- .../iris/engine/actuator/OreWarmUp.java | 73 ++++ .../iris/engine/actuator/TerrainModule.java | 19 +- .../engine/decorator/BiomeDecorators.java | 173 +++++++++ .../iris/engine/decorator/DecoratorCore.java | 118 +++--- .../engine/decorator/FloatingDecorator.java | 12 +- .../decorator/IrisCeilingDecorator.java | 14 +- .../engine/decorator/IrisEngineDecorator.java | 8 +- .../decorator/IrisSeaFloorDecorator.java | 25 +- .../decorator/IrisSeaSurfaceDecorator.java | 22 +- .../decorator/IrisShoreLineDecorator.java | 25 +- .../decorator/IrisSurfaceDecorator.java | 24 +- .../engine/decorator/ResolvedDecorator.java | 269 +++++++++++++ .../mantle/components/ObjectModule.java | 12 +- .../mantle/components/ObjectWarmUp.java | 91 +++++ .../iris/engine/modifier/CaveApplying.java | 16 +- .../iris/engine/modifier/FloatingIslands.java | 4 +- .../object/decoration/IrisDecorator.java | 356 ------------------ .../engine/object/world/biome/IrisBiome.java | 24 -- .../world/biome/IrisBiomeColorRenderer.java | 11 +- 24 files changed, 1086 insertions(+), 564 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java rename src/main/java/art/arcane/iris/{engine/object/decoration/IrisDecorationPart.java => builtin/decorant/DecorationPart.java} (81%) create mode 100644 src/main/java/art/arcane/iris/builtin/decorant/Decorator.java create mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java new file mode 100644 index 000000000..775ac54c3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java @@ -0,0 +1,51 @@ +/* + * 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.builtin.decorant; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The decorators one biome declares, written as {@code "iris:decorant": {"decorators": [...]}}. IrisApi types only, like + * {@link Decorator}. + */ +@Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") +@Feature(id = "iris:decorant", name = "Decorators", targets = Target.BIOME) +public final class DecorantSettings implements IrisFeature { + @MinItems(1) + @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") + private List decorators = List.of(); + + public DecorantSettings() { + } + + public DecorantSettings(List decorators) { + this.decorators = List.copyOf(decorators); + } + + public List decorators() { + return decorators == null ? List.of() : Collections.unmodifiableList(decorators); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationPart.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorationPart.java similarity index 81% rename from src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationPart.java rename to src/main/java/art/arcane/iris/builtin/decorant/DecorationPart.java index 38ec3f688..433ac4f25 100644 --- a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationPart.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorationPart.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.decoration; +package art.arcane.iris.builtin.decorant; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Represents a location where decorations should go") -public enum IrisDecorationPart { +public enum DecorationPart { @Desc("The default, decorate anywhere") NONE, diff --git a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java new file mode 100644 index 000000000..9ef5e0eff --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java @@ -0,0 +1,202 @@ +/* + * 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.builtin.decorant; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * One decorator of a biome, as packs write it in the {@code decorators} of {@code "iris:decorant"} or under + * {@code snippet/decorator/}: which blocks it places, where, how often and how tall. A value of IrisApi types only; the + * decorant module resolves the blocks and builds the noise. + */ +@Snippet("decorator") +@Desc("A biome decorator is used for placing flowers, grass, cacti and so on") +public final class Decorator { + private static final String STATIC_NOISE = "STATIC"; + private static final String DEFAULT_BLOCK = "grass"; + + @Desc("The varience dispersion is used when multiple blocks are put in the palette. Scatter scrambles them, Wispy shows streak-looking varience") + private NoiseStyle variance = NoiseStyle.of(STATIC_NOISE); + + @Desc("Forcefully place this decorant anywhere it is supposed to go even if it should not go on a specific surface block. For example, you could force tallgrass to place on top of stone by using this.") + private boolean forcePlace = false; + + @Desc("Forced the surface block of this decorant to be the specified block. Assumes forcePlace.") + private BlockSpec forceBlock; + + @MinItems(1) + @Desc("When set, the decorator can only place onto any of these blocks.") + private List whitelist; + + @MinItems(1) + @Desc("When set, the decorator will never place onto any of these blocks.") + private List blacklist; + + @Desc("The slope at which this decorator can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the decorator placement.") + private DecoratorSlope slopeCondition = new DecoratorSlope(); + + @Desc("If stackMax is set to true, use this to limit its max height for large caverns") + private int absoluteMaxStack = 30; + + @Desc("Dispersion is used to pick places to spawn. Scatter randomly places them (vanilla) or Wispy for a streak like patch system.") + private NoiseStyle style = NoiseStyle.of(STATIC_NOISE); + + @Desc("If this decorator has a height more than 1 this changes how it picks the height between your maxes. Scatter = random, Wispy = wavy heights") + private NoiseStyle heightVariance = NoiseStyle.of(STATIC_NOISE); + + @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") + private DecorationPart partOf = DecorationPart.NONE; + + @MinNumber(1) + @MaxNumber(2032) + @Desc("The minimum repeat stack height (setting to 3 would stack 3 of on top of each other") + private int stackMin = 1; + + @MinNumber(1) + @MaxNumber(2032) + @Desc("The maximum repeat stack height") + private int stackMax = 1; + + @Desc(""" + Changes stackMin and stackMin from being absolute block heights and instead uses them as a percentage to scale the stack based on the cave height + + Within a cave, setting them stackMin/max to 50 would make the stack 50% of the cave height""") + private boolean scaleStack = false; + + @Required + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") + private double chance = 0.1; + + @Required + @MinItems(1) + @Desc("The palette of blocks to pick from when this decorator needs to place.") + private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); + + @MinItems(1) + @Desc("The palette of blocks used at the very top of a 'stackMax' of higher than 1. For example, bamboo tops.") + private List topPalette = List.of(); + + @MinNumber(0.01) + @MaxNumber(1.0) + @Desc("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.") + private double topThreshold = 1.0; + + /** A decorator with every option at its default, as packs get it from {@code {}}. */ + public Decorator() { + } + + public NoiseStyle variance() { + return variance == null ? NoiseStyle.of(STATIC_NOISE) : variance; + } + + public boolean forcePlace() { + return forcePlace; + } + + public Optional forceBlock() { + return Optional.ofNullable(forceBlock); + } + + /** The blocks it may only be placed onto; empty when unset, which {@link #hasWhitelist()} tells apart from an explicitly empty list that blocks all placement. */ + public List whitelist() { + return listOrEmpty(whitelist); + } + + public boolean hasWhitelist() { + return whitelist != null; + } + + public List blacklist() { + return listOrEmpty(blacklist); + } + + public boolean hasBlacklist() { + return blacklist != null; + } + + public DecoratorSlope slopeCondition() { + return slopeCondition == null ? new DecoratorSlope() : slopeCondition; + } + + public int absoluteMaxStack() { + return absoluteMaxStack; + } + + public NoiseStyle style() { + return style == null ? NoiseStyle.of(STATIC_NOISE) : style; + } + + public NoiseStyle heightVariance() { + return heightVariance == null ? NoiseStyle.of(STATIC_NOISE) : heightVariance; + } + + public DecorationPart partOf() { + return partOf == null ? DecorationPart.NONE : partOf; + } + + public int stackMin() { + return stackMin; + } + + public int stackMax() { + return stackMax; + } + + public boolean scaleStack() { + return scaleStack; + } + + public double chance() { + return chance; + } + + public List palette() { + return listOrEmpty(palette); + } + + public List topPalette() { + return listOrEmpty(topPalette); + } + + public double topThreshold() { + return topThreshold; + } + + /** Whether it places more than one block per column. */ + public boolean isStacking() { + return stackMax > 1; + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java b/src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java new file mode 100644 index 000000000..f7ea80716 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java @@ -0,0 +1,64 @@ +/* + * 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.builtin.decorant; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** The terrain slopes a decorator may be placed on, as packs write it in a decorator's {@code slopeCondition}. */ +@Desc("Limits placement to a minimum and maximum terrain slope") +public final class DecoratorSlope { + private static final double UNLIMITED_MINIMUM = 0; + private static final double UNLIMITED_MAXIMUM = 10; + + @MinNumber(0) + @MaxNumber(1024) + @Desc("The minimum slope for placement") + private double minimumSlope = UNLIMITED_MINIMUM; + + @MinNumber(0) + @MaxNumber(1024) + @Desc("The maximum slope for placement") + private double maximumSlope = UNLIMITED_MAXIMUM; + + public DecoratorSlope() { + } + + public double minimumSlope() { + return minimumSlope; + } + + public double maximumSlope() { + return maximumSlope; + } + + /** Whether every slope passes: the limits are the defaults, or looser. */ + public boolean isDefault() { + return minimumSlope <= UNLIMITED_MINIMUM && maximumSlope >= UNLIMITED_MAXIMUM; + } + + public boolean isValid(double slope) { + if (isDefault()) { + return true; + } + + return !(minimumSlope > slope) && !(maximumSlope < slope); + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 1bd6b4195..bf486e46c 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -21,12 +21,14 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineDecorator; +import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; @@ -34,8 +36,10 @@ import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; import com.volmit.world.PackWorld; @@ -43,11 +47,11 @@ import com.volmit.world.PackWorld; import java.util.function.Predicate; /** - * Module {@code iris:decorant}: the biomes' decorators, placed on the surface the mantle's blocks left: the - * surface itself, the sea surface and floor, and the shore line. A dimension turns decorating off with - * {@code decorate}. + * Module {@code iris:decorant}: the biomes' decorators ({@link DecorantSettings}), placed on the surface the mantle's + * blocks left: the surface itself, the sea surface and floor, and the shore line. A dimension turns decorating off with + * {@code decorate}. The decorators' noise is built ahead of generation, in {@link #warmUp}. */ -public final class DecorantModule implements IrisModule { +public final class DecorantModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @Override @@ -55,6 +59,17 @@ public final class DecorantModule implements IrisModule { return ModuleInfo.of("iris:decorant", "Decorators", VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerSettings(DecorantSettings.class); + registry.registerLifecycle(this); + } + + @Override + public void warmUp(PackWorld world) { + BiomeDecorators.of(world).warm(); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Decorant.DECORATE).requires(IrisStages.Matter.INSERT).run(DecorantModule::decorate); @@ -75,6 +90,7 @@ public final class DecorantModule implements IrisModule { private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); private final Engine engine; + private final BiomeDecorators decorators; private final IrisSurfaceDecorator surfaceDecorator; private final EngineDecorator seaSurfaceDecorator; private final EngineDecorator seaFloorDecorator; @@ -86,6 +102,7 @@ public final class DecorantModule implements IrisModule { Decorating(Engine engine) { this.engine = engine; + decorators = BiomeDecorators.of(engine); surfaceDecorator = new IrisSurfaceDecorator(engine); seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); shoreLineDecorator = new IrisShoreLineDecorator(engine); @@ -111,7 +128,7 @@ public final class DecorantModule implements IrisModule { height = context.getRoundedHeight(i, j); biome = context.getBiome().get(i, j); - if (biome.getDecorators().isEmpty()) { + if (!decorators.hasDecorators(biome)) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java new file mode 100644 index 000000000..0e5bbbaf9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -0,0 +1,73 @@ +/* + * 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.actuator; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; +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 art.arcane.volmlib.util.math.RNG; + +import java.util.Comparator; + +/** + * Builds the noise of every ore generator the world's biomes, regions and dimension declare before generation needs it. + * A generator keeps the noise of the first random it is given, so each one is warmed with the random of its place in + * this order: the biomes by key, the regions by key, then the dimension. The order is part of what a world generates. + */ +final class OreWarmUp { + private static final long ROOT_SEED_SALT = 7777L; + + private final Engine engine; + private final RNG root; + private int warmed; + + OreWarmUp(Engine engine) { + this.engine = engine; + this.root = new RNG(engine.getSeedManager().getComponent() + ROOT_SEED_SALT); + } + + void warm() { + KList biomes = engine.getAllBiomes(); + biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); + for (IrisBiome biome : biomes) { + warmAll(biome.getOres()); + } + + KList regions = engine.getDimension().getAllRegions(engine); + regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); + for (IrisRegion region : regions) { + warmAll(region.getOres()); + } + + warmAll(engine.getDimension().getOres()); + } + + private void warmAll(KList ores) { + if (ores == null) { + return; + } + for (IrisOreGenerator ore : ores) { + if (ore != null) { + ore.warm(root.nextParallelRNG(warmed++), engine.getData()); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 4693cb44b..7926c0357 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -21,6 +21,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.framework.Engine; @@ -38,17 +39,21 @@ import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; /** * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up * to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and - * biome replacing blocks on the way and the upper dimension's ground filled in from the top. + * biome replacing blocks on the way and the upper dimension's ground filled in from the top. The ore generators' noise + * is built ahead of generation, in {@link #warmUp}. */ -public final class TerrainModule implements IrisModule { +public final class TerrainModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @Override @@ -56,6 +61,16 @@ public final class TerrainModule implements IrisModule { return ModuleInfo.of("iris:terrain", "Terrain", VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerLifecycle(this); + } + + @Override + public void warmUp(PackWorld world) { + new OreWarmUp(IrisPackWorld.of(world).engine()).warm(); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); diff --git a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java new file mode 100644 index 000000000..e288f9f2e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -0,0 +1,173 @@ +/* + * 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.decorator; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.builtin.decorant.Decorator; +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the decorant module keeps for one world: the decorators of its biomes made ready ({@link ResolvedDecorator}), + * sorted into the places they decorate, and how loaded the busiest biome is. Built from the biomes' {@link DecorantSettings} + * when first asked for, or ahead of generation by {@link #warm()}. + * + *

A decorator's noise seed is a function of the world's decorator seed, its biome's key and its place in the biome's + * list, so it does not depend on which column or which warm-up reached it first. + */ +public final class BiomeDecorators { + private static final ResolvedDecorator[] NO_DECORATORS = new ResolvedDecorator[0]; + private static final int COLUMNS_PER_CHUNK = 256; + private static final long KEY_SEED_FACTOR = 0x9E3779B97F4A7C15L; + private static final long INDEX_SEED_FACTOR = 0xC2B2AE3D27D4EB4FL; + + private final Engine engine; + private final Map> decorators = new ConcurrentHashMap<>(); + private volatile Double busiestBiomeLoad; + + /** @param world a world of an Iris engine */ + BiomeDecorators(PackWorld world) { + this(IrisPackWorld.of(world).engine()); + } + + BiomeDecorators(Engine engine) { + this.engine = engine; + } + + /** The world {@code engine} generates now. */ + public static BiomeDecorators of(Engine engine) { + return engine.getGeneration().state(BiomeDecorators.class, BiomeDecorators::new); + } + + /** The world's decorators, kept in its state store. */ + public static BiomeDecorators of(PackWorld world) { + return world.state(BiomeDecorators.class, BiomeDecorators::new); + } + + /** Whether the biome declares any decorator. */ + public boolean hasDecorators(IrisBiome biome) { + DecorantSettings settings = settingsOf(biome); + return settings != null && !settings.decorators().isEmpty(); + } + + /** The biome's decorators for {@code part}, in the order the biome lists them. */ + ResolvedDecorator[] decorators(IrisBiome biome, DecorationPart part) { + DecorantSettings settings = settingsOf(biome); + if (settings == null) { + return NO_DECORATORS; + } + return decorators.computeIfAbsent(settings, declared -> resolve(biome.getLoadKey(), declared)).getOrDefault(part, NO_DECORATORS); + } + + /** Whether the biome has a decorator for {@code part}. */ + public boolean hasDecorators(IrisBiome biome, DecorationPart part) { + return decorators(biome, part).length > 0; + } + + /** Resolves every decorator of every biome the dimension reaches and builds its noise, so that generation finds them ready. */ + public void warm() { + List biomes = engine.getAllBiomes(); + biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); + for (IrisBiome biome : biomes) { + for (DecorationPart part : DecorationPart.values()) { + for (ResolvedDecorator decorator : decorators(biome, part)) { + decorator.warm(); + } + } + } + } + + /** The most decorating any reachable biome does, as the sum of its decorators' chances times their stack heights. */ + public double busiestBiomeLoad() { + Double cached = busiestBiomeLoad; + if (cached != null) { + return cached; + } + + double busiest = 0D; + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { + busiest = Math.max(busiest, load(biome)); + } + busiestBiomeLoad = busiest; + return busiest; + } + + /** How loaded the biome is with decorators: the sum of their chances times their stack heights, at least one block each. */ + public double load(IrisBiome biome) { + DecorantSettings settings = settingsOf(biome); + if (settings == null) { + return 0D; + } + + double load = 0D; + for (Decorator decorator : settings.decorators()) { + load += Math.max(decorator.stackMax(), 1) * decorator.chance(); + } + return load; + } + + /** How strongly studio's decorator load view colours the biome: the sum of its decorators' chances over a chunk's columns. */ + public double colourLoad(IrisBiome biome) { + DecorantSettings settings = settingsOf(biome); + if (settings == null) { + return 0D; + } + + double load = 0D; + for (Decorator decorator : settings.decorators()) { + load += decorator.chance() * Math.min(1, decorator.stackMax()) * COLUMNS_PER_CHUNK; + } + return load; + } + + private static DecorantSettings settingsOf(IrisBiome biome) { + return biome.getModuleSettings().find(DecorantSettings.class).orElse(null); + } + + private Map resolve(String biomeKey, DecorantSettings settings) { + Map> staging = new EnumMap<>(DecorationPart.class); + List declared = settings.decorators(); + for (int index = 0; index < declared.size(); index++) { + Decorator decorator = declared.get(index); + if (decorator == null) { + continue; + } + ResolvedDecorator resolved = ResolvedDecorator.of(decorator, engine, decoratorSeed(biomeKey, index)); + staging.computeIfAbsent(decorator.partOf(), part -> new ArrayList<>()).add(resolved); + } + + Map buckets = new EnumMap<>(DecorationPart.class); + staging.forEach((part, list) -> buckets.put(part, list.toArray(NO_DECORATORS))); + return buckets; + } + + private long decoratorSeed(String biomeKey, int index) { + return engine.getSeedManager().getDecorator() + (biomeKey.hashCode() * KEY_SEED_FACTOR) + (index * INDEX_SEED_FACTOR); + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java index b9407e23b..3762479c5 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -18,11 +18,8 @@ package art.arcane.iris.engine.decorator; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.platform.bukkit.BukkitBlockState; import art.arcane.iris.spi.IrisLogging; @@ -66,23 +63,18 @@ final class DecoratorCore { return baseSeed + SEED_OFFSET - (partOrdinal * PART_FACTOR); } - static long partSeed(long baseSeed, IrisDecorationPart part) { + static long partSeed(long baseSeed, DecorationPart part) { return partSeed(baseSeed, part.ordinal()); } - static IrisDecorator pickDecorator(IrisBiome biome, IrisDecorationPart part, RNG gRNG, - RNG colRng, IrisData data, double realX, double realZ) { - IrisDecorator[] bucket = biome.getDecoratorBucket(part); - if (bucket.length == 0) { - return null; - } - - IrisDecorator picked = null; + /** The decorator of {@code bucket} that decorates the column, drawing from {@code colRng} to choose between those whose chance noise passes. */ + static ResolvedDecorator pickDecorator(ResolvedDecorator[] bucket, RNG colRng, double realX, double realZ) { + ResolvedDecorator picked = null; int count = 0; - for (IrisDecorator d : bucket) { + for (ResolvedDecorator d : bucket) { try { - if (d.passesChanceGate(gRNG, realX, realZ, data)) { + if (d.passesChanceGate(realX, realZ)) { count++; if (count == 1 || colRng.nextInt(count) == 0) { picked = d; @@ -104,37 +96,32 @@ final class DecoratorCore { return half.equals("upper") || half.equals("lower") ? "lower" : "bottom"; } - static void placeSurfaceSingle(IrisDecorator decorator, + static void placeSurfaceSingle(ResolvedDecorator decorator, int x, int z, int realX, int height, int realZ, - Hunk data, RNG rng, IrisData irisData, + Hunk data, boolean underwater, boolean caveSkipFluid, EngineMantle mantle) { if (height < 0 || height >= data.getHeight()) { return; } PlatformBlockState bdx = data.get(x, height, z); - PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + PlatformBlockState bd = decorator.pickBlock(realX, realZ); if (!underwater && !canGoOn(bd, bdx) - && !decorator.isForcePlace() && decorator.getForceBlock() == null) { + && !decorator.isForcePlace() && decorator.forceBlock() == null) { return; } - if (decorator.getForceBlock() != null) { + if (decorator.forceBlock() != null) { if (caveSkipFluid && B.isFluid(bdx)) { return; } data.set(x, height, z, fixFacesForHunk( - decorator.getForceBlock().getBlockData(irisData), data, x, z, realX, height, realZ, mantle)); + decorator.forceBlock(), data, x, z, realX, height, realZ, mantle)); } - if (!decorator.isForcePlace()) { - if (decorator.getWhitelist() != null && !matchesPalette(decorator.getWhitelistArray(irisData), bdx)) { - return; - } - if (decorator.getBlacklist() != null && matchesPalette(decorator.getBlacklistArray(irisData), bdx)) { - return; - } + if (!decorator.isForcePlace() && decorator.rejectsSurface(bdx)) { + return; } String half = bd == null ? null : IrisProceduralBlocks.propertyValue(bd, "half"); @@ -164,20 +151,10 @@ final class DecoratorCore { } } - private static boolean matchesPalette(PlatformBlockState[] palette, PlatformBlockState surface) { - for (int i = 0; i < palette.length; i++) { - if (palette[i].equals(surface)) { - return true; - } - } - - return false; - } - - static void placeSingleAt(IrisDecorator decorator, int x, int z, + static void placeSingleAt(ResolvedDecorator decorator, int x, int z, int realX, int height, int realZ, Hunk data, - RNG rng, IrisData irisData, boolean applyFixFaces, EngineMantle mantle) { - PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + boolean applyFixFaces, EngineMantle mantle) { + PlatformBlockState bd = decorator.pickBlock(realX, realZ); if (bd == null) { return; } @@ -187,9 +164,9 @@ final class DecoratorCore { data.set(x, height, z, bd); } - static void placeStackUp(IrisDecorator decorator, int x, int z, int realX, int realZ, + static void placeStackUp(ResolvedDecorator decorator, int x, int z, int realX, int realZ, int height, int max, Hunk data, - RNG rng, IrisData irisData, PlaceOpts opts) { + PlaceOpts opts) { if (height < 0 || height >= data.getHeight()) { return; } @@ -199,7 +176,7 @@ final class DecoratorCore { effectiveMax = opts.fluidHeight; } - int stack = computeStack(decorator, rng, realX, realZ, irisData, effectiveMax); + int stack = computeStack(decorator, realX, realZ, effectiveMax); if (stack == 1) { int targetY = height + 1; @@ -213,7 +190,7 @@ final class DecoratorCore { return; } - PlatformBlockState block = decorator.pickBlockDataTop(rng, irisData, realX, realZ); + PlatformBlockState block = decorator.pickTopBlock(realX, realZ); if (block == null || (!opts.underwater && !canGoOn(block, data.get(x, height, z)))) { return; } @@ -228,9 +205,9 @@ final class DecoratorCore { for (int i = 0; i < stack; i++) { int h = height + i; double threshold = ((double) i) / (stack - 1); - PlatformBlockState bd = threshold >= decorator.getTopThreshold() - ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) - : decorator.pickBlockData(rng, irisData, realX, realZ); + PlatformBlockState bd = threshold >= decorator.topThreshold() + ? decorator.pickTopBlock(realX, realZ) + : decorator.pickBlock(realX, realZ); if (bd == null) { break; @@ -263,20 +240,20 @@ final class DecoratorCore { } } - static void placeStackDown(IrisDecorator decorator, int x, int z, int realX, int realZ, + static void placeStackDown(ResolvedDecorator decorator, int x, int z, int realX, int realZ, int height, int minHeight, Hunk data, - RNG rng, IrisData irisData, int max, PlaceOpts opts, EngineMantle mantle) { + int max, PlaceOpts opts, EngineMantle mantle) { if (height < 0 || height >= data.getHeight()) { return; } - int stack = computeStack(decorator, rng, realX, realZ, irisData, max); + int stack = computeStack(decorator, realX, realZ, max); if (stack == 1) { if (opts.caveSkipFluid && B.isFluid(data.get(x, height, z))) { return; } - PlatformBlockState block = decorator.pickBlockDataTop(rng, irisData, realX, realZ); + PlatformBlockState block = decorator.pickTopBlock(realX, realZ); if (block == null) { return; } @@ -292,9 +269,9 @@ final class DecoratorCore { } double threshold = ((double) i) / (double) (stack - 1); - PlatformBlockState bd = threshold >= decorator.getTopThreshold() - ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) - : decorator.pickBlockData(rng, irisData, realX, realZ); + PlatformBlockState bd = threshold >= decorator.topThreshold() + ? decorator.pickTopBlock(realX, realZ) + : decorator.pickBlock(realX, realZ); if (bd == null) { break; @@ -312,11 +289,10 @@ final class DecoratorCore { } } - static void placeFloatingSimple(IrisDecorator decorator, + static void placeFloatingSimple(ResolvedDecorator decorator, int xf, int zf, int realX, int realZ, - int height, int max, Hunk data, - RNG rng, IrisData irisData) { - PlatformBlockState bd = decorator.pickBlockData(rng, irisData, realX, realZ); + int height, int max, Hunk data) { + PlatformBlockState bd = decorator.pickBlock(realX, realZ); if (bd == null) { return; } @@ -345,13 +321,12 @@ final class DecoratorCore { } } - static int placeFloatingStacked(IrisDecorator decorator, + static int placeFloatingStacked(ResolvedDecorator decorator, int xf, int zf, int realX, int realZ, - int height, int max, Hunk data, - RNG rng, IrisData irisData) { - int stack = decorator.getHeight(rng, realX, realZ, irisData); + int height, int max, Hunk data) { + int stack = decorator.stackHeight(realX, realZ); if (decorator.isScaleStack()) { - stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); + stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack()); } else { stack = Math.min(max, stack); } @@ -363,9 +338,9 @@ final class DecoratorCore { break; } double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1); - PlatformBlockState bd = threshold >= decorator.getTopThreshold() - ? decorator.pickBlockDataTop(rng, irisData, realX, realZ) - : decorator.pickBlockData(rng, irisData, realX, realZ); + PlatformBlockState bd = threshold >= decorator.topThreshold() + ? decorator.pickTopBlock(realX, realZ) + : decorator.pickBlock(realX, realZ); if (bd == null) { break; } @@ -444,7 +419,7 @@ final class DecoratorCore { return ((BlockData) surface.nativeHandle()).isFaceSturdy(BlockFace.UP, BlockSupport.FULL); } - static boolean isValidShorelineSupport(IrisDecorator decorator, PlatformBlockState decorant, PlatformBlockState surface) { + static boolean isValidShorelineSupport(ResolvedDecorator decorator, PlatformBlockState decorant, PlatformBlockState surface) { return surface != null && B.isSolid(surface) && (decorator.isForcePlace() || canGoOn(decorant, surface)); @@ -466,11 +441,10 @@ final class DecoratorCore { && (!caveSkipFluid || !B.isFluid(lower) && !B.isFluid(upper)); } - private static int computeStack(IrisDecorator decorator, RNG rng, double realX, double realZ, - IrisData irisData, int max) { - int stack = decorator.getHeight(rng, realX, realZ, irisData); + private static int computeStack(ResolvedDecorator decorator, double realX, double realZ, int max) { + int stack = decorator.stackHeight(realX, realZ); if (decorator.isScaleStack()) { - stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.getAbsoluteMaxStack()); + stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack()); } else { stack = Math.min(max, stack); } diff --git a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java index d8d31447b..ebf564456 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java @@ -18,10 +18,9 @@ package art.arcane.iris.engine.decorator; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.spi.PlatformBlockState; @@ -33,12 +32,11 @@ import art.arcane.iris.spi.PlatformBlockState; */ public class FloatingDecorator { - public static int decorateColumn(Engine engine, IrisBiome target, IrisDecorationPart part, + public static int decorateColumn(Engine engine, IrisBiome target, DecorationPart part, int xf, int zf, int realX, int realZ, int height, int max, Hunk data, RNG rng, Runnable candidatesNullCallback) { - RNG gRNG = new RNG(DecoratorCore.partSeed(engine.getSeedManager().getDecorator(), part)); - IrisDecorator decorator = DecoratorCore.pickDecorator(target, part, gRNG, rng, engine.getData(), realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(BiomeDecorators.of(engine).decorators(target, part), rng, realX, realZ); if (decorator == null) { candidatesNullCallback.run(); @@ -46,10 +44,10 @@ public class FloatingDecorator { } if (!decorator.isStacking()) { - DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data, rng, engine.getData()); + DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data); return max > 1 ? 1 : 0; } - return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data, rng, engine.getData()); + return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java index 6efb73a6a..ccbb7e951 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java @@ -21,8 +21,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.documentation.BlockCoordinates; @@ -30,11 +29,8 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.spi.PlatformBlockState; public class IrisCeilingDecorator extends IrisEngineDecorator { - private final RNG partRNG; - public IrisCeilingDecorator(Engine engine) { - super(engine, "Ceiling", IrisDecorationPart.CEILING); - this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.CEILING)); + super(engine, "Ceiling", DecorationPart.CEILING); } @BlockCoordinates @@ -49,7 +45,7 @@ public class IrisCeilingDecorator extends IrisEngineDecorator { Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType); RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); if (decorator == null) { return; @@ -62,13 +58,13 @@ public class IrisCeilingDecorator extends IrisEngineDecorator { return; } } - DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, rng, getData(), true, getEngine().getMantle()); + DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, true, getEngine().getMantle()); return; } DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); opts.reset(); opts.caveSkipFluid = caveSkipFluid; - DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, rng, getData(), max, opts, getEngine().getMantle()); + DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, max, opts, getEngine().getMantle()); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java index 9dde144e7..5c07087a6 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java @@ -21,18 +21,20 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedComponent; import art.arcane.iris.engine.framework.EngineDecorator; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; import lombok.Getter; public abstract class IrisEngineDecorator extends EngineAssignedComponent implements EngineDecorator { @Getter - private final IrisDecorationPart part; + private final DecorationPart part; + protected final BiomeDecorators decorators; - public IrisEngineDecorator(Engine engine, String name, IrisDecorationPart part) { + public IrisEngineDecorator(Engine engine, String name, DecorationPart part) { super(engine, name + " Decorator"); this.part = part; + this.decorators = BiomeDecorators.of(engine); } @BlockCoordinates diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java index 6f4abf0b9..b183bece4 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java @@ -20,19 +20,15 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.spi.PlatformBlockState; public class IrisSeaFloorDecorator extends IrisEngineDecorator { - private final RNG partRNG; - public IrisSeaFloorDecorator(Engine engine) { - super(engine, "Sea Floor", IrisDecorationPart.SEA_FLOOR); - this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SEA_FLOOR)); + super(engine, "Sea Floor", DecorationPart.SEA_FLOOR); } @BlockCoordinates @@ -40,24 +36,23 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); if (decorator == null) { return; } if (!decorator.isStacking()) { - if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault() - && !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) { + if (decorator.slopeBlocks(() -> getComplex().getSlopeStream().get(realX, realZ))) { return; } if (height >= 0 && height < getEngine().getHeight()) { - data.set(x, height, z, decorator.getBlockData100(biome, rng, realX, height, realZ, getData())); + data.set(x, height, z, decorator.blockAt(biome, realX, height, realZ)); } return; } - int stack = decorator.getHeight(rng, realX, realZ, getData()); + int stack = decorator.stackHeight(realX, realZ); if (decorator.isScaleStack()) { stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); } else { @@ -65,7 +60,7 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { } if (stack == 1) { - data.set(x, height, z, decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData())); + data.set(x, height, z, decorator.topBlockAt(biome, realX, height, realZ)); return; } @@ -76,9 +71,9 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { continue; } double threshold = ((double) i) / (stack - 1); - data.set(x, h, z, threshold >= decorator.getTopThreshold() - ? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData()) - : decorator.getBlockData100(biome, rng, realX, h, realZ, getData())); + data.set(x, h, z, threshold >= decorator.topThreshold() + ? decorator.topBlockAt(biome, realX, h, realZ) + : decorator.blockAt(biome, realX, h, realZ)); } } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java index 62d470345..aaca4f012 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java @@ -20,19 +20,15 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.spi.PlatformBlockState; public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { - private final RNG partRNG; - public IrisSeaSurfaceDecorator(Engine engine) { - super(engine, "Sea Surface", IrisDecorationPart.SEA_SURFACE); - this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SEA_SURFACE)); + super(engine, "Sea Surface", DecorationPart.SEA_SURFACE); } @BlockCoordinates @@ -40,7 +36,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); if (decorator == null) { return; @@ -50,7 +46,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { int targetY = height + 1; if (height >= 0 && targetY < getEngine().getHeight() && DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { - PlatformBlockState block = decorator.getBlockData100(biome, rng, realX, height, realZ, getData()); + PlatformBlockState block = decorator.blockAt(biome, realX, height, realZ); if (block != null) { data.set(x, targetY, z, block); } @@ -58,7 +54,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { return; } - int stack = decorator.getHeight(rng, realX, realZ, getData()); + int stack = decorator.stackHeight(realX, realZ); if (decorator.isScaleStack()) { stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); } @@ -69,7 +65,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { return; } - PlatformBlockState block = decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData()); + PlatformBlockState block = decorator.topBlockAt(biome, realX, height, realZ); if (block != null) { data.set(x, targetY, z, block); } @@ -85,9 +81,9 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { break; } double threshold = ((double) i) / (stack - 1); - PlatformBlockState block = threshold >= decorator.getTopThreshold() - ? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData()) - : decorator.getBlockData100(biome, rng, realX, h, realZ, getData()); + PlatformBlockState block = threshold >= decorator.topThreshold() + ? decorator.topBlockAt(biome, realX, h, realZ) + : decorator.blockAt(biome, realX, h, realZ); if (block == null) { break; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java index d07750a71..39bbd4cc8 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java @@ -20,8 +20,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.volmlib.util.documentation.BlockCoordinates; @@ -29,11 +28,8 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.spi.PlatformBlockState; public class IrisShoreLineDecorator extends IrisEngineDecorator { - private final RNG partRNG; - public IrisShoreLineDecorator(Engine engine) { - super(engine, "Shore Line", IrisDecorationPart.SHORE_LINE); - this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.SHORE_LINE)); + super(engine, "Shore Line", DecorationPart.SHORE_LINE); } @BlockCoordinates @@ -54,14 +50,13 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { } RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); if (decorator == null) { return; } - if (!decorator.isForcePlace() && !decorator.getSlopeCondition().isDefault() - && !decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ))) { + if (decorator.slopeBlocks(() -> getComplex().getSlopeStream().get(realX, realZ))) { return; } @@ -76,14 +71,14 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { return; } - PlatformBlockState block = decorator.getBlockData100(biome, rng, realX, height, realZ, getData()); + PlatformBlockState block = decorator.blockAt(biome, realX, height, realZ); if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) { data.set(x, targetY, z, block); } return; } - int stack = decorator.getHeight(rng, realX, realZ, getData()); + int stack = decorator.stackHeight(realX, realZ); if (decorator.isScaleStack()) { stack = (int) Math.ceil((double) (max - height) * ((double) stack / 100)); } else { @@ -96,7 +91,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { return; } - PlatformBlockState block = decorator.getBlockDataForTop(biome, rng, realX, height, realZ, getData()); + PlatformBlockState block = decorator.topBlockAt(biome, realX, height, realZ); if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) { data.set(x, targetY, z, block); } @@ -111,9 +106,9 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { break; } double threshold = ((double) i) / (stack - 1); - PlatformBlockState block = threshold >= decorator.getTopThreshold() - ? decorator.getBlockDataForTop(biome, rng, realX, h, realZ, getData()) - : decorator.getBlockData100(biome, rng, realX, h, realZ, getData()); + PlatformBlockState block = threshold >= decorator.topThreshold() + ? decorator.topBlockAt(biome, realX, h, realZ) + : decorator.blockAt(biome, realX, h, realZ); if (block == null) { break; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java index 0b18b6a84..fde5ae2b5 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java @@ -21,31 +21,23 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.spi.PlatformBlockState; public class IrisSurfaceDecorator extends IrisEngineDecorator { - private final RNG partRNG; - public IrisSurfaceDecorator(Engine engine) { - super(engine, "Surface", IrisDecorationPart.NONE); - this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.NONE)); + super(engine, "Surface", DecorationPart.NONE); } protected IrisSurfaceDecorator(Engine engine, String name) { - super(engine, name, IrisDecorationPart.NONE); - this.partRNG = new RNG(DecoratorCore.partSeed(getSeed(), IrisDecorationPart.NONE)); + super(engine, name, DecorationPart.NONE); } - protected boolean isSlopeValid(IrisDecorator decorator, int realX, int realZ) { - if (decorator.isForcePlace() || decorator.getSlopeCondition().isDefault()) { - return true; - } - return decorator.getSlopeCondition().isValid(getComplex().getSlopeStream().get(realX, realZ)); + protected boolean isSlopeValid(ResolvedDecorator decorator, int realX, int realZ) { + return !decorator.slopeBlocks(() -> getComplex().getSlopeStream().get(realX, realZ)); } @BlockCoordinates @@ -66,7 +58,7 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { boolean underwater = isUnderwater(inferredType, height, fluidHeight); boolean caveSkipFluid = skipsFluid(inferredType); RNG rng = getRNG(realX, realZ); - IrisDecorator decorator = DecoratorCore.pickDecorator(biome, getPart(), partRNG, rng, getData(), realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); if (decorator == null || !isSlopeValid(decorator, realX, realZ)) { return; @@ -78,12 +70,12 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { opts.underwater = underwater; opts.fluidHeight = fluidHeight; opts.caveSkipFluid = caveSkipFluid; - DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, rng, getData(), opts); + DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, opts); return; } DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ, - data, rng, getData(), underwater, caveSkipFluid, getEngine().getMantle()); + data, underwater, caveSkipFluid, getEngine().getMantle()); } static boolean isUnderwater(InferredType inferredType, int height, int fluidHeight) { diff --git a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java new file mode 100644 index 000000000..b6c529176 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -0,0 +1,269 @@ +/* + * 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.decorator; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.builtin.decorant.Decorator; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.DoubleSupplier; + +/** + * One {@link Decorator} made ready for one world: its palettes resolved to the platform's blocks, and the noise that + * decides where it places, which block of the palette it picks and how tall it stacks, built when first asked for. What + * the decorator describes stays in the settings; everything that needs the platform, the pack or the world seed is here. + * + *

The noise seeds are the decorator's own seed plus the same offsets Iris's decorator always used, so a decorator + * noise is a pure function of its seed. + */ +final class ResolvedDecorator { + private final Decorator settings; + private final long seed; + private final NoiseFactory noise; + private final List blocks; + private final List topBlocks; + private final PlatformBlockState[] blockArray; + private final PlatformBlockState[] topBlockArray; + private final PlatformBlockState forceBlock; + private final PlatformBlockState[] whitelist; + private final PlatformBlockState[] blacklist; + private final AtomicCache chanceNoise = new AtomicCache<>(); + private final AtomicCache varianceNoise = new AtomicCache<>(); + private final AtomicCache heightNoise = new AtomicCache<>(); + + /** + * @param blocks the palette as the platform's blocks, each repeated by its weight + * @param topBlocks the top palette the same way + * @param forceBlock the block it forces onto the surface, or null + * @param whitelist the blocks it may only be placed onto; ignored unless the decorator has a whitelist + * @param blacklist the blocks it is never placed onto; ignored unless the decorator has a blacklist + */ + ResolvedDecorator(Decorator settings, long seed, NoiseFactory noise, List blocks, List topBlocks, + PlatformBlockState forceBlock, List whitelist, List blacklist) { + this.settings = settings; + this.seed = seed; + this.noise = noise; + this.blocks = List.copyOf(blocks); + this.topBlocks = List.copyOf(topBlocks); + this.blockArray = blocks.toArray(new PlatformBlockState[0]); + this.topBlockArray = topBlocks.toArray(new PlatformBlockState[0]); + this.forceBlock = forceBlock; + this.whitelist = whitelist.toArray(new PlatformBlockState[0]); + this.blacklist = blacklist.toArray(new PlatformBlockState[0]); + } + + /** {@code settings} ready for {@code engine}: its blocks resolved through the pack, its noise seeded from {@code seed}. */ + static ResolvedDecorator of(Decorator settings, Engine engine, long seed) { + var resources = engine.getData().getPackResources(); + BlockRegistry registry = resources.blocks(); + PlatformBlockState forced = settings.forceBlock().map(spec -> platformState(registry, spec)).orElse(null); + return new ResolvedDecorator(settings, seed, resources.noise(), weighted(registry, settings.palette()), + weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist())); + } + + private static PlatformBlockState platformState(BlockRegistry registry, BlockSpec spec) { + return B.getState(registry.resolve(spec).key()); + } + + private static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : palette) { + PlatformBlockState state = platformState(registry, spec); + if (state == null) { + continue; + } + for (int n = 0; n < spec.weight(); n++) { + weighted.add(state); + } + } + return weighted; + } + + private static List each(BlockRegistry registry, List palette) { + return palette.stream().map(spec -> platformState(registry, spec)).toList(); + } + + Decorator settings() { + return settings; + } + + DecorationPart part() { + return settings.partOf(); + } + + boolean isStacking() { + return settings.isStacking(); + } + + boolean isForcePlace() { + return settings.forcePlace(); + } + + boolean isScaleStack() { + return settings.scaleStack(); + } + + int absoluteMaxStack() { + return settings.absoluteMaxStack(); + } + + double topThreshold() { + return settings.topThreshold(); + } + + /** The block it forces onto the surface instead of the one found there, or null. */ + PlatformBlockState forceBlock() { + return forceBlock; + } + + /** Whether the terrain's slope keeps the decorator off; the slope is only worked out when the decorator limits it. */ + boolean slopeBlocks(DoubleSupplier slope) { + if (settings.forcePlace() || settings.slopeCondition().isDefault()) { + return false; + } + return !settings.slopeCondition().isValid(slope.getAsDouble()); + } + + /** Whether the white and black lists keep the decorator off {@code surface}. */ + boolean rejectsSurface(PlatformBlockState surface) { + if (settings.hasWhitelist() && !matches(whitelist, surface)) { + return true; + } + return settings.hasBlacklist() && matches(blacklist, surface); + } + + private static boolean matches(PlatformBlockState[] palette, PlatformBlockState surface) { + for (PlatformBlockState state : palette) { + if (state.equals(surface)) { + return true; + } + } + return false; + } + + /** How many blocks the decorator stacks at the column: the minimum, or a height between the limits drawn from its height noise. */ + int stackHeight(double x, double z) { + if (settings.stackMin() == settings.stackMax()) { + return settings.stackMin(); + } + + double zoom = settings.heightVariance().zoom(); + return fit(settings.stackMin(), settings.stackMax(), heightNoise().sample(x / zoom, z / zoom)); + } + + /** Whether the chance noise lets the decorator place at the column. */ + boolean passesChanceGate(double x, double z) { + if (blocks.isEmpty()) { + return false; + } + double zoom = settings.style().zoom(); + return chanceNoise().sample(x / zoom, z / zoom) <= settings.chance(); + } + + /** The block of the palette at the position, for decorations that fill a column block by block; null when the palette has no block. */ + PlatformBlockState blockAt(IrisBiome biome, double x, double y, double z) { + if (blocks.isEmpty()) { + IrisLogging.warnOnce("decorator-empty:" + biome.getName(), "Empty Block Data for " + biome.getName()); + return null; + } + + if (blocks.size() == 1) { + return blocks.get(0); + } + + return blocks.get(fit(0, blocks.size() - 1, varianceNoise().sample(z, y, x))); // X and Z are switched + } + + /** The top palette's block at the position, or the palette's when there is no top palette; null where the chance noise declines. */ + PlatformBlockState topBlockAt(IrisBiome biome, double x, double y, double z) { + if (topBlocks.isEmpty()) { + return blockAt(biome, x, y, z); + } + + double zoom = settings.style().zoom(); + if (!(chanceNoise().sample(x / zoom, z / zoom) <= settings.chance())) { + return null; + } + + if (blocks.size() == 1) { + return topBlocks.get(0); + } + + return topBlocks.get(fit(0, topBlocks.size() - 1, varianceNoise().sample(z, y, x))); + } + + /** The palette's block for the column, or null when the palette has no block. */ + PlatformBlockState pickBlock(double x, double z) { + return pick(blockArray, x, z); + } + + /** The top palette's block for the column; the palette's when there is no top palette. */ + PlatformBlockState pickTopBlock(double x, double z) { + if (topBlockArray.length == 0) { + return pickBlock(x, z); + } + return pick(topBlockArray, x, z); + } + + private PlatformBlockState pick(PlatformBlockState[] palette, double x, double z) { + if (palette.length == 0) { + return null; + } + if (palette.length == 1) { + return palette[0]; + } + return palette[Math.abs(fit(0, palette.length - 1, varianceNoise().sample(z, x)))]; + } + + /** Builds the noise now instead of when first asked for. */ + void warm() { + heightNoise(); + chanceNoise(); + varianceNoise(); + } + + private NoiseSampler heightNoise() { + return heightNoise.aquireOrThrow(() -> noise.sampler(settings.heightVariance(), + seed + blocks.size() + settings.stackMax() + settings.stackMin())); + } + + private NoiseSampler chanceNoise() { + return chanceNoise.aquireOrThrow(() -> noise.sampler(settings.style(), seed + blocks.size())); + } + + private NoiseSampler varianceNoise() { + return varianceNoise.aquireOrThrow(() -> noise.sampler(settings.variance(), seed + blocks.size())); + } + + /** The whole number between {@code min} and {@code max} that {@code fraction}, from 0 to 1, is the way along. */ + private static int fit(int min, int max, double fraction) { + return (int) Math.round(min + (fraction * (max - min))); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 6e7b4fd5e..fcb5c66b3 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -26,6 +26,7 @@ import art.arcane.iris.engine.framework.Engine; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLifecycle; import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; import com.volmit.stage.MantleStageContext; @@ -37,10 +38,11 @@ import java.util.Set; /** * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work - * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells + * done by {@link ObjectPlacing}, one per engine runtime, with the noise of its placements and the variants of its procedural + * objects built ahead of generation ({@link #warmUp}). Its reach is the pack's largest object placement. It tells * Iris which objects a chunk would get ({@link ObjectsAt}), for the object search and studio tools. */ -public final class ObjectModule implements IrisModule { +public final class ObjectModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @Override @@ -56,6 +58,12 @@ public final class ObjectModule implements IrisModule { @Override public void register(FeatureRegistry registry) { registry.registerService(ObjectsAt.class, ObjectModule::objectsAt); + registry.registerLifecycle(this); + } + + @Override + public void warmUp(PackWorld world) { + new ObjectWarmUp(IrisPackWorld.of(world).engine()).warm(); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java new file mode 100644 index 000000000..71880284c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -0,0 +1,91 @@ +/* + * 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.engine.framework.Engine; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; +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 art.arcane.volmlib.util.math.RNG; + +import java.util.Comparator; + +/** + * Builds what object placing would build on first use, for every object placement and procedural object the world's + * biomes and regions declare: the placement's surface warp and density noise, and a procedural object's variants. None + * of it depends on the random it is warmed with; the warp is seeded from the world, the density noise is cached per seed + * and the variants are baked whatever picks one. + */ +final class ObjectWarmUp { + private static final long ROOT_SEED_SALT = 7777L; + private static final int PROBE_COORDINATE = 0; + + private final Engine engine; + private final RNG root; + private int warmed; + + ObjectWarmUp(Engine engine) { + this.engine = engine; + this.root = new RNG(engine.getSeedManager().getComponent() + ROOT_SEED_SALT); + } + + void warm() { + KList biomes = engine.getAllBiomes(); + biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); + for (IrisBiome biome : biomes) { + warmPlacements(biome.getObjects()); + warmProcedural(biome.getProceduralObjects()); + } + + KList regions = engine.getDimension().getAllRegions(engine); + regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); + for (IrisRegion region : regions) { + warmPlacements(region.getObjects()); + warmProcedural(region.getProceduralObjects()); + } + } + + private void warmPlacements(KList placements) { + if (placements == null) { + return; + } + for (IrisObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + RNG rng = root.nextParallelRNG(warmed++); + placement.getSurfaceWarp(rng, engine.getData(), engine); + placement.getDensity(rng, PROBE_COORDINATE, PROBE_COORDINATE, engine.getData()); + } + } + + private void warmProcedural(IrisProceduralObjects procedural) { + if (procedural == null) { + return; + } + for (IrisProceduralPlacement placement : procedural.getAllPlacements()) { + if (placement != null) { + placement.getVariantObject(engine.getData(), root.nextParallelRNG(warmed++)); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 67b9ac805..15242fee5 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -19,13 +19,13 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.decorator.IrisCeilingDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.common.data.B; @@ -65,12 +65,14 @@ public class CaveApplying { private final RNG rng; private final PlatformBlockState AIR = B.getState("CAVE_AIR"); private final PlatformBlockState LAVA = B.getState("LAVA"); + private final BiomeDecorators decorators; private final IrisSurfaceDecorator surfaceDecorator; private final IrisCeilingDecorator ceilingDecorator; public CaveApplying(Engine engine) { this.engine = engine; rng = new RNG(engine.getSeedManager().getCarve()); + decorators = BiomeDecorators.of(engine); surfaceDecorator = new IrisSurfaceDecorator(engine); ceilingDecorator = new IrisCeilingDecorator(engine); } @@ -640,17 +642,11 @@ public class CaveApplying { } } - IrisDecorator[] surfaceDecorators = floorBiome == null - ? new IrisDecorator[0] - : floorBiome.getDecoratorBucket(IrisDecorationPart.NONE); - if (surfaceDecorators.length > 0 && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { + if (floorBiome != null && decorators.hasDecorators(floorBiome, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { surfaceDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); } - IrisDecorator[] ceilingDecorators = ceilingBiome == null - ? new IrisDecorator[0] - : ceilingBiome.getDecoratorBucket(IrisDecorationPart.CEILING); - if (ceilingDecorators.length > 0 && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { + if (ceilingBiome != null && decorators.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { ceilingDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 4a97bcd25..5abfef7f5 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -31,7 +31,7 @@ import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySamp import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; import art.arcane.iris.engine.object.placement.IrisSlopeClip; @@ -331,7 +331,7 @@ public class FloatingIslands { if (above == null || above.isAir()) { try { RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(baseSeed, wx, wz)); - FloatingDecorator.decorateColumn(engine, target, IrisDecorationPart.NONE, xf, zf, wx, wz, topY, max, output, colRng, NOOP_DECORATION_MISS); + FloatingDecorator.decorateColumn(engine, target, DecorationPart.NONE, xf, zf, wx, wz, topY, max, output, colRng, NOOP_DECORATION_MISS); } catch (Throwable e) { IrisLogging.reportError(e); } diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java deleted file mode 100644 index 8c3e6123c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java +++ /dev/null @@ -1,356 +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.decoration; - -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.placement.IrisSlopeClip; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -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.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Snippet("decorator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A biome decorator is used for placing flowers, grass, cacti and so on") -@Data -public class IrisDecorator { - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache varianceGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache> blockDataTops = new AtomicCache<>(); - private final transient AtomicCache blockDataArray = new AtomicCache<>(); - private final transient AtomicCache blockDataTopsArray = new AtomicCache<>(); - private final transient AtomicCache whitelistArray = new AtomicCache<>(); - private final transient AtomicCache blacklistArray = new AtomicCache<>(); - @Desc("The varience dispersion is used when multiple blocks are put in the palette. Scatter scrambles them, Wispy shows streak-looking varience") - private IrisGeneratorStyle variance = NoiseStyle.STATIC.style(); - @Desc("Forcefully place this decorant anywhere it is supposed to go even if it should not go on a specific surface block. For example, you could force tallgrass to place on top of stone by using this.") - private boolean forcePlace = false; - @Desc("Forced the surface block of this decorant to be the specified block. Assumes forcePlace.") - private IrisBlockData forceBlock; - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("When set, the decorator can only place onto any of these blocks.") - private KList whitelist; - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("When set, the decorator will never place onto any of these blocks.") - private KList blacklist; - @Desc("The slope at which this decorator can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the decorator placement.") - private IrisSlopeClip slopeCondition = new IrisSlopeClip(); - @DependsOn({"scaleStack", "stackMin", "stackMax"}) - @Desc("If stackMax is set to true, use this to limit its max height for large caverns") - private int absoluteMaxStack = 30; - @Desc("Dispersion is used to pick places to spawn. Scatter randomly places them (vanilla) or Wispy for a streak like patch system.") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @DependsOn({"stackMin", "stackMax"}) - @Desc("If this decorator has a height more than 1 this changes how it picks the height between your maxes. Scatter = random, Wispy = wavy heights") - private IrisGeneratorStyle heightVariance = NoiseStyle.STATIC.style(); - @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") - private IrisDecorationPart partOf = IrisDecorationPart.NONE; - @DependsOn({"stackMin", "stackMax"}) - @MinNumber(1) - @MaxNumber(2032) - @Desc("The minimum repeat stack height (setting to 3 would stack 3 of on top of each other") - private int stackMin = 1; - @DependsOn({"stackMin", "stackMax"}) - @MinNumber(1) - @MaxNumber(2032) - @Desc("The maximum repeat stack height") - private int stackMax = 1; - @DependsOn({"stackMin", "stackMax"}) - @Desc(""" - Changes stackMin and stackMin from being absolute block heights and instead uses them as a percentage to scale the stack based on the cave height - - Within a cave, setting them stackMin/max to 50 would make the stack 50% of the cave height""") - private boolean scaleStack = false; - @Required - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") - private double chance = 0.1; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks to pick from when this decorator needs to place.") - private KList palette = new KList().qadd(new IrisBlockData("grass")); - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The palette of blocks used at the very top of a 'stackMax' of higher than 1. For example, bamboo tops.") - private KList topPalette = new KList<>(); - @DependsOn("topPalette") - @MinNumber(0.01) - @MaxNumber(1.0) - @Desc("When the stack passes the top threshold, the top palette will start being used instead of the normal palette.") - private double topThreshold = 1.0; - - public int getHeight(RNG rng, double x, double z, IrisData data) { - if (stackMin == stackMax) { - return stackMin; - } - - return getHeightGenerator(rng, data) - .fit(stackMin, stackMax, - x / heightVariance.getZoom(), - z / heightVariance.getZoom()); - } - - public CNG getHeightGenerator(RNG rng, IrisData data) { - CNG cached = heightGenerator.getIfPresent(); - - if (cached != null) { - return cached; - } - - return heightGenerator.aquire(() -> - heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin), data)); - } - - public CNG getGenerator(RNG rng, IrisData data) { - CNG cached = layerGenerator.getIfPresent(); - - if (cached != null) { - return cached; - } - - return layerGenerator.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()), data)); - } - - public CNG getVarianceGenerator(RNG rng, IrisData data) { - CNG cached = varianceGenerator.getIfPresent(); - - if (cached != null) { - return cached; - } - - return varianceGenerator.aquire(() -> - variance.create( - rng.nextParallelRNG(getBlockData(data).size()), data) - .scale(1D / variance.getZoom())); - } - - public KList add(String b) { - palette.add(new IrisBlockData(b)); - return palette; - } - - public boolean passesChanceGate(RNG rng, double x, double z, IrisData data) { - if (getBlockData(data).isEmpty()) { - return false; - } - double xx = x / style.getZoom(); - double zz = z / style.getZoom(); - return getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance; - } - - public PlatformBlockState getBlockData(IrisBiome b, RNG rng, double x, double z, IrisData data) { - if (!passesChanceGate(rng, x, z, data)) { - return null; - } - if (getBlockData(data).size() == 1) { - return getBlockData(data).get(0); - } - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x); - } - - public PlatformBlockState getBlockData100(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { - if (getBlockData(data).isEmpty()) { - IrisLogging.warnOnce("decorator-empty:" + b.getName(), "Empty Block Data for " + b.getName()); - return null; - } - - if (getBlockData(data).size() == 1) { - return getBlockData(data).get(0); - } - - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, y, x); //X and Z must be switched - } - - public PlatformBlockState getBlockDataForTop(IrisBiome b, RNG rng, double x, double y, double z, IrisData data) { - if (getBlockDataTops(data).isEmpty()) { - return getBlockData100(b, rng, x, y, z, data); - } - - double xx = x / style.getZoom(); - double zz = z / style.getZoom(); - - if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { //Exclude y from here - if (getBlockData(data).size() == 1) { - return getBlockDataTops(data).get(0); - } - - return getVarianceGenerator(rng, data).fit(getBlockDataTops(data), z, y, x); //X and Z must be switched - } - - return null; - } - - public KList getBlockData(IrisData data) { - KList cached = blockData.getIfPresent(); - - if (cached != null) { - return cached; - } - - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for (IrisBlockData i : palette) { - PlatformBlockState bx = i.getBlockData(data); - if (bx != null) { - for (int n = 0; n < i.getWeight(); n++) { - blockData.add(bx); - } - } - } - - return blockData; - }); - } - - public KList getBlockDataTops(IrisData data) { - KList cached = blockDataTops.getIfPresent(); - - if (cached != null) { - return cached; - } - - return blockDataTops.aquire(() -> - { - KList blockDataTops = new KList<>(); - for (IrisBlockData i : topPalette) { - PlatformBlockState bx = i.getBlockData(data); - if (bx != null) { - for (int n = 0; n < i.getWeight(); n++) { - blockDataTops.add(bx); - } - } - } - - return blockDataTops; - }); - } - - public PlatformBlockState[] getBlockDataArray(IrisData data) { - PlatformBlockState[] cached = blockDataArray.getIfPresent(); - - if (cached != null) { - return cached; - } - - return blockDataArray.aquire(() -> { - KList list = getBlockData(data); - return list.toArray(new PlatformBlockState[0]); - }); - } - - public PlatformBlockState[] getBlockDataTopsArray(IrisData data) { - PlatformBlockState[] cached = blockDataTopsArray.getIfPresent(); - - if (cached != null) { - return cached; - } - - return blockDataTopsArray.aquire(() -> { - KList list = getBlockDataTops(data); - return list.toArray(new PlatformBlockState[0]); - }); - } - - /** - * The resolved whitelist palette. Empty when no whitelist is configured; callers must still gate on - * {@link #getWhitelist()} being non null, because an explicitly empty whitelist blocks all placement. - */ - public PlatformBlockState[] getWhitelistArray(IrisData data) { - PlatformBlockState[] cached = whitelistArray.getIfPresent(); - - if (cached != null) { - return cached; - } - - return whitelistArray.aquire(() -> resolvePalette(whitelist, data)); - } - - public PlatformBlockState[] getBlacklistArray(IrisData data) { - PlatformBlockState[] cached = blacklistArray.getIfPresent(); - - if (cached != null) { - return cached; - } - - return blacklistArray.aquire(() -> resolvePalette(blacklist, data)); - } - - private static PlatformBlockState[] resolvePalette(KList list, IrisData data) { - if (list == null) { - return new PlatformBlockState[0]; - } - - PlatformBlockState[] resolved = new PlatformBlockState[list.size()]; - - for (int i = 0; i < resolved.length; i++) { - resolved[i] = list.get(i).getBlockData(data); - } - - return resolved; - } - - public PlatformBlockState pickBlockData(RNG rng, IrisData data, double x, double z) { - PlatformBlockState[] arr = getBlockDataArray(data); - if (arr.length == 0) { - return null; - } - if (arr.length == 1) { - return arr[0]; - } - return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))]; - } - - public PlatformBlockState pickBlockDataTop(RNG rng, IrisData data, double x, double z) { - PlatformBlockState[] arr = getBlockDataTopsArray(data); - if (arr.length == 0) { - return pickBlockData(rng, data, x, z); - } - if (arr.length == 1) { - return arr[0]; - } - return arr[Math.abs((int) getVarianceGenerator(rng, data).fit(0, arr.length - 1, z, x))]; - } - - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean isStacking() { - return getStackMax() > 1; - } -} 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 index 10f40aafc..471c20236 100644 --- 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 @@ -18,8 +18,6 @@ package art.arcane.iris.engine.object.world.biome; -import art.arcane.iris.engine.object.decoration.IrisDecorationPart; -import art.arcane.iris.engine.object.decoration.IrisDecorator; import art.arcane.iris.engine.object.entity.IrisEffect; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.loot.IrisBlockDrops; @@ -118,12 +116,10 @@ public class IrisBiome extends IrisRegistrant implements IRare { private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); private final transient AtomicCache undergroundOreBoundsCache = new AtomicCache<>(); - private final transient AtomicCache> decoratorBuckets = 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<>(); - private static final IrisDecorator[] EMPTY_BUCKET = new IrisDecorator[0]; @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.") @@ -205,9 +201,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @ArrayType(type = IrisBiomePaletteLayer.class) @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") private KList seaLayers = new KList<>(); - @ArrayType(min = 1, type = IrisDecorator.class) - @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") - private KList decorators = new KList<>(); @ArrayType(min = 1, type = IrisObjectPlacement.class) @Desc("Objects define what schematics (iob files) iris will place in this biome") private KList objects = new KList<>(); @@ -635,23 +628,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { return "biomes"; } - public IrisDecorator[] getDecoratorBucket(IrisDecorationPart part) { - return decoratorBuckets.aquire(this::buildDecoratorBuckets).getOrDefault(part, EMPTY_BUCKET); - } - - private EnumMap buildDecoratorBuckets() { - EnumMap> staging = new EnumMap<>(IrisDecorationPart.class); - for (IrisDecorator d : decorators) { - staging.computeIfAbsent(d.getPartOf(), k -> new KList<>()).add(d); - } - EnumMap result = new EnumMap<>(IrisDecorationPart.class); - for (IrisDecorationPart part : IrisDecorationPart.values()) { - KList list = staging.get(part); - result.put(part, list == null ? EMPTY_BUCKET : list.toArray(EMPTY_BUCKET)); - } - return result; - } - public String getTypeName() { return "Biome"; } 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 index ec1bdcb93..44e9ce0fe 100644 --- 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 @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.world.biome; -import art.arcane.iris.engine.object.decoration.IrisDecorator; +import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; @@ -76,13 +76,8 @@ final class IrisBiomeColorRenderer { } case DECORATOR_LOAD -> { return biome.getCacheColorDecoratorLoad().aquire(() -> { - double density = 0; - - for (IrisDecorator i : biome.getDecorators()) { - density += i.getChance() * Math.min(1, i.getStackMax()) * 256; - } - - return Color.getHSBColor(0.41f, (float) (density / engine.getMaxBiomeDecoratorDensity()), 1f); + BiomeDecorators decorators = BiomeDecorators.of(engine); + return Color.getHSBColor(0.41f, (float) (decorators.colourLoad(biome) / decorators.busiestBiomeLoad()), 1f); }); } case LAYER_LOAD -> { From 9401e8aa78070b44f30e414572c1bf48c41aac6c Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:01:32 +0200 Subject: [PATCH 031/139] Placement settings as module-owned IrisApi types: object limit, slope clip, stilt, vacuum, block replace, axis rotation clamp --- .../iris/builtin/blocks/ObjectReplace.java | 69 ++++++++++++++ .../prepare/AxisRotationClamp.java} | 94 +++++++++++++------ .../prepare/SlopeClip.java} | 47 ++++++---- .../iris/builtin/stilt/StiltSettings.java | 90 ++++++++++++++++++ .../vacuum/VacuumSettings.java} | 62 +++++++++--- .../validate/ObjectLimit.java} | 41 ++++---- .../mantle/components/ObjectPlacing.java | 14 +-- .../iris/engine/modifier/FloatingIslands.java | 4 +- .../engine/modifier/SurfaceSmoothing.java | 4 +- .../object/decoration/IrisDecorator.java | 4 +- .../iris/engine/object/mod/IrisMod.java | 6 +- .../engine/object/placement/BlocksModule.java | 7 ++ .../object/placement/IrisObjectPlacement.java | 17 ++-- .../object/placement/IrisObjectReplace.java | 84 ----------------- .../object/placement/IrisObjectVacuum.java | 20 ++-- .../object/placement/IrisStiltSettings.java | 47 ---------- .../engine/object/placement/ObjectEdits.java | 17 ++-- .../object/placement/ObjectSpinKernel.java | 10 +- .../object/placement/PrepareModule.java | 16 +++- .../object/placement/ResolvedReplace.java | 94 +++++++++++++++++++ .../object/placement/ResolvedReplaces.java | 54 +++++++++++ .../engine/object/placement/StiltModule.java | 35 +++++-- .../engine/object/placement/VacuumModule.java | 11 ++- .../object/placement/ValidateModule.java | 7 ++ .../object/prefab/IrisObjectRotation.java | 74 +++++---------- .../object/procedural/coral/IrisCoral.java | 12 +-- .../procedural/crystal/IrisCrystal.java | 12 +-- .../procedural/formation/IrisFormation.java | 12 +-- .../object/procedural/fungi/IrisFungus.java | 12 +-- .../object/procedural/ruin/IrisRuin.java | 12 +-- .../procedural/tree/IrisProceduralTree.java | 12 +-- .../object/structure/IrisStructure.java | 6 +- .../terrain/IrisBiomeLayerGenerator.java | 6 +- .../object/terrain/IrisBiomePaletteLayer.java | 4 +- 34 files changed, 654 insertions(+), 362 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java rename src/main/java/art/arcane/iris/{engine/object/prefab/IrisAxisRotationClamp.java => builtin/prepare/AxisRotationClamp.java} (50%) rename src/main/java/art/arcane/iris/{engine/object/placement/IrisSlopeClip.java => builtin/prepare/SlopeClip.java} (54%) create mode 100644 src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java rename src/main/java/art/arcane/iris/{engine/object/placement/IrisVacuumSettings.java => builtin/vacuum/VacuumSettings.java} (52%) rename src/main/java/art/arcane/iris/{engine/object/placement/IrisObjectLimit.java => builtin/validate/ObjectLimit.java} (56%) delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java new file mode 100644 index 000000000..091b70635 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java @@ -0,0 +1,69 @@ +/* + * 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.builtin.blocks; + +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** One find-and-replace of an object placement's blocks, an entry of the placement's {@code edit}. */ +@Snippet("object-block-replacer") +@Desc("Find and replace object materials") +public final class ObjectReplace { + @MinItems(1) + @Required + @Desc("Find this block") + private List find = List.of(); + @Required + @Desc("Replace it with this block palette") + private PaletteSpec replace = PaletteSpec.of(List.of(BlockSpec.of("stone"))); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @MinNumber(0) + @MaxNumber(1) + @Desc("Modifies the chance the block is replaced") + private float chance = 1; + + public ObjectReplace() { + } + + public List find() { + return find == null ? List.of() : Collections.unmodifiableList(find); + } + + public PaletteSpec replace() { + return replace == null ? PaletteSpec.of(List.of(BlockSpec.of("stone"))) : replace; + } + + public boolean exact() { + return exact; + } + + public float chance() { + return chance; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java b/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java similarity index 50% rename from src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java rename to src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java index dc55cdd01..52e7040aa 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisAxisRotationClamp.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,57 +16,78 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.prefab; +package art.arcane.iris.builtin.prepare; -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.volmlib.util.math.M; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import java.util.Objects; + +/** One axis of an object rotation, with the angles it may turn by and the steps between them. */ @Snippet("axis-rotation") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor @Desc("Represents a rotation axis with intervals and maxes. The x and z axis values are defaulted to disabled. The Y axis defaults to on, rotating by 90 degree increments.") -@Data -public class IrisAxisRotationClamp { +public final class AxisRotationClamp { + private static final double FULL_TURN_DEGREES = 360D; + @Desc("Should this axis be rotated at all?") private boolean enabled = false; private transient boolean forceLock = false; @Required - @DependsOn({"max"}) @MinNumber(-360) @MaxNumber(360) @Desc("The minimum angle (from) or set this and max to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") private double min = 0; @Required - @DependsOn({"min"}) @MinNumber(-360) @MaxNumber(360) @Desc("The maximum angle (to) or set this and min to zero for any angle degrees. Set both to the same non-zero value to force it to that angle only") private double max = 0; @Required - @DependsOn({"min", "max"}) @MinNumber(0) @MaxNumber(360) @Desc("Iris spins the axis but not freely. For example an interval of 90 would mean 4 possible angles (right angles) degrees. \nSetting this to 0 means totally free rotation.\n\nNote that a lot of structures can have issues with non 90 degree intervals because the minecraft block resolution is so low.") private double interval = 0; - public void minMax(double fd) { - min = fd; - max = fd; - forceLock = true; + public AxisRotationClamp() { + } + + /** An axis turned as {@code enabled} says, by angles from {@code min} to {@code max} in steps of {@code interval}. */ + public static AxisRotationClamp of(boolean enabled, boolean forceLock, double min, double max, double interval) { + AxisRotationClamp clamp = new AxisRotationClamp(); + clamp.enabled = enabled; + clamp.forceLock = forceLock; + clamp.min = min; + clamp.max = max; + clamp.interval = interval; + return clamp; + } + + /** An axis that turns to exactly {@code angle}, in steps of {@code interval}, whatever its min and max say. */ + public static AxisRotationClamp locked(boolean enabled, double angle, double interval) { + return of(enabled, true, angle, angle, interval); + } + + public boolean enabled() { + return enabled; + } + + public double min() { + return min; + } + + public double max() { + return max; + } + + public double interval() { + return interval; } public boolean isUnlimited() { @@ -79,18 +100,33 @@ public class IrisAxisRotationClamp { public double getRadians(int rng) { if (forceLock) { - return Math.toRadians(Math.ceil(Math.abs((max % 360D)))); + return Math.toRadians(Math.ceil(Math.abs((max % FULL_TURN_DEGREES)))); } if (isUnlimited()) { double resolvedInterval = interval < 1 ? 1 : interval; - return Math.toRadians((resolvedInterval * (Math.ceil(Math.abs((rng % 360D) / resolvedInterval)))) % 360D); + return Math.toRadians((resolvedInterval * (Math.ceil(Math.abs((rng % FULL_TURN_DEGREES) / resolvedInterval)))) % FULL_TURN_DEGREES); } if (min == max && min != 0) { return Math.toRadians(max); } - return Math.toRadians(M.clip((interval * (Math.ceil(Math.abs((rng % 360D) / interval)))) % 360D, Math.min(min, max), Math.max(min, max))); + double angle = (interval * (Math.ceil(Math.abs((rng % FULL_TURN_DEGREES) / interval)))) % FULL_TURN_DEGREES; + return Math.toRadians(Math.min(Math.max(min, max), Math.max(Math.min(min, max), angle))); + } + + @Override + public boolean equals(Object other) { + return other instanceof AxisRotationClamp clamp + && enabled == clamp.enabled + && Double.compare(min, clamp.min) == 0 + && Double.compare(max, clamp.max) == 0 + && Double.compare(interval, clamp.interval) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(enabled, min, max, interval); } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java b/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java similarity index 54% rename from src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java rename to src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java index 22c7860fa..9d2030c1d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisSlopeClip.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,39 +16,46 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.prepare; -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; +/** The terrain slopes a placement or decorator may sit on, written as its {@code slopeCondition}. */ @Snippet("slope-clip") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("Limits placement to a minimum and maximum terrain slope") -@Data -public class IrisSlopeClip { +public final class SlopeClip { + private static final double DEFAULT_MINIMUM_SLOPE = 0; + private static final double DEFAULT_MAXIMUM_SLOPE = 10; + @MinNumber(0) @MaxNumber(1024) @Desc("The minimum slope for placement") - private double minimumSlope = 0; + private double minimumSlope = DEFAULT_MINIMUM_SLOPE; @MinNumber(0) @MaxNumber(1024) @Desc("The maximum slope for placement") - private double maximumSlope = 10; + private double maximumSlope = DEFAULT_MAXIMUM_SLOPE; + public SlopeClip() { + } + + public double minimumSlope() { + return minimumSlope; + } + + public double maximumSlope() { + return maximumSlope; + } + + /** Whether every slope passes. */ public boolean isDefault() { - return minimumSlope <= 0 && maximumSlope >= 10; + return minimumSlope <= 0 && maximumSlope >= DEFAULT_MAXIMUM_SLOPE; } - @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isValid(double slope) { if (isDefault()) { return true; diff --git a/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java b/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java new file mode 100644 index 000000000..41fad88d1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java @@ -0,0 +1,90 @@ +/* + * 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.builtin.stilt; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +import java.util.Optional; + +/** How far and with which blocks an object stilts into the ground, written as the placement's {@code stiltSettings}. */ +@Snippet("stilt-settings") +@Desc("Defines stilting behaviour.") +public final class StiltSettings { + @MinNumber(0) + @MaxNumber(64) + @Desc("Defines the maximum amount of blocks the object stilts verticially before overstilting and randomRange.") + private int yMax; + @MinNumber(0) + @MaxNumber(64) + @Desc("Defines the upper boundary for additional blocks after overstilting and/or maxStiltRange.") + private int yRand; + @MaxNumber(64) + @MinNumber(0) + @Desc("If the place mode is set to stilt, you can over-stilt it even further into the ground. Especially useful when using fast stilt due to inaccuracies.") + private int overStilt; + @Desc("If defined, stilting will be done using this block palette rather than the last layer of the object.") + private PaletteSpec palette; + @MinNumber(1) + @MaxNumber(256) + @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks to scan toward the cave floor (or ceiling) looking for solid ground before giving up.") + private int organicMaxScan = 48; + @MinNumber(0) + @MaxNumber(32) + @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks each column's stilt is randomly shortened by, giving the underside a ragged organic edge instead of a flat disc.") + private int organicJitter = 3; + @MinNumber(0) + @MaxNumber(1) + @Desc("For ORGANIC_STILT / CEILING_HANG: in the deepest fraction of each stilt column, blocks are randomly skipped to break the tip up. Higher = more broken and scratchy. 0 disables.") + private double organicScratch = 0.55; + + public StiltSettings() { + } + + public int yMax() { + return yMax; + } + + public int yRand() { + return yRand; + } + + public int overStilt() { + return overStilt; + } + + public Optional palette() { + return Optional.ofNullable(palette); + } + + public int organicMaxScan() { + return organicMaxScan; + } + + public int organicJitter() { + return organicJitter; + } + + public double organicScratch() { + return organicScratch; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java similarity index 52% rename from src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java rename to src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java index 12eb59fc4..26e63793c 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisVacuumSettings.java +++ b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java @@ -1,21 +1,32 @@ -package art.arcane.iris.engine.object.placement; +/* + * 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 . + */ -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +package art.arcane.iris.builtin.vacuum; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +/** How a VACUUM place mode bends terrain to meet an object's base, written as the placement's {@code vacuumSettings}. */ @Snippet("vacuum-settings") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("Defines how a VACUUM place mode bends terrain to meet an object's base.") -@Data -public class IrisVacuumSettings { +public final class VacuumSettings { @MinNumber(0) @MaxNumber(128) @Desc("The horizontal radius (in blocks) the terrain deformation extends beyond the object footprint before it blends back to the natural surface. 0 = derive automatically from the place mode (VACUUM, VACUUM_HIGH larger, VACUUM_FAST smaller).") @@ -36,4 +47,27 @@ public class IrisVacuumSettings { @MaxNumber(64) @Desc("For VACUUM_WAVY: the frequency of the simplex wave. Higher values make tighter, choppier ripples; lower values make broad, gentle swells. The wavelength in blocks is roughly 100 / waveScale.") private double waveScale = 5.0; + + public VacuumSettings() { + } + + public int radius() { + return radius; + } + + public double falloff() { + return falloff; + } + + public int organicJitter() { + return organicJitter; + } + + public int waveAmplitude() { + return waveAmplitude; + } + + public double waveScale() { + return waveScale; + } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectLimit.java b/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java similarity index 56% rename from src/main/java/art/arcane/iris/engine/object/placement/IrisObjectLimit.java rename to src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java index 71bcaab65..3c09f1090 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectLimit.java +++ b/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,24 +16,17 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.validate; -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; +/** The heights an object placement may sit between, written as the placement's {@code clamp}. */ @Snippet("object-limit") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("Limits object placement by minimum and maximum world height") -@Data -public class IrisObjectLimit { +public final class ObjectLimit { @MinNumber(-2048) @MaxNumber(2048) @Desc("The minimum height for placement (bottom of object)") @@ -44,7 +37,19 @@ public class IrisObjectLimit { @Desc("The maximum height for placement (top of object)") private int maximumHeight = 2048; - public boolean canPlace(int h, int l) { - return h <= maximumHeight && l >= minimumHeight; + public ObjectLimit() { + } + + public int minimumHeight() { + return minimumHeight; + } + + public int maximumHeight() { + return maximumHeight; + } + + /** Whether an object whose top is at {@code highest} and bottom at {@code lowest} fits between the limits. */ + public boolean canPlace(int highest, int lowest) { + return highest <= maximumHeight && lowest >= minimumHeight; } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 8702ababf..80cbed186 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import art.arcane.iris.core.IrisSettings; @@ -32,7 +33,6 @@ import art.arcane.iris.engine.framework.TreeBlockMaterial; import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.engine.object.placement.DecayControlPlacer; import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.carving.IrisCaveAnchorMode; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; @@ -1092,9 +1092,9 @@ public class ObjectPlacing { private IrisObjectRotation buildUpsideDownRotation() { IrisObjectRotation rt = new IrisObjectRotation(); rt.setEnabled(true); - rt.setXAxis(new IrisAxisRotationClamp(true, true, 180D, 180D, 90D)); - rt.setYAxis(new IrisAxisRotationClamp(true, false, 0D, 0D, 90D)); - rt.setZAxis(new IrisAxisRotationClamp()); + rt.setXAxis(AxisRotationClamp.of(true, true, 180D, 180D, 90D)); + rt.setYAxis(AxisRotationClamp.of(true, false, 0D, 0D, 90D)); + rt.setZAxis(new AxisRotationClamp()); return rt; } @@ -1542,8 +1542,8 @@ public class ObjectPlacing { int height = scaledDimension(size.getBlockY(), scale); int depth = scaledDimension(size.getBlockZ(), scale); IrisObjectRotation rotation = placement.getRotation(); - boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().isEnabled(); - boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().isEnabled(); + boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().enabled(); + boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().enabled(); int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); int warp = placement.getWarp() != null && !placement.getWarp().isFlat() @@ -1574,7 +1574,7 @@ public class ObjectPlacing { if (rotateVertically) { return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); } - boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().isEnabled(); + boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().enabled(); return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 4a97bcd25..713740fc3 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; @@ -34,7 +35,6 @@ import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.decoration.IrisDecorationPart; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; -import art.arcane.iris.engine.object.placement.IrisSlopeClip; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.context.ChunkContext; @@ -86,7 +86,7 @@ public class FloatingIslands { continue; } double layerDepth = heightGenerator.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / layer.getZoom(), wz / layer.getZoom()); - IrisSlopeClip slopeClip = layer.getSlopeCondition(); + SlopeClip slopeClip = layer.getSlopeCondition(); if (slopeClip != null && !slopeClip.isDefault() && complex != null && !slopeClip.isValid(complex.getSlopeStream().get(wx, wz))) { layerDepth = 0; diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 625b59b6a..6b15edda1 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.placement.IrisSlopeClip; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.hunk.Hunk; @@ -210,7 +210,7 @@ public class SurfaceSmoothing { || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, originX, originZ, currentData))) //@done { - IrisSlopeClip sc = biome.getSlab().getSlopeCondition(); + SlopeClip sc = biome.getSlab().getSlopeCondition(); PlatformBlockState d = sc.isValid(engine.getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, engine.getData()) : null; if (d != null) { diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java index 8c3e6123c..a7c8803f8 100644 --- a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java +++ b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorator.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.decoration; +import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.placement.IrisSlopeClip; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; @@ -71,7 +71,7 @@ public class IrisDecorator { @Desc("When set, the decorator will never place onto any of these blocks.") private KList blacklist; @Desc("The slope at which this decorator can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the decorator placement.") - private IrisSlopeClip slopeCondition = new IrisSlopeClip(); + private SlopeClip slopeCondition = new SlopeClip(); @DependsOn({"scaleStack", "stackMin", "stackMax"}) @Desc("If stackMax is set to true, use this to limit its max height for large caverns") private int absoluteMaxStack = 30; 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 index 48968bcfc..e01880283 100644 --- a/src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java +++ b/src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.mod; -import art.arcane.iris.engine.object.placement.IrisObjectReplace; +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; @@ -100,9 +100,9 @@ public class IrisMod extends IrisRegistrant { @Desc("Replace regions with other regions") private KList regionReplacers = new KList<>(); - @ArrayType(min = 1, type = IrisObjectReplace.class) + @ArrayType(min = 1, type = ObjectReplace.class) @Desc("Replace blocks with other blocks") - private KList blockReplacers = new KList<>(); + private KList blockReplacers = new KList<>(); @ArrayType(min = 1, type = IrisModNoiseStyleReplacer.class) @Desc("Replace noise styles with other styles") diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 95acd4342..dc7dd6727 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; @@ -65,6 +67,11 @@ public final class BlocksModule implements IrisModule { return ModuleInfo.of("iris:blocks", "Object blocks", PlacementModules.VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(ObjectReplace.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Blocks.WRITE) 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 index 23b508538..20673ee8c 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,6 +18,11 @@ package art.arcane.iris.engine.object.placement; +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.engine.object.loot.IObjectLoot; import art.arcane.iris.engine.object.loot.IrisLootTable; @@ -96,7 +101,7 @@ public class IrisObjectPlacement { @Desc("Rotate this objects placement") private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max height or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + 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.") @@ -104,7 +109,7 @@ public class IrisObjectPlacement { @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 IrisSlopeClip slopeCondition = new IrisSlopeClip(); + 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; @@ -118,9 +123,9 @@ public class IrisObjectPlacement { @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 IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("When a VACUUM place mode is used, this defines the deformation radius and falloff.") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @MaxNumber(64) @MinNumber(0) @Desc("When bore is enabled, expand max-y of the cuboid it removes") @@ -168,9 +173,9 @@ public class IrisObjectPlacement { private IrisGeneratorStyle warp = new IrisGeneratorStyle(NoiseStyle.FLAT); @Desc("The placement mode") private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - @ArrayType(min = 1, type = IrisObjectReplace.class) + @ArrayType(min = 1, type = ObjectReplace.class) @Desc("Find and replace blocks") - private KList edit = new KList<>(); + private KList edit = new KList<>(); @Desc("Translate this object's placement") private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Scale Objects") diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.java deleted file mode 100644 index 0ba26ca28..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectReplace.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.placement; - -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.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.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Snippet("object-block-replacer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Find and replace object materials") -@Data -public class IrisObjectReplace { - private final transient AtomicCache replaceGen = new AtomicCache<>(); - private final transient AtomicCache> findData = new AtomicCache<>(); - private final transient AtomicCache> replaceData = new AtomicCache<>(); - @ArrayType(min = 1, type = IrisBlockData.class) - @Required - @Desc("Find this block") - private KList find = new KList<>(); - @Required - @Desc("Replace it with this block palette") - private IrisMaterialPalette replace = new IrisMaterialPalette(); - @Desc("Exactly match the block data or not") - private boolean exact = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("Modifies the chance the block is replaced") - private float chance = 1; - - public KList getFind(IrisData rdata) { - return findData.aquire(() -> - { - KList b = new KList<>(); - - for (IrisBlockData i : find) { - PlatformBlockState bx = i.getBlockData(rdata); - - if (bx != null) { - b.add(bx); - } - } - - return b; - }); - } - - public PlatformBlockState getReplace(RNG seed, double x, double y, double z, IrisData rdata) { - return getReplace().get(seed, x, y, z, rdata); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java index b10b38e87..e12f4ced3 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.vacuum.VacuumSettings; + public final class IrisObjectVacuum { private static final double DEFAULT_WAVE_AMPLITUDE = 3.0; private static final double DEFAULT_WAVE_SCALE = 5.0; @@ -35,14 +37,14 @@ public final class IrisObjectVacuum { || mode == ObjectPlaceMode.VACUUM_WAVY; } - public static int resolveRadius(ObjectPlaceMode mode, IrisVacuumSettings settings) { + public static int resolveRadius(ObjectPlaceMode mode, VacuumSettings settings) { int radius = switch (mode) { case VACUUM_HIGH -> 20; case VACUUM_FAST -> 8; default -> 12; }; - if (settings != null && settings.getRadius() > 0) { - radius = settings.getRadius(); + if (settings != null && settings.radius() > 0) { + radius = settings.radius(); } return Math.max(0, Math.min(MAX_RADIUS_BLOCKS, radius)); } @@ -51,22 +53,22 @@ public final class IrisObjectVacuum { return mode == ObjectPlaceMode.VACUUM_FAST ? 2 : 1; } - public static double resolveFalloff(IrisVacuumSettings settings) { - return settings != null ? Math.max(0.25, settings.getFalloff()) : 2.0; + public static double resolveFalloff(VacuumSettings settings) { + return settings != null ? Math.max(0.25, settings.falloff()) : 2.0; } - public static double resolveWaveAmplitude(IrisVacuumSettings settings) { + public static double resolveWaveAmplitude(VacuumSettings settings) { if (settings == null) { return DEFAULT_WAVE_AMPLITUDE; } - return Math.max(0, settings.getWaveAmplitude()); + return Math.max(0, settings.waveAmplitude()); } - public static double resolveWaveScale(IrisVacuumSettings settings) { + public static double resolveWaveScale(VacuumSettings settings) { if (settings == null) { return DEFAULT_WAVE_SCALE; } - double scale = settings.getWaveScale(); + double scale = settings.waveScale(); return scale > 0 ? scale : DEFAULT_WAVE_SCALE; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java deleted file mode 100644 index c9245aba8..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisStiltSettings.java +++ /dev/null @@ -1,47 +0,0 @@ -package art.arcane.iris.engine.object.placement; - -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("stilt-settings") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Defines stilting behaviour.") -@Data -public class IrisStiltSettings { - @MinNumber(0) - @MaxNumber(64) - @Desc("Defines the maximum amount of blocks the object stilts verticially before overstilting and randomRange.") - private int yMax; - @MinNumber(0) - @MaxNumber(64) - @Desc("Defines the upper boundary for additional blocks after overstilting and/or maxStiltRange.") - private int yRand; - @MaxNumber(64) - @MinNumber(0) - @Desc("If the place mode is set to stilt, you can over-stilt it even further into the ground. Especially useful when using fast stilt due to inaccuracies.") - private int overStilt; - @Desc("If defined, stilting will be done using this block palette rather than the last layer of the object.") - private IrisMaterialPalette palette; - @MinNumber(1) - @MaxNumber(256) - @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks to scan toward the cave floor (or ceiling) looking for solid ground before giving up.") - private int organicMaxScan = 48; - @MinNumber(0) - @MaxNumber(32) - @Desc("For ORGANIC_STILT / CEILING_HANG: the maximum number of blocks each column's stilt is randomly shortened by, giving the underside a ragged organic edge instead of a flat disc.") - private int organicJitter = 3; - @MinNumber(0) - @MaxNumber(1) - @Desc("For ORGANIC_STILT / CEILING_HANG: in the deepest fraction of each stilt column, blocks are randomly skipped to break the tip up. Higher = more broken and scratchy. 0 disables.") - private double organicScratch = 0.55; - -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java index 122ef4e7f..b6bf61863 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.material.BlockDataMergeSupport; import art.arcane.iris.engine.object.prefab.IrisObjectShaping; @@ -37,25 +38,27 @@ final class ObjectEdits { /** {@code tile} may be null; the result's tile is the last replacement's tile, if it has one. */ static Edited apply(IrisObjectPlacement config, PlatformBlockState data, TileData tile, RNG rng, double x, double y, double z, IrisData rdata) { + ResolvedReplaces replaces = ResolvedReplaces.of(rdata); PlatformBlockState edited = data; TileData editedTile = tile; - for (IrisObjectReplace replace : config.getEdit()) { - if (!rng.chance(replace.getChance())) { + for (ObjectReplace settings : config.getEdit()) { + ResolvedReplace replace = replaces.of(settings); + if (!rng.chance(replace.chance())) { continue; } - for (PlatformBlockState find : replace.getFind(rdata)) { + for (PlatformBlockState find : replace.find()) { if (!finds(replace, find, edited)) { continue; } - edited = replaced(edited, replace.getReplace(rng, x, y, z, rdata)); - editedTile = replace.getReplace().getTile(rng, x, y, z, rdata).orElse(editedTile); + edited = replaced(edited, replace.replacement(rng, x, y, z)); + editedTile = replace.tile(rng).orElse(editedTile); } } return new Edited(edited, editedTile); } - private static boolean finds(IrisObjectReplace replace, PlatformBlockState find, PlatformBlockState data) { - return replace.isExact() + private static boolean finds(ResolvedReplace replace, PlatformBlockState find, PlatformBlockState data) { + return replace.exact() ? find.matches(data) : IrisObjectShaping.materialKey(find).equals(IrisObjectShaping.materialKey(data)); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java index 3947fdc35..84513c78a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.math.IrisBlockVector; @@ -55,20 +55,20 @@ import art.arcane.iris.util.common.math.IrisBlockVector; ySin = Math.sin(yAngle); } - private static int modeOf(IrisAxisRotationClamp clamp) { + private static int modeOf(AxisRotationClamp clamp) { if (!clamp.isLocked()) { return MODE_ANGLE; } - if (Math.abs(clamp.getMax()) % 360D == 180D) { + if (Math.abs(clamp.max()) % 360D == 180D) { return MODE_FLIP; } - if (clamp.getMax() % 360D == 90D || clamp.getMax() % 360D == -270D) { + if (clamp.max() % 360D == 90D || clamp.max() % 360D == -270D) { return MODE_QUARTER; } - if (clamp.getMax() == -90D || clamp.getMax() % 360D == 270D) { + if (clamp.max() == -90D || clamp.max() % 360D == 270D) { return MODE_THREE_QUARTER; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 6d1ed38ab..58e57bb77 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -18,11 +18,13 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.prepare.SlopeClip; +import com.volmit.FeatureRegistry; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; -import art.arcane.iris.engine.object.prefab.IrisAxisRotationClamp; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; @@ -52,6 +54,12 @@ public final class PrepareModule implements IrisModule { return ModuleInfo.of("iris:prepare", "Placement preparation", PlacementModules.VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(SlopeClip.class); + registry.registerHeldType(AxisRotationClamp.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Prepare.SLOPE).produce(PrepareModule::slope); @@ -89,15 +97,15 @@ public final class PrepareModule implements IrisModule { double downhill = lowest == north ? NORTH : lowest == east ? EAST : lowest == south ? SOUTH : WEST; IrisObjectRotation requested = config.getRotation(); - double turn = requested.getYAxis().getMin() + downhill; + double turn = requested.getYAxis().min() + downhill; IrisObjectRotation rotation = new IrisObjectRotation(); rotation.setXAxis(requested.getXAxis()); rotation.setZAxis(requested.getZAxis()); if (turn == 0) { - rotation.setYAxis(new IrisAxisRotationClamp(false, false, 0, 0, QUARTER_TURN)); + rotation.setYAxis(AxisRotationClamp.of(false, false, 0, 0, QUARTER_TURN)); rotation.setEnabled(requested.canRotateX() || requested.canRotateZ()); } else { - rotation.setYAxis(new IrisAxisRotationClamp(true, false, turn, turn, QUARTER_TURN)); + rotation.setYAxis(AxisRotationClamp.of(true, false, turn, turn, QUARTER_TURN)); rotation.setEnabled(true); } IrisObjectPlacement turned = config.toPlacement(config.getPlace().toArray(new String[0])); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java new file mode 100644 index 000000000..0dfe6050f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java @@ -0,0 +1,94 @@ +/* + * 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.blocks.ObjectReplace; +import art.arcane.iris.core.modules.BlockEntities; +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.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.object.BlockEntityData; + +import java.util.List; +import java.util.Optional; + +/** + * One {@link ObjectReplace} made ready for a pack: the blocks it finds resolved to the platform's, its palette + * picked through the pack's block registry with the seed of the {@link RNG} the placement hands in, and the tile + * data of the palette's entries resolved once. The old settings class cached the same things on itself. + */ +final class ResolvedReplace { + private final List find; + private final boolean exact; + private final float chance; + private final PaletteSpec replace; + private final BlockRegistry blocks; + private final List> entryTiles; + private final int weightedSize; + + ResolvedReplace(List find, boolean exact, float chance, PaletteSpec replace, BlockRegistry blocks) { + this.find = List.copyOf(find); + this.exact = exact; + this.chance = chance; + this.replace = replace; + this.blocks = blocks; + this.entryTiles = replace.palette().stream().map(blocks::blockEntity).toList(); + this.weightedSize = replace.palette().stream().mapToInt(spec -> Math.max(0, spec.weight())).sum(); + } + + static ResolvedReplace of(ObjectReplace settings, BlockRegistry blocks) { + List find = settings.find().stream() + .map(spec -> B.getState(blocks.resolve(spec).key())) + .toList(); + return new ResolvedReplace(find, settings.exact(), settings.chance(), settings.replace(), blocks); + } + + float chance() { + return chance; + } + + boolean exact() { + return exact; + } + + List find() { + return find; + } + + PlatformBlockState replacement(RNG rng, double x, double y, double z) { + return B.getState(blocks.palette(replace, rng.getSeed()).at(x, y, z).key()); + } + + /** The tile data of the entry picked for {@code rng}: the first entry when the palette's weights add up to one, else a uniform pick. */ + Optional tile(RNG rng) { + if (weightedSize == 0) { + return Optional.empty(); + } + Optional entity = entryTiles.get(weightedSize == 1 ? 0 : pickedEntry(rng)); + return entity.map(BlockEntities::tileOf); + } + + private int pickedEntry(RNG rng) { + return entryTiles.size() == 1 ? 0 : rng.nextInt(entryTiles.size()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java new file mode 100644 index 000000000..1b1fd4ce4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java @@ -0,0 +1,54 @@ +/* + * 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.blocks.ObjectReplace; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; +import com.volmit.block.BlockRegistry; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** The {@link ResolvedReplace}s of one engine runtime, one per decoded {@link ObjectReplace}, built when a placement first uses it. */ +final class ResolvedReplaces { + private final BlockRegistry blocks; + private final Map resolved = new ConcurrentHashMap<>(); + + ResolvedReplaces(Engine engine) { + this(engine.getData().getPackResources().blocks()); + } + + ResolvedReplaces(BlockRegistry blocks) { + this.blocks = blocks; + } + + /** The replacements of the engine {@code data} serves, or of {@code data} alone when no engine runs it. */ + static ResolvedReplaces of(IrisData data) { + Engine engine = data.getEngine(); + if (engine == null) { + return new ResolvedReplaces(data.getPackResources().blocks()); + } + return engine.getGeneration().state(ResolvedReplaces.class, ResolvedReplaces::new); + } + + ResolvedReplace of(ObjectReplace settings) { + return resolved.computeIfAbsent(settings, replace -> ResolvedReplace.of(replace, blocks)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index eee31d184..6c9cbf679 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.placement; +import com.volmit.FeatureRegistry; +import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.stilt.StiltLayers; import art.arcane.iris.core.modules.IrisPlacement; @@ -64,6 +66,11 @@ public final class StiltModule implements IrisModule { return ModuleInfo.of("iris:stilt", "Stilts", PlacementModules.VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(StiltSettings.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Stilt.LAYERS) @@ -107,7 +114,8 @@ public final class StiltModule implements IrisModule { private final IrisPlacement placement; private final PreparedPlacement prepared; private final IrisObjectPlacement config; - private final IrisStiltSettings settings; + private final StiltSettings settings; + private final PlatformBlockState palette; private final StiltShape shape; private final PlacementWorld world; private final RNG rng; @@ -124,10 +132,19 @@ public final class StiltModule implements IrisModule { this.world = new PlacementWorld(context.access(), placement.states()); this.rng = new RNG(context.random().nextLong()); this.anchorY = context.output(IrisStages.Anchor.FINAL).y(); + this.palette = settings == null ? null : paletteBlock(settings); this.layerY = shape == StiltShape.CEILING ? layers.topY() : layers.bottomY(); this.erode = shape == StiltShape.ERODE ? ErodeShape.of(layers.bottom()) : null; } + /** The block the settings' palette picks for this placement, the same for every column; null without a palette. */ + private PlatformBlockState paletteBlock(StiltSettings stilt) { + return stilt.palette() + .map(spec -> placement.data().getPackResources().blocks().palette(spec, rng.getSeed())) + .map(picker -> B.getState(picker.at(placement.x(), anchorY, placement.z()).key())) + .orElse(null); + } + private void grow(ObjectBlock block) { BlockPosition offset = block.position(); PlatformBlockState state = stiltState(block, offset); @@ -152,8 +169,8 @@ public final class StiltModule implements IrisModule { /** The block the stilt repeats: the palette's when the settings have one, soil turned to dirt, edited and turned with the object. */ private PlatformBlockState stiltState(ObjectBlock block, BlockPosition offset) { PlatformBlockState state = placement.states().toPlatform(block.state()); - if (settings != null && settings.getPalette() != null) { - state = settings.getPalette().get(rng, placement.x(), anchorY, placement.z(), placement.data()); + if (palette != null) { + state = palette; } else if (SOIL_MATERIALS.contains(IrisObjectShaping.materialKey(state))) { state = B.getState(SOIL_REPLACEMENT); } @@ -174,9 +191,9 @@ public final class StiltModule implements IrisModule { } int lowerBound = highest - 1; if (settings != null) { - lowerBound -= settings.getOverStilt() - rng.i(0, settings.getYRand()); - if (settings.getYMax() != 0) { - lowerBound -= Math.min(settings.getYMax() - (top - highest), 0); + lowerBound -= settings.overStilt() - rng.i(0, settings.yRand()); + if (settings.yMax() != 0) { + lowerBound -= Math.min(settings.yMax() - (top - highest), 0); } } if (erode != null) { @@ -198,9 +215,9 @@ public final class StiltModule implements IrisModule { /** Grows from the layer toward the first solid block in {@code direction}, -1 down or 1 up. */ private void growOrganic(PlatformBlockState state, int x, int z, int direction) { - int maxScan = settings != null ? Math.max(1, settings.getOrganicMaxScan()) : DEFAULT_ORGANIC_MAX_SCAN; - int jitterMax = settings != null ? Math.max(0, settings.getOrganicJitter()) : DEFAULT_ORGANIC_JITTER; - double scratch = settings != null ? Math.max(0, Math.min(1, settings.getOrganicScratch())) : DEFAULT_ORGANIC_SCRATCH; + int maxScan = settings != null ? Math.max(1, settings.organicMaxScan()) : DEFAULT_ORGANIC_MAX_SCAN; + int jitterMax = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; + double scratch = settings != null ? Math.max(0, Math.min(1, settings.organicScratch())) : DEFAULT_ORGANIC_SCRATCH; long columnHash = ((long) x * HASH_X) ^ ((long) z * HASH_Y); int jitter = jitterMax > 0 ? (int) (Math.abs(columnHash) % (jitterMax + 1)) : 0; int start = layerY + anchorY; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 2865cc31a..95553141d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.placement; +import com.volmit.FeatureRegistry; +import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.core.modules.IrisPlacement; @@ -49,6 +51,11 @@ public final class VacuumModule implements IrisModule { return ModuleInfo.of("iris:vacuum", "Vacuum", PlacementModules.VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(VacuumSettings.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Vacuum.TERRAIN) @@ -91,11 +98,11 @@ public final class VacuumModule implements IrisModule { this.prepared = prepared; this.world = new PlacementWorld(context.access(), placement.states()); this.complex = engine.getComplex(); - IrisVacuumSettings settings = prepared.config().getVacuumSettings(); + VacuumSettings settings = prepared.config().getVacuumSettings(); this.radius = IrisObjectVacuum.resolveRadius(mode, settings); this.step = IrisObjectVacuum.resolveStep(mode); this.falloff = IrisObjectVacuum.resolveFalloff(settings); - this.jitter = settings != null ? Math.max(0, settings.getOrganicJitter()) : DEFAULT_ORGANIC_JITTER; + this.jitter = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); this.waves = mode == ObjectPlaceMode.VACUUM_WAVY && waveAmplitude > 0 ? new SimplexNoise(WAVE_SEED) : null; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 915094e2f..815d4712d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.validate.ObjectLimit; +import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.framework.Engine; @@ -53,6 +55,11 @@ public final class ValidateModule implements IrisModule { return ModuleInfo.of("iris:validate", "Placement checks", PlacementModules.VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(ObjectLimit.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Validate.SURFACE) 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 index 330fcbe75..e9d6b801b 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java @@ -18,6 +18,7 @@ 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; @@ -79,64 +80,41 @@ public class IrisObjectRotation { private boolean enabled = true; @Desc("The x axis rotation") - private IrisAxisRotationClamp xAxis = new IrisAxisRotationClamp(); + private AxisRotationClamp xAxis = new AxisRotationClamp(); @Desc("The y axis rotation") - private IrisAxisRotationClamp yAxis = new IrisAxisRotationClamp(true, false, 0, 0, 90); + private AxisRotationClamp yAxis = AxisRotationClamp.of(true, false, 0, 0, 90); @Desc("The z axis rotation") - private IrisAxisRotationClamp zAxis = new IrisAxisRotationClamp(); + private AxisRotationClamp zAxis = new AxisRotationClamp(); public static IrisObjectRotation xFlip180() { IrisObjectRotation rt = new IrisObjectRotation(); - IrisAxisRotationClamp rtx = new IrisAxisRotationClamp(); - IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); - IrisAxisRotationClamp rtz = new IrisAxisRotationClamp(); rt.setEnabled(true); - rt.setXAxis(rtx); - rt.setYAxis(rty); - rt.setZAxis(rtz); - rtx.setEnabled(true); - rtx.minMax(180); - rty.setEnabled(false); - rtz.setEnabled(false); + 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(new IrisAxisRotationClamp(true, false, 0, 0, 90)); + rt.setYAxis(AxisRotationClamp.of(true, false, 0, 0, 90)); return rt; } public static IrisObjectRotation xFlip180WithY(double y) { IrisObjectRotation rt = xFlip180(); - IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); - rty.setEnabled(true); - rty.setInterval(90); - rty.minMax(y); - rt.setYAxis(rty); + rt.setYAxis(AxisRotationClamp.locked(true, y, 90)); return rt; } public static IrisObjectRotation of(double x, double y, double z) { IrisObjectRotation rt = new IrisObjectRotation(); - IrisAxisRotationClamp rtx = new IrisAxisRotationClamp(); - IrisAxisRotationClamp rty = new IrisAxisRotationClamp(); - IrisAxisRotationClamp rtz = new IrisAxisRotationClamp(); rt.setEnabled(x != 0 || y != 0 || z != 0); - rt.setXAxis(rtx); - rt.setYAxis(rty); - rt.setZAxis(rtz); - rtx.setEnabled(x != 0); - rty.setEnabled(y != 0); - rtz.setEnabled(z != 0); - rtx.setInterval(90); - rty.setInterval(90); - rtz.setInterval(90); - rtx.minMax(x); - rty.minMax(y); - rtz.minMax(z); + 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; } @@ -182,12 +160,12 @@ public class IrisObjectRotation { return s; } - public double getRotation(int spin, IrisAxisRotationClamp clamp) { + public double getRotation(int spin, AxisRotationClamp clamp) { if (!enabled) { return 0; } - if (!clamp.isEnabled()) { + if (!clamp.enabled()) { return 0; } @@ -457,14 +435,14 @@ public class IrisObjectRotation { if (canRotateX()) { if (getXAxis().isLocked()) { - if (Math.abs(getXAxis().getMax()) % 360D == 180D) { + if (Math.abs(getXAxis().max()) % 360D == 180D) { v.setZ(-v.getZ()); v.setY(-v.getY()); - } else if (getXAxis().getMax() % 360D == 90D || getXAxis().getMax() % 360D == -270D) { + } else if (getXAxis().max() % 360D == 90D || getXAxis().max() % 360D == -270D) { double z = v.getZ(); v.setZ(v.getY()); v.setY(-z); - } else if (getXAxis().getMax() == -90D || getXAxis().getMax() % 360D == 270D) { + } else if (getXAxis().max() == -90D || getXAxis().max() % 360D == 270D) { double z = v.getZ(); v.setZ(-v.getY()); v.setY(z); @@ -478,14 +456,14 @@ public class IrisObjectRotation { if (canRotateZ()) { if (getZAxis().isLocked()) { - if (Math.abs(getZAxis().getMax()) % 360D == 180D) { + if (Math.abs(getZAxis().max()) % 360D == 180D) { v.setY(-v.getY()); v.setX(-v.getX()); - } else if (getZAxis().getMax() % 360D == 90D || getZAxis().getMax() % 360D == -270D) { + } else if (getZAxis().max() % 360D == 90D || getZAxis().max() % 360D == -270D) { double y = v.getY(); v.setY(v.getX()); v.setX(-y); - } else if (getZAxis().getMax() == -90D || getZAxis().getMax() % 360D == 270D) { + } else if (getZAxis().max() == -90D || getZAxis().max() % 360D == 270D) { double y = v.getY(); v.setY(-v.getX()); v.setX(y); @@ -499,14 +477,14 @@ public class IrisObjectRotation { if (canRotateY()) { if (getYAxis().isLocked()) { - if (Math.abs(getYAxis().getMax()) % 360D == 180D) { + if (Math.abs(getYAxis().max()) % 360D == 180D) { v.setX(-v.getX()); v.setZ(-v.getZ()); - } else if (getYAxis().getMax() % 360D == 90D || getYAxis().getMax() % 360D == -270D) { + } else if (getYAxis().max() % 360D == 90D || getYAxis().max() % 360D == -270D) { double x = v.getX(); v.setX(v.getZ()); v.setZ(-x); - } else if (getYAxis().getMax() == -90D || getYAxis().getMax() % 360D == 270D) { + } else if (getYAxis().max() == -90D || getYAxis().max() % 360D == 270D) { double x = v.getX(); v.setX(-v.getZ()); v.setZ(x); @@ -522,15 +500,15 @@ public class IrisObjectRotation { } public boolean canRotateX() { - return enabled && xAxis.isEnabled(); + return enabled && xAxis.enabled(); } public boolean canRotateY() { - return enabled && yAxis.isEnabled(); + return enabled && yAxis.enabled(); } public boolean canRotateZ() { - return enabled && zAxis.isEnabled(); + return enabled && zAxis.enabled(); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java index 8a1ab5fb2..1157a89d5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.procedural.coral; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectLimit; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisStiltSettings; -import art.arcane.iris.engine.object.placement.IrisVacuumSettings; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -81,7 +81,7 @@ public class IrisCoral implements IrisProceduralPlacement { private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + private ObjectLimit clamp = new ObjectLimit(); @Desc("Whether this coral may place on the terrain surface, under carvings, or both.") private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; @@ -93,10 +93,10 @@ public class IrisCoral implements IrisProceduralPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @Desc("If true (default), every resolved coral block that is waterloggable is forced waterlogged so the coral does not die in water (coral fans, sea pickles and kelp also waterlog). Set false to place dead/dry coral.") private boolean waterlogged = true; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java index 971c2349d..994b478a8 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.procedural.crystal; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectLimit; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisStiltSettings; -import art.arcane.iris.engine.object.placement.IrisVacuumSettings; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -81,7 +81,7 @@ public class IrisCrystal implements IrisProceduralPlacement { private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + private ObjectLimit clamp = new ObjectLimit(); @Desc("Whether this crystal cluster may place on the terrain surface, under carvings, or both. Crystals are meant for caves, so this defaults to CARVING_ONLY.") private CarvingMode carvingSupport = CarvingMode.CARVING_ONLY; @@ -93,10 +93,10 @@ public class IrisCrystal implements IrisProceduralPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @Desc("The surface this crystal grows from (FLOOR shards up, CEILING shards down, WALL shards outward). This orients the baked geometry only.") private IrisCrystalSurface growthSurface = IrisCrystalSurface.FLOOR; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java index b13a70d7b..b8506ff04 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.procedural.formation; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectLimit; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisStiltSettings; -import art.arcane.iris.engine.object.placement.IrisVacuumSettings; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -81,7 +81,7 @@ public class IrisFormation implements IrisProceduralPlacement { private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + private ObjectLimit clamp = new ObjectLimit(); @Desc("Whether this formation may place on the terrain surface, under carvings, or both.") private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; @@ -98,10 +98,10 @@ public class IrisFormation implements IrisProceduralPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @Desc("The overall silhouette of the formation. Drives which sculpting routine the generator uses.") private IrisFormationForm form = IrisFormationForm.SPIRE; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java index ba6fde25b..990345198 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.procedural.fungi; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectLimit; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisStiltSettings; -import art.arcane.iris.engine.object.placement.IrisVacuumSettings; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -81,7 +81,7 @@ public class IrisFungus implements IrisProceduralPlacement { private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + private ObjectLimit clamp = new ObjectLimit(); @Desc("Whether this fungus may place on the terrain surface, under carvings, or both.") private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; @@ -93,10 +93,10 @@ public class IrisFungus implements IrisProceduralPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @Required @Desc("The stem block, e.g. minecraft:mushroom_stem. Ignored when stemPalette is set.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java index 10e7f190a..c7f4fed30 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.procedural.ruin; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectLimit; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisStiltSettings; -import art.arcane.iris.engine.object.placement.IrisVacuumSettings; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -83,7 +83,7 @@ public class IrisRuin implements IrisProceduralPlacement { private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max or min terrain height at which this ruin may place.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + private ObjectLimit clamp = new ObjectLimit(); @Desc("Whether this ruin may place on the terrain surface, under carvings (caves), or both. SURFACE_ONLY keeps ruins above ground.") private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; @@ -95,10 +95,10 @@ public class IrisRuin implements IrisProceduralPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @Required @Desc("The primary structural block, e.g. minecraft:cobblestone or minecraft:stone_bricks. Ignored when blockPalette is set. This is the bulk material of the ruin before weathering swaps some of it out.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java index 7d4f9a7a3..0f6c635e3 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectLimit; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisStiltSettings; -import art.arcane.iris.engine.object.placement.IrisVacuumSettings; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -86,7 +86,7 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private IrisObjectRotation rotation = new IrisObjectRotation(); @Desc("Limit the max or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + private ObjectLimit clamp = new ObjectLimit(); @Desc("Whether this tree may place on the terrain surface, under carvings, or both.") private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; @@ -98,10 +98,10 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private IrisStiltSettings stiltSettings; + private StiltSettings stiltSettings; @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private IrisVacuumSettings vacuumSettings; + private VacuumSettings vacuumSettings; @Required @Desc("The trunk (log) block, e.g. minecraft:oak_log. Ignored when trunkPalette is set.") 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 index e3bc5a159..b30ef0ced 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.structure; +import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisObjectLoot; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisObjectReplace; import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; @@ -96,9 +96,9 @@ public class IrisStructure extends IrisRegistrant { @Desc("The place mode used when stamping each piece object into the world.") private ObjectPlaceMode placeMode = ObjectPlaceMode.STRUCTURE_PIECE; - @ArrayType(min = 1, type = IrisObjectReplace.class) + @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<>(); + private KList edit = new KList<>(); @ArrayType(type = String.class, min = 1) @RegistryListResource(IrisLootTable.class) diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java index 5a976aaa6..e9b04809a 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.terrain; +import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisSlopeClip; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink; @@ -73,7 +73,7 @@ public final class IrisBiomeLayerGenerator { CNG hgen = heightGenerators.get(i); double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); - IrisSlopeClip sc = layer.getSlopeCondition(); + SlopeClip sc = layer.getSlopeCondition(); if (!sc.isDefault()) { if (!sc.isValid(complex.getSlopeStream().get(wx, wz))) { @@ -193,7 +193,7 @@ public final class IrisBiomeLayerGenerator { CNG hgen = heightGenerators.get(i); double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); - IrisSlopeClip sc = layer.getSlopeCondition(); + SlopeClip sc = layer.getSlopeCondition(); if (!sc.isDefault()) { if (!sc.isValid(complex.getSlopeStream().get(wx, wz))) { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java index 86e9120a4..1825e7863 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.terrain; +import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.placement.IrisSlopeClip; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; @@ -65,7 +65,7 @@ public class IrisBiomePaletteLayer { @Desc("The max thickness of this layer") private int maxHeight = 1; @Desc("If set, this layer only shows where the terrain slope is within these bounds; outside them the layer is skipped entirely. Thickness is not scaled by slope.") - private IrisSlopeClip slopeCondition = new IrisSlopeClip(); + private SlopeClip slopeCondition = new SlopeClip(); @MinNumber(0.0001) @Desc("The terrain zoom mostly for zooming in on a wispy palette") private double zoom = 5; From a1af4a85ff838c946ef078e84d523498386d40c4 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:02:47 +0200 Subject: [PATCH 032/139] iris:loot: Loot and BlockDrops providers, loot table resolution and item drawing moved out of core --- source-patterns.txt | 1 + .../iris/engine/loot/BlockDropping.java | 66 +++++++ .../arcane/iris/engine/loot/LootGiving.java | 114 ++++++++++++ .../arcane/iris/engine/loot/LootItems.java | 151 ++++++++++++++++ .../arcane/iris/engine/loot/LootModule.java | 50 ++++++ .../arcane/iris/engine/loot/LootTables.java | 162 ++++++++++++++++++ .../mantle/components/ObjectLocating.java | 18 ++ .../engine/object/loot/IrisBlockDrops.java | 37 ++-- .../iris/engine/object/loot/IrisLoot.java | 2 +- .../engine/object/loot/IrisLootTable.java | 2 +- .../object/loot/IrisVanillaLootTable.java | 2 +- 11 files changed, 590 insertions(+), 15 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/loot/BlockDropping.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootGiving.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootItems.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootModule.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootTables.java diff --git a/source-patterns.txt b/source-patterns.txt index b09f3c28b..f4f3d130d 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -16,3 +16,4 @@ 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/** diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java new file mode 100644 index 000000000..e1ff26a61 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -0,0 +1,66 @@ +/* + * 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.loot; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.loot.IrisBlockDrops; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.item.ItemDrop; +import com.volmit.service.BlockDrops; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; + +/** + * How {@code iris:loot} drops items for broken blocks: the block drops of the biome, the region and the dimension, the + * biome's first and the biome able to keep the others from dropping. + */ +public final class BlockDropping implements BlockDrops { + @Override + public Result drops(PackWorld world, Broken broken) { + Engine engine = IrisPackWorld.of(world).engine(); + int x = broken.position().x(); + int y = broken.position().y(); + int z = broken.position().z(); + PlatformBlockState block = IrisPlatforms.get().registries().block(broken.block().key()); + + IrisBiome biome = engine.getBiome(x, y, z); + List providers = dropsFor(biome.getBlockDrops(), block, engine); + if (providers.stream().noneMatch(IrisBlockDrops::isSkipParents)) { + IrisRegion region = engine.getRegion(x, z); + providers.addAll(dropsFor(region.getBlockDrops(), block, engine)); + providers.addAll(dropsFor(engine.getDimension().getBlockDrops(), block, engine)); + } + + LootItems items = new LootItems(world.resources().items(), false); + List drops = new ArrayList<>(); + providers.forEach(provider -> provider.fillDrops(items, drops)); + return new Result(drops, providers.stream().anyMatch(IrisBlockDrops::isReplaceVanillaDrops)); + } + + private static List dropsFor(KList candidates, PlatformBlockState block, Engine engine) { + return new KList<>(candidates.stream().filter(drops -> drops.shouldDropFor(block, engine.getData())).toList()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java new file mode 100644 index 000000000..f747148a8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -0,0 +1,114 @@ +/* + * 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.loot; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.framework.PlacedObject; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.engine.object.loot.IrisVanillaLootTable; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemDrop; +import com.volmit.service.Loot; +import com.volmit.world.PackWorld; + +import java.util.List; + +/** + * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the + * dimension, region and biomes at its column, and the items each table gives. Draws are deterministic per container, so + * a container always holds the same loot. + */ +public final class LootGiving implements Loot { + @Override + public List tables(PackWorld world, Site site) { + Engine engine = engine(world); + int x = site.position().x(); + int z = site.position().z(); + int relativeY = site.position().y(); + RNG rng = LootResolver.containerRng(lootSeed(engine), x, relativeY + engine.getMinHeight(), z); + + List tables = new KList<>(); + boolean objectLootDefined = site.nativeLootDefined(); + IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z); + if (placement != null) { + objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty(); + IrisLootTable table = placement.getTable(platformState(site), engine.getData(), rng); + if (table != null) { + tables.add(table); + if (placement.isOverrideGlobalLoot()) { + return sourcesOf(engine, site, List.of(table)); + } + } + } + + LootTables.resolveEnvironmentSources(tables, engine, rng, x, relativeY, z, objectLootDefined, table -> table); + return sourcesOf(engine, site, tables); + } + + @Override + public List items(PackWorld world, Site site, String key) { + Engine engine = engine(world); + IrisLootTable table = engine.getData().getLootLoader().load(key); + if (table == null) { + return List.of(); + } + int worldY = site.position().y() + engine.getMinHeight(); + return new LootItems(world.resources().items(), site.debug()) + .draw(table, lootSeed(engine), site.position().x(), worldY, site.position().z()); + } + + private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) { + PlacedObject placed = engine.getObjectPlacement(x, relativeY, z); + return placed == null ? null : placed.getPlacement(); + } + + private static List sourcesOf(Engine engine, Site site, List tables) { + int worldY = site.position().y() + engine.getMinHeight(); + List sources = new KList<>(); + for (IrisLootTable table : tables) { + if (table instanceof IrisVanillaLootTable vanilla) { + long seed = LootTables.seed(lootSeed(engine), vanilla, site.position().x(), worldY, site.position().z()); + sources.add(new PlatformTable(vanilla.getLootTableKey(), seed)); + continue; + } + if (table != null && table.getLoadKey() != null) { + sources.add(new Table(table.getLoadKey())); + } + } + return sources; + } + + private static PlatformBlockState platformState(Site site) { + return IrisPlatforms.get().registries().block(site.container().key()); + } + + private static long lootSeed(Engine engine) { + return engine.getSeedManager().getLoot(); + } + + private static Engine engine(PackWorld world) { + return IrisPackWorld.of(world).engine(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java new file mode 100644 index 000000000..d1b3247d5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -0,0 +1,151 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.object.entity.IrisAttributeModifier; +import art.arcane.iris.engine.object.loot.IrisEnchantment; +import art.arcane.iris.engine.object.loot.InventorySlotType; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; +import com.volmit.item.ItemEnchantment; +import com.volmit.item.ItemRegistry; + +import java.util.ArrayList; +import java.util.List; +import java.util.OptionalInt; + +/** + * Turns loot entries into the items they give: every random choice is made here, in the order Iris always made them + * (amount, enchantments, attribute modifiers, damage), so that a container's loot stays what it was. What the platform + * must do with the result is the host's. + */ +public final class LootItems { + private static final String AIR = "air"; + private static final String MINECRAFT_PREFIX = "minecraft:"; + private static final int MIN_AMOUNT = 1; + + private final ItemRegistry items; + private final boolean debug; + + /** @param debug whether the items say where they came from */ + public LootItems(ItemRegistry items, boolean debug) { + this.items = items; + this.debug = debug; + } + + /** + * The items {@code table} gives at the spot {@code x}, {@code y}, {@code z} (world coordinates): picks entries + * from the table's own random stream until it has the number of items the table asks for or runs out of tries. + */ + public List draw(IrisLootTable table, long lootSeed, int x, int y, int z) { + List drops = new ArrayList<>(); + List entries = table.getLoot(); + if (entries.isEmpty() || table.getMaxTries() <= 0) { + return drops; + } + + RNG rng = LootTables.rng(lootSeed, table, x, y, z); + int wanted = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked())); + int tries = 0; + while (drops.size() < wanted && tries++ < table.getMaxTries()) { + int index = rng.nextInt(entries.size()); + IrisLoot entry = entries.get(index); + if (entry == null || entry.getSlotTypes() != InventorySlotType.STORAGE) { + continue; + } + ItemDrop drop = drawEntry(entry, table, rng, lootSeed, index, x, y, z); + if (drop != null) { + drops.add(drop); + } + } + return drops; + } + + /** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */ + public ItemDrop give(IrisLoot entry, RNG rng) { + return resolve(entry, rng, null); + } + + private ItemDrop drawEntry(IrisLoot entry, IrisLootTable table, RNG rng, long lootSeed, int index, int x, int y, int z) { + long combinedRarity = LootResolver.combinedRarity(entry.getRarity(), table.getRarity()); + if (!LootTables.spatialOneIn(lootSeed, table, index, x, y, z, combinedRarity)) { + return null; + } + return resolve(entry, rng, table); + } + + private ItemDrop resolve(IrisLoot entry, RNG rng, IrisLootTable table) { + String type = entry.getTypeKey(); + OptionalInt maxDurability = items.maxDurability(type); + if (maxDurability.isEmpty() || isAir(type)) { + return null; + } + + int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.getMinAmount(), entry.getMaxAmount())); + List enchantments = drawEnchantments(entry, rng); + List attributes = drawAttributes(entry, rng); + Double damage = maxDurability.getAsInt() > 0 ? 1D - rng.d(entry.getMinDurability(), entry.getMaxDurability()) : null; + return new ItemDrop(type, amount, entry.getDisplayName(), entry.getLore(), enchantments, attributes, + entry.isUnbreakable(), entry.getItemFlags(), entry.getCustomModel(), damage, entry.getLeatherColor(), + entry.getDyeColorKey(), entry.getCustomNbt(), debug ? sourceOf(entry, table) : null); + } + + private static List drawEnchantments(IrisLoot entry, RNG rng) { + List enchantments = new ArrayList<>(); + for (IrisEnchantment enchantment : entry.getEnchantments()) { + String key = enchantment.getEnchantment(); + if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.getChance()) { + continue; + } + enchantments.add(new ItemEnchantment(key, Math.max(1, enchantment.getLevel(rng)))); + } + return enchantments; + } + + private static List drawAttributes(IrisLoot entry, RNG rng) { + List attributes = new ArrayList<>(); + for (IrisAttributeModifier modifier : entry.getAttributes()) { + if (rng.nextDouble() >= modifier.getChance()) { + continue; + } + String attribute = modifier.getAttribute(); + if (attribute == null || attribute.isBlank()) { + continue; + } + attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng))); + } + return attributes; + } + + private static ItemDrop.Source sourceOf(IrisLoot entry, IrisLootTable table) { + if (table == null) { + return new ItemDrop.Source(null, 0, entry.getRarity()); + } + return new ItemDrop.Source(table.getName(), table.getRarity(), entry.getRarity()); + } + + private static boolean isAir(String type) { + String key = type.startsWith(MINECRAFT_PREFIX) ? type.substring(MINECRAFT_PREFIX.length()) : type; + return AIR.equalsIgnoreCase(key); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java new file mode 100644 index 000000000..ff32bc104 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -0,0 +1,50 @@ +/* + * 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.loot; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.service.BlockDrops; +import com.volmit.service.Loot; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:loot}: the loot tables of the pack and the items they and the block drops of the dimension, regions + * and biomes give. It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through + * {@link BlockDrops} when a player breaks a block. + */ +public final class LootModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:loot", "Loot", VERSION); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerService(Loot.class, new LootGiving()); + registry.registerService(BlockDrops.class, new BlockDropping()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java new file mode 100644 index 000000000..021c3c2b1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -0,0 +1,162 @@ +/* + * 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.loot; + +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.object.loot.IrisLootMode; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.loot.IrisLootTable; +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 art.arcane.volmlib.util.math.RNG; + +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +/** + * Which loot tables a place in the world draws from, and the random streams that draw from them: the part of loot + * that reads the pack's tables, loot references and layout. The streams themselves are + * {@link LootResolver}'s; here a table is named by its {@linkplain #identity identity}. + */ +public final class LootTables { + private LootTables() { + } + + /** What names a table in the random streams: its key, else its name. */ + public static String identity(IrisLootTable table) { + if (table == null) { + return ""; + } + String loadKey = table.getLoadKey(); + if (loadKey != null && !loadKey.isBlank()) { + return loadKey; + } + String name = table.getName(); + return name == null ? "" : name; + } + + public static RNG rng(long lootSeed, IrisLootTable table, int x, int y, int z) { + return LootResolver.tableRng(lootSeed, identity(table), x, y, z); + } + + public static long seed(long lootSeed, IrisLootTable table, int x, int y, int z) { + return LootResolver.tableSeed(lootSeed, identity(table), x, y, z); + } + + public static boolean spatialOneIn(long lootSeed, IrisLootTable table, int entryIndex, int x, int y, int z, long rarity) { + return LootResolver.spatialOneIn(lootSeed, identity(table), entryIndex, x, y, z, rarity); + } + + /** + * Adds the tables of the dimension, the region, the surface biome and (below the surface) the cave biome at a + * column to {@code sources}, as their loot references say, then scales their number by the areas' multipliers. + * {@code mapper} turns a table into the caller's own source; a null result skips it. + */ + public static void resolveEnvironmentSources( + List sources, + Engine engine, + RNG rng, + int x, + int relativeY, + int z, + boolean objectLootDefined, + Function mapper + ) { + IrisRegion region = engine.getComplex().getRegionStream().get(x, z); + IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z); + double terrainHeight = engine.getComplex().getHeightStream().get(x, z); + IrisBiome contextualBiome = relativeY < terrainHeight + ? engine.getCaveBiome(x, relativeY, z) + : surfaceBiome; + if (contextualBiome == null) { + contextualBiome = surfaceBiome; + } + + boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome); + double multiplier = engine.getDimension().getLoot().getMultiplier() + * region.getLoot().getMultiplier() + * surfaceBiome.getLoot().getMultiplier(); + if (distinctContextualBiome) { + multiplier *= contextualBiome.getLoot().getMultiplier(); + } + + boolean fallback = !objectLootDefined; + injectReference(sources, engine.getDimension().getLoot(), engine, mapper, fallback); + injectReference(sources, region.getLoot(), engine, mapper, fallback); + injectReference(sources, surfaceBiome.getLoot(), engine, mapper, fallback); + if (distinctContextualBiome) { + injectReference(sources, contextualBiome.getLoot(), engine, mapper, fallback); + } + LootResolver.scaleSources(sources, multiplier, rng); + } + + /** Adds {@code additions} to {@code sources} the way {@code mode} says; {@code fallback} is whether nothing else defined a table. */ + public static void injectSources( + List sources, + List additions, + IrisLootMode mode, + boolean fallback + ) { + if (mode == IrisLootMode.FALLBACK && !fallback) { + return; + } + if (mode == IrisLootMode.CLEAR) { + sources.clear(); + return; + } + if (mode == IrisLootMode.REPLACE) { + sources.clear(); + } + sources.addAll(additions); + } + + static boolean sameBiome(IrisBiome first, IrisBiome second) { + if (first == second) { + return true; + } + if (first == null || second == null) { + return false; + } + return Objects.equals(first.getLoadKey(), second.getLoadKey()); + } + + private static void injectReference( + List sources, + IrisLootReference reference, + Engine engine, + Function mapper, + boolean fallback + ) { + KList tables = reference.getLootTables(engine.getComplex()); + KList additions = new KList<>(); + for (IrisLootTable table : tables) { + if (table == null) { + continue; + } + T source = mapper.apply(table); + if (source != null) { + additions.add(source); + } + } + injectSources(sources, additions, reference.getMode(), fallback); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index 2f002ae1e..b022b03f3 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -1,3 +1,21 @@ +/* + * 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.core.modules.IrisPackWorld; diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java index fa2aa2f57..c3c26608c 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java @@ -22,6 +22,7 @@ import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.Required; @@ -33,8 +34,9 @@ import lombok.Data; import lombok.NoArgsConstructor; import art.arcane.iris.spi.PlatformBlockState; import lombok.experimental.Accessors; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; +import com.volmit.item.ItemDrop; + +import java.util.List; @Snippet("block-drops") @Accessors(chain = true) @@ -43,7 +45,7 @@ import org.bukkit.inventory.ItemStack; @Desc("Represents a block drop list") @Data public class IrisBlockDrops { - private final transient AtomicCache> data = new AtomicCache<>(); + private final transient AtomicCache> data = new AtomicCache<>(); @Required @ArrayType(min = 1, type = IrisBlockData.class) @Desc("The blocks that drop loot") @@ -58,23 +60,23 @@ public class IrisBlockDrops { @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") private boolean replaceVanillaDrops = false; - public boolean shouldDropFor(BlockData data, IrisData rdata) { - KList list = this.data.aquire(() -> { - KList b = new KList<>(); + public boolean shouldDropFor(PlatformBlockState broken, IrisData rdata) { + KList list = this.data.aquire(() -> { + KList b = new KList<>(); for (IrisBlockData i : getBlocks()) { PlatformBlockState state = i.getBlockData(rdata); if (state != null) { - b.add((BlockData) state.nativeHandle()); + b.add(state); } } return b.removeDuplicates(); }); - for (BlockData i : list) { - if (exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) { + for (PlatformBlockState i : list) { + if (exactBlocks ? i.key().equals(broken.key()) : materialOf(i).equals(materialOf(broken))) { return true; } } @@ -82,11 +84,22 @@ public class IrisBlockDrops { return false; } - public void fillDrops(boolean debug, KList d) { + /** Adds the items of the drops that pass their rarity to {@code d}. */ + public void fillDrops(LootItems items, List d) { for (IrisLoot i : getDrops()) { - if (LootResolver.oneIn(RNG.r, i.getRarity())) { - d.add(i.get(debug, RNG.r)); + if (!LootResolver.oneIn(RNG.r, i.getRarity())) { + continue; + } + ItemDrop drop = items.give(i, RNG.r); + if (drop != null) { + d.add(drop); } } } + + private static String materialOf(PlatformBlockState state) { + String key = state.key(); + int properties = key.indexOf('['); + return properties < 0 ? key : key.substring(0, properties); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java index 8ad144f9c..30251684e 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java @@ -184,7 +184,7 @@ public class IrisLoot { public ItemStack get(boolean debug, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, int x, int y, int z) { long combinedRarity = LootResolver.combinedRarity(rarity, table.getRarity()); - if (!LootResolver.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { + if (!art.arcane.iris.engine.loot.LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { return null; } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java index ba9342ca5..9b85aac40 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java @@ -80,7 +80,7 @@ public class IrisLootTable extends IrisRegistrant { return lootf; } - RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z); + RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); int m = 0; int c = 0; int mx = Math.max(0, LootResolver.inclusive(rng, getMinPicked(), getMaxPicked())); diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java index c66c624f1..e61521405 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java @@ -78,7 +78,7 @@ public class IrisVanillaLootTable extends IrisLootTable { IrisLogging.warn("Unknown vanilla loot table " + lootTableKey); return new KList<>(); } - RNG rng = LootResolver.tableRng(lootSeed, this, x, y, z); + RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); return new KList<>(table.populateLoot(rng, new LootContext.Builder(new Location(world, x, y, z)).build())); } From c4c8fa69d3921dc2ab5e56ed237274693eb4f0a2 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:04:03 +0200 Subject: [PATCH 033/139] ObjectPlaceMode, AnchorSampling and StiltShape move to art.arcane.iris.builtin.anchor with IrisApi annotations --- .../placement => builtin/anchor}/AnchorSampling.java | 4 ++-- .../anchor}/ObjectPlaceMode.java | 12 ++++++------ .../placement => builtin/anchor}/StiltShape.java | 4 ++-- .../iris/engine/framework/IrisStructureLocator.java | 2 +- .../structure/NativeReplacementValidation.java | 2 +- .../mantle/components/FloatingObjectPlacing.java | 2 +- .../iris/engine/mantle/components/ObjectPlacing.java | 2 +- .../engine/mantle/components/StructurePlacing.java | 2 +- .../iris/engine/object/placement/AnchorModule.java | 1 + .../iris/engine/object/placement/BlocksModule.java | 1 + .../engine/object/placement/IrisObjectPlacement.java | 1 + .../engine/object/placement/IrisObjectVacuum.java | 7 ++----- .../iris/engine/object/placement/PrepareModule.java | 1 + .../engine/object/placement/PreparedPlacement.java | 1 + .../iris/engine/object/placement/StiltModule.java | 1 + .../iris/engine/object/placement/VacuumModule.java | 1 + .../iris/engine/object/placement/ValidateModule.java | 1 + .../iris/engine/object/placement/WorldVolume.java | 1 + .../engine/object/procedural/coral/IrisCoral.java | 2 +- .../object/procedural/crystal/IrisCrystal.java | 2 +- .../object/procedural/formation/IrisFormation.java | 2 +- .../engine/object/procedural/fungi/IrisFungus.java | 2 +- .../iris/engine/object/procedural/ruin/IrisRuin.java | 2 +- .../object/procedural/tree/IrisProceduralTree.java | 2 +- .../iris/engine/object/structure/IrisStructure.java | 2 +- .../object/terrain/carving/IrisCaveProfile.java | 2 +- .../terrain/floating/IrisFloatingChildBiomes.java | 2 +- 27 files changed, 35 insertions(+), 29 deletions(-) rename src/main/java/art/arcane/iris/{engine/object/placement => builtin/anchor}/AnchorSampling.java (95%) rename src/main/java/art/arcane/iris/{engine/object/placement => builtin/anchor}/ObjectPlaceMode.java (96%) rename src/main/java/art/arcane/iris/{engine/object/placement => builtin/anchor}/StiltShape.java (94%) diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java b/src/main/java/art/arcane/iris/builtin/anchor/AnchorSampling.java similarity index 95% rename from src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java rename to src/main/java/art/arcane/iris/builtin/anchor/AnchorSampling.java index 5f7b7d572..bd4c53a9d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorSampling.java +++ b/src/main/java/art/arcane/iris/builtin/anchor/AnchorSampling.java @@ -16,10 +16,10 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.anchor; /** How a placement mode finds the height of an object placed without a requested height. */ -enum AnchorSampling { +public enum AnchorSampling { /** The surface at the object's center, or the floor of the cave it is placed in. */ CENTER, /** The highest surface under any column of the object. */ diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java b/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java similarity index 96% rename from src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java rename to src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java index af6f6a335..b57e3d7c1 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlaceMode.java +++ b/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.anchor; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Object Place modes are useful for positioning objects just right. The default value is CENTER_HEIGHT.") @@ -115,16 +115,16 @@ public enum ObjectPlaceMode { } /** How a placement without a requested height finds one. */ - AnchorSampling anchor() { + public AnchorSampling anchor() { return anchor; } /** The stilt this mode grows under or above the object. */ - StiltShape stilt() { + public StiltShape stilt() { return stilt; } - boolean isVacuum() { - return IrisObjectVacuum.isVacuumMode(this); + public boolean isVacuum() { + return this == VACUUM || this == VACUUM_HIGH || this == VACUUM_FAST || this == VACUUM_ORGANIC || this == VACUUM_WAVY; } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java b/src/main/java/art/arcane/iris/builtin/anchor/StiltShape.java similarity index 94% rename from src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java rename to src/main/java/art/arcane/iris/builtin/anchor/StiltShape.java index 121a71cb0..1eef735f5 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltShape.java +++ b/src/main/java/art/arcane/iris/builtin/anchor/StiltShape.java @@ -16,10 +16,10 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.anchor; /** What a placement mode grows between the object and the ground or ceiling. */ -enum StiltShape { +public enum StiltShape { NONE, /** Repeats the bottom layer straight down to the surface. */ STRAIGHT, diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index a3e1672bb..d3e824f49 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; @@ -34,7 +35,6 @@ import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.IrisStructureTerrain; import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; 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 index 22cc602f9..21c83a39b 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.framework.structure; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.core.pack.PackValidationIo; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; import com.volmit.validation.Problem; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 249c80a13..5878a5282 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; @@ -33,7 +34,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 80cbed186..5de9e197d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; @@ -44,7 +45,6 @@ import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; 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 index c09f31c7a..fd02c5d15 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.mantle.components; +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; @@ -34,7 +35,6 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index 4a1afbbbd..6b40570a3 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.AnchorHeight; import art.arcane.iris.core.modules.IrisPlacement; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index dc7dd6727..f9abd4bb8 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.blocks.ObjectReplace; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; 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 index 20673ee8c..08c9f9d24 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java index e12f4ced3..101f9215d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.vacuum.VacuumSettings; public final class IrisObjectVacuum { @@ -30,11 +31,7 @@ public final class IrisObjectVacuum { } public static boolean isVacuumMode(ObjectPlaceMode mode) { - return mode == ObjectPlaceMode.VACUUM - || mode == ObjectPlaceMode.VACUUM_HIGH - || mode == ObjectPlaceMode.VACUUM_FAST - || mode == ObjectPlaceMode.VACUUM_ORGANIC - || mode == ObjectPlaceMode.VACUUM_WAVY; + return mode != null && mode.isVacuum(); } public static int resolveRadius(ObjectPlaceMode mode, VacuumSettings settings) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 58e57bb77..00b911609 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.prepare.SlopeClip; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.prepare.AxisRotationClamp; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java index 3aeed4175..b8179078a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.math.IrisBlockVector; import art.arcane.iris.util.project.noise.CNG; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 6c9cbf679..679b55010 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.StiltShape; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.IrisStages; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 95553141d..b876b78ea 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.IrisStages; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 815d4712d..3a3b5a815 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.validate.ObjectLimit; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java index fca0d968c..918216a59 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.core.modules.IrisPlacement; /** diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java index 1157a89d5..e9de0ef73 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.coral; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java index 994b478a8..7cb60c2bb 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.crystal; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java index b8506ff04..810fb3b50 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.formation; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java index 990345198..66e6a6e92 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.fungi; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java index c7f4fed30..004da5435 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.ruin; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java index 0f6c635e3..2b7d32351 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; 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 index b30ef0ced..609939ce1 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.object.structure; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisObjectLoot; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; 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; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java index 4cbd9c7ab..04db427b4 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java @@ -1,9 +1,9 @@ package art.arcane.iris.engine.object.terrain.carving; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.IrisStyledRange; import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java index d24c188f0..151f17205 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.terrain.floating; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlaceMode; import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; From e94d8e00f7867a63dfbb38254f69ee1d4ae37b50 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:05:41 +0200 Subject: [PATCH 034/139] iris:objects grows saplings into trees and names the objects it places as trees (TreeGrowing) --- .../mantle/components/ObjectModule.java | 4 +- .../engine/mantle/components/TreeGrowing.java | 249 ++++++++++++++++++ 2 files changed, 252 insertions(+), 1 deletion(-) create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index c39b696bf..99796dc12 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -27,6 +27,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; +import com.volmit.service.SaplingGrowth; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; @@ -35,7 +36,7 @@ import com.volmit.stage.StageGraph; * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work * done by {@link ObjectPlacing}, one per engine runtime. Its reach is the pack's largest object placement. It tells * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the - * object search and studio tools. + * object search and studio tools, and grows the trees of saplings ({@link TreeGrowing}). */ public final class ObjectModule implements IrisModule { private static final String VERSION = "built-in"; @@ -53,6 +54,7 @@ public final class ObjectModule implements IrisModule { @Override public void register(FeatureRegistry registry) { registry.registerService(ObjectsAt.class, new ObjectLocating()); + registry.registerService(SaplingGrowth.class, new TreeGrowing()); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java new file mode 100644 index 000000000..1bcfe3226 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -0,0 +1,249 @@ +/* + * 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.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.placement.IObjectPlacer; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.IrisTreeSize; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.IrisTreeModes; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.placement.PlacedBlock; +import com.volmit.service.SaplingGrowth; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; +import org.bukkit.TreeType; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * How {@code iris:objects} grows trees: when a sapling grows, the tree comes from the tree placements of the biome and + * region at the sapling (the region's too when the dimension uses all of them), placed like any object but into a list + * of blocks the host then places. The same placements tell which objects are trees. + */ +public final class TreeGrowing implements SaplingGrowth { + private static final IrisTreeSize SAPLING_SIZE = new IrisTreeSize(1, 1); + + @Override + public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { + Engine engine = IrisPackWorld.of(world).engine(); + if (!engine.getDimension().getTreeSettings().isEnabled()) { + return Optional.empty(); + } + + IrisObjectPlacement placement = pickPlacement(engine, sapling); + if (placement == null) { + return Optional.empty(); + } + + IrisData data = engine.getData(); + IrisObject object = data.getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); + GrowthPlacer placer = new GrowthPlacer(engine, surroundings); + BlockPosition center = sapling.center(); + object.place(center.x(), center.y() + object.getH() / 2, center.z(), placer, placement, RNG.r, data); + return Optional.of(new Growth(object.getLoadKey(), placer.placed())); + } + + @Override + public TreeObjects treeObjects(PackWorld world) { + Engine engine = IrisPackWorld.of(world).engine(); + Set objects = new HashSet<>(); + Set procedural = new HashSet<>(); + + for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { + if (region != null) { + collectPlacements(region.getObjects(), objects); + collectProceduralTrees(region.getProceduralObjects(), procedural); + } + } + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { + if (biome != null) { + collectPlacements(biome.getObjects(), objects); + collectProceduralTrees(biome.getProceduralObjects(), procedural); + } + } + return new TreeObjects(objects, procedural); + } + + /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ + private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { + TreeType species = TreeType.valueOf(sapling.species()); + KList placements = new KList<>(); + boolean useAll = engine.getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); + + BlockPosition at = sapling.at(); + placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), species)); + if (useAll || placements.isEmpty()) { + placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), species)); + } + return placements.isNotEmpty() ? placements.getRandom() : null; + } + + private static KList matching(KList objects, TreeType species) { + KList matches = new KList<>(); + for (IrisObjectPlacement placement : objects) { + if (placement.matches(SAPLING_SIZE, species)) { + matches.add(placement); + } + } + return matches; + } + + private static void collectPlacements(Iterable placements, Set objectKeys) { + if (placements == null) { + return; + } + for (IrisObjectPlacement placement : placements) { + if (placement == null + || placement.getTrees() == null + || placement.getTrees().isEmpty() + || placement.getPlace() == null) { + continue; + } + for (String objectKey : placement.getPlace()) { + if (objectKey != null && !objectKey.isBlank()) { + objectKeys.add(objectKey); + } + } + } + } + + private static void collectProceduralTrees(IrisProceduralObjects proceduralObjects, Set objectKeys) { + if (proceduralObjects == null || proceduralObjects.getTrees() == null) { + return; + } + for (IrisProceduralTree tree : proceduralObjects.getTrees()) { + if (tree == null || tree.getName() == null || tree.getName().isBlank()) { + continue; + } + int variants = Math.max(1, tree.getVariants()); + for (int index = 0; index < variants; index++) { + objectKeys.add(tree.getVariantLoadKey(index)); + } + } + } + + /** Places an object into a list of blocks, reading the world around the sapling through the host. */ + private static final class GrowthPlacer implements IObjectPlacer { + private final Engine engine; + private final Surroundings surroundings; + private final PlatformBlockStates states = new PlatformBlockStates(key -> IrisPlatforms.get().registries().block(key)); + private final List placed = new ArrayList<>(); + + private GrowthPlacer(Engine engine, Surroundings surroundings) { + this.engine = engine; + this.surroundings = surroundings; + } + + private List placed() { + return placed; + } + + @Override + public int getHighest(int x, int z, IrisData data) { + return surroundings.highest(x, z, false); + } + + @Override + public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { + return surroundings.highest(x, z, ignoreFluid); + } + + @Override + public void set(int x, int y, int z, PlatformBlockState state) { + placed.add(new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), Optional.empty())); + } + + @Override + public PlatformBlockState get(int x, int y, int z) { + BlockState block = surroundings.blockAt(x, y, z); + return states.toPlatform(block); + } + + @Override + public boolean isPreventingDecay() { + return true; + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return isSolid(x, y, z); + } + + @Override + public boolean isSolid(int x, int y, int z) { + return get(x, y, z).isSolid(); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public int getFluidHeight() { + return engine.getDimension().getFluidHeight(); + } + + @Override + public boolean isDebugSmartBore() { + return false; + } + + @Override + public void setTile(int xx, int yy, int zz, TileData tile) { + } + + @Override + public void setData(int xx, int yy, int zz, T data) { + } + + @Override + public T getData(int xx, int yy, int zz, Class t) { + return null; + } + + @Override + public Engine getEngine() { + return engine; + } + } +} From 8a6bc5bfc0dce7747f292382be4c1b6a93ba572a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:09:38 +0200 Subject: [PATCH 035/139] importedStructures becomes iris:structure settings; the native structure planner moves into the module's vanilla hook builtin.structure: StructureSettings (feature iris:structure, target DIMENSION, the JSON of IrisImportedStructureControl: disabled, disabledExact, undergroundYShift, datapackOverrides, frequencyOverrides, adjustments), StructureSetFrequency, StructureAdjustment, IrisApi types only (fits are StructureTerrain, StructureStilts, YBand). ImportedStructures reads them: disables (family and exact keys), adjustment per structure and underground step, setup (frequencies, protecting vanilla definitions), matchesKey. NativeStartPlanner is the planner that was core's (selectSource, resolveBaseY, priority by placementIdentity, same RNG domain). StructureVanillaHook answers rule (REPLACE/BLOCK/ALSO_PLACE from placements and settings), adjustment, starts (planner plans as VanillaStructureStarts, heights above the bottom) and setup; StructureModule registers it and its settings. Deleted: IrisDimension.importedStructures, IrisImportedStructureControl, IrisVanillaStructureAdjustment, IrisStructureSetFrequencyOverride, RegistryListVanillaStructureSet, RegistryListVanillaStructure.prefixes. --- .../structure/StructureAdjustment.java} | 93 +++++---- .../structure/StructureSetFrequency.java} | 40 ++-- .../builtin/structure/StructureSettings.java | 111 +++++++++++ .../framework/IrisStructureLocator.java | 9 +- .../structure/ImportedStructures.java | 145 ++++++++++++++ .../structure/NativeStartPlanner.java | 174 +++++++++++++++++ .../structure/StructureVanillaHook.java | 115 +++++++++++ .../mantle/components/StructureModule.java | 27 +-- .../RegistryListVanillaStructure.java | 9 - .../RegistryListVanillaStructureSet.java | 33 ---- .../IrisImportedFeatureControl.java | 4 +- .../vanilla/IrisImportedStructureControl.java | 184 ------------------ .../object/world/dimension/IrisDimension.java | 3 - 13 files changed, 643 insertions(+), 304 deletions(-) rename src/main/java/art/arcane/iris/{engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java => builtin/structure/StructureAdjustment.java} (61%) rename src/main/java/art/arcane/iris/{engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java => builtin/structure/StructureSetFrequency.java} (67%) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java b/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java similarity index 61% rename from src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java rename to src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java index 3104537a5..20c5b473a 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisVanillaStructureAdjustment.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,32 +16,28 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.structure.vanilla; +package art.arcane.iris.builtin.structure; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureYBand; -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.RegistryListVanillaStructure; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.vanilla.StructureStilts; +import com.volmit.vanilla.StructureTerrain; +import com.volmit.vanilla.YBand; -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor +import java.util.List; +import java.util.Optional; + +/** One entry of {@link StructureSettings#adjustments()}: how the platform's own starts of the structures it matches are moved and fitted. */ @Desc("A per-structure adjustment applied to vanilla, mod, and datapack structures that still generate natively (those NOT suppressed by an Iris 'structures' placement). Vertical shifts move the structure start, pieces, bounds, and jigsaw metadata together before references and placement. Intersecting trees are cleared automatically inside structure piece envelopes; optional postprocessing can build palette-driven foundation columns.") -@Data -public class IrisVanillaStructureAdjustment { - @ArrayType(type = String.class, min = 1) - @RegistryListVanillaStructure(prefixes = true) +public final class StructureAdjustment { + @MinItems(1) + @Ref(Reference.STRUCTURE_PREFIX) @Desc("Structure keys this adjustment applies to, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' adjusts every village variant and 'minecraft:ruined_portal' adjusts every ruined portal. Empty matches nothing.") - private KList match = new KList<>(); + private List match = List.of(); @MinNumber(-512) @MaxNumber(512) @@ -49,23 +45,52 @@ public class IrisVanillaStructureAdjustment { private int yShift = 0; @Desc("Optional absolute world Y band. The structure is relocated so its vertical midpoint lands inside the band, deterministically from its start chunk and clamped to the world's build bounds. Precedence: preserveSourceY wins over yBand, and yBand wins over both yShift and Iris burial repositioning. Structures with a fixed vanilla alignment (ocean monument sea level, desert and jungle pyramid surface fit) ignore it.") - private IrisStructureYBand yBand = null; + private YBand yBand = null; @Desc("When true, skip Iris burial repositioning so the structure keeps the Y its own vanilla placement chose. Underground structures are otherwise pushed below the lowest solid column across their whole footprint, which hides terrain-aware structures such as mineshafts that intentionally breach cliffs and surfaces. Vertical shifts still apply on top of the preserved Y: this dimension's undergroundYShift plus every matching adjustment's yShift.") private boolean preserveSourceY = false; @Desc("Optional foundation columns placed beneath the native structure piece bases after placement.") - private IrisStructureStiltSettings stilt = null; + private StructureStilts stilt = null; @Desc("Optional terrain integration override. VACUUM raises surface terrain from processed solid rigid-template foundations at or below each authored ground plane with a 12-block falloff without lowering existing ground. BORE and FORCE_CARVE clear every intersecting chunk before native pieces are placed, while ENCASE fills it with solid blocks instead. Left unset, SOURCE replays the registered structure's authored terrain adaptation, including surface fitting, burial, and encapsulation.") - private IrisStructureTerrain terrain = null; + private StructureTerrain terrain = null; - public boolean matches(String key) { - for (String entry : match) { - if (IrisImportedStructureControl.matchesKey(entry, key)) { - return true; - } - } - return false; + public StructureAdjustment() { + } + + public StructureAdjustment(List match, int yShift, YBand yBand, boolean preserveSourceY, StructureStilts stilt, + StructureTerrain terrain) { + this.match = List.copyOf(match); + this.yShift = yShift; + this.yBand = yBand; + this.preserveSourceY = preserveSourceY; + this.stilt = stilt; + this.terrain = terrain; + } + + /** Family patterns of the structures this adjustment applies to. */ + public List match() { + return StructureSettings.listOrEmpty(match); + } + + public int yShift() { + return yShift; + } + + public Optional yBand() { + return Optional.ofNullable(yBand); + } + + public boolean preserveSourceY() { + return preserveSourceY; + } + + public Optional stilt() { + return Optional.ofNullable(stilt); + } + + public Optional terrain() { + return Optional.ofNullable(terrain); } } diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java b/src/main/java/art/arcane/iris/builtin/structure/StructureSetFrequency.java similarity index 67% rename from src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java rename to src/main/java/art/arcane/iris/builtin/structure/StructureSetFrequency.java index 516d36d28..b273697d7 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisStructureSetFrequencyOverride.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureSetFrequency.java @@ -16,24 +16,18 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.structure.vanilla; +package art.arcane.iris.builtin.structure; -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.RegistryListVanillaStructureSet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor +/** One entry of {@link StructureSettings#frequencyOverrides()}: how often the structures of one platform structure set start. */ @Desc("An exact registered structure-set frequency multiplier. Iris retains the set's structures, weights, biome eligibility, placement algorithm, salt, exclusion zone, starts, processors, mobs, loot, and locate behavior while scaling only its native placement density.") -@Data -public class IrisStructureSetFrequencyOverride { - @RegistryListVanillaStructureSet +public final class StructureSetFrequency { + @Ref(Reference.STRUCTURE_SET) @Desc("Exact registered structure-set key, for example 'minecraft:nether_complexes'. Structure keys such as 'minecraft:fortress' are not valid here.") private String structureSet = ""; @@ -41,4 +35,20 @@ public class IrisStructureSetFrequencyOverride { @MaxNumber(16) @Desc("Requested placement-density multiplier. Random-spread sets scale their placement frequency first and then their integer chunk spacing; integer spacing and separation constraints can make the realized increase slightly lower or higher. The default 1 leaves the registered placement unchanged.") private double multiplier = 1D; + + public StructureSetFrequency() { + } + + public StructureSetFrequency(String structureSet, double multiplier) { + this.structureSet = structureSet; + this.multiplier = multiplier; + } + + public String structureSet() { + return structureSet == null ? "" : structureSet; + } + + public double multiplier() { + return multiplier; + } } diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java new file mode 100644 index 000000000..4ab5886cc --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java @@ -0,0 +1,111 @@ +/* + * 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.builtin.structure; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +import java.util.Collections; +import java.util.List; + +/** + * How a dimension treats the platform's own structures (vanilla, data pack and mod structures), written as + * {@code "iris:structure": {"disabled": [...], "adjustments": [...]}}: which ones it disables, how the ones that still + * generate are moved and fitted, how often structure sets start, and whether installed data packs may replace the + * platform's own definitions. The JSON packs wrote as {@code importedStructures}. IrisApi types only. + */ +@Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris structure list ' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") +@Feature(id = "iris:structure", name = "Structures", targets = Target.DIMENSION) +public final class StructureSettings implements IrisFeature { + @MinItems(1) + @Ref(Reference.STRUCTURE_PREFIX) + @Desc("Structure keys to deny explicitly, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' disables every village variant and 'minecraft:ruined_portal' disables every ruined portal. Every key not matched here remains enabled.") + private List disabled = List.of(); + + @MinItems(1) + @Ref(Reference.STRUCTURE) + @Desc("Exact structure keys to deny after trimming and case normalization. Unlike 'disabled', entries never match key families, so 'minecraft:ruined_portal' does not disable 'minecraft:ruined_portal_nether'.") + private List disabledExact = List.of(); + + @MinNumber(-512) + @MaxNumber(512) + @Desc("Vertical block offset applied only to UNDERGROUND vanilla structures (the UNDERGROUND_STRUCTURES, UNDERGROUND_DECORATION, and STRONGHOLDS generation steps: strongholds, trial chambers, mineshafts, ancient cities, etc.). Surface structures (villages, outposts, etc.) are never shifted. Use a negative value to push deep structures lower when your dimension's sea/terrain level differs from vanilla's (e.g. -64 if you lowered the fluid height to 0). 0 = no shift.") + private int undergroundYShift = 0; + + @Desc("Controls whether ingested datapacks may replace minecraft-namespaced structure definitions, sets, pools, and templates. When false, those overrides are stripped from installed datapack copies so vanilla definitions stay intact. Non-minecraft structures from datapacks and mods remain governed by disabled because namespace alone cannot identify their origin. Resolved globally across loaded packs: if any dimension sets this false, minecraft-namespaced overrides are stripped from every installed datapack copy.") + private boolean datapackOverrides = true; + + @MinItems(1) + @Desc("Exact registered structure-set frequency overrides for native generation. The last entry for a normalized structure-set key wins. These do not convert native structures into Iris placements and affect only newly generated chunks.") + private List frequencyOverrides = List.of(); + + @MinItems(1) + @Desc("Per-structure adjustments applied to vanilla, mod, and datapack structures that still generate natively. Vertical shifts from every matching entry stack. A matching preserveSourceY option disables Iris burial repositioning for that structure. The last matching entry with stilt settings controls foundation columns, and likewise for terrain and yBand settings. A structure suppressed by an Iris placement is unaffected.") + private List adjustments = List.of(); + + public StructureSettings() { + } + + public StructureSettings(List disabled, List disabledExact, int undergroundYShift, boolean datapackOverrides, + List frequencyOverrides, List adjustments) { + this.disabled = List.copyOf(disabled); + this.disabledExact = List.copyOf(disabledExact); + this.undergroundYShift = undergroundYShift; + this.datapackOverrides = datapackOverrides; + this.frequencyOverrides = List.copyOf(frequencyOverrides); + this.adjustments = List.copyOf(adjustments); + } + + /** Family patterns of the structures the dimension disables. */ + public List disabled() { + return listOrEmpty(disabled); + } + + /** Complete keys of the structures the dimension disables. */ + public List disabledExact() { + return listOrEmpty(disabledExact); + } + + public int undergroundYShift() { + return undergroundYShift; + } + + public boolean datapackOverrides() { + return datapackOverrides; + } + + public List frequencyOverrides() { + return listOrEmpty(frequencyOverrides); + } + + public List adjustments() { + return listOrEmpty(adjustments); + } + + static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index a3e1672bb..ad0d61b6a 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.framework; +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; @@ -479,7 +480,7 @@ public final class IrisStructureLocator { if (engine == null || engine.getData() == null || engine.getSeedManager() == null) { throw new IllegalStateException("Iris structure placement requires a fully bound engine"); } - NativeStructurePlacementPlanner.validateBackend(placement); + NativeStartPlanner.validateBackend(placement); if (!placement.hasIrisStructures() || placement.getDistribution() == null) { throw new IllegalStateException("Iris structure placement is missing its distribution or structure list"); } @@ -600,7 +601,7 @@ public final class IrisStructureLocator { IrisData data = engine.getData(); String normalizedKey = normalize(key); if (hasNativePlacement(engine, key)) { - for (NativeStructureStartPlan plan : NativeStructurePlacementPlanner.plansAt(engine, cx, cz)) { + for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(engine, cx, cz)) { if (normalize(plan.source().getStructure()).equals(normalizedKey)) { return new ResolvedStart(cx << 4, plan.baseY(), cz << 4); } @@ -648,7 +649,7 @@ public final class IrisStructureLocator { return null; } if (!placement.isUnderwater() - && NativeStructurePlacementPlanner.isSubmerged(engine, originX, originZ)) { + && NativeStartPlanner.isSubmerged(engine, originX, originZ)) { return null; } if (placement.resolvedAnchor() == IrisStructureAnchorMode.SURFACE) { @@ -1180,7 +1181,7 @@ public final class IrisStructureLocator { if (placement.getDistribution() == null) { throw new IllegalStateException("Iris structure placement is missing its distribution"); } - NativeStructurePlacementPlanner.validateBackend(placement); + NativeStartPlanner.validateBackend(placement); boolean replacesNative = NativeStructureSuppression.REPLACE_SOURCE == placement.getNativeSuppression(); if (replacesNative && !allowNativeSuppression) { throw new IllegalStateException("REPLACE_SOURCE is only valid on dimension-level structure placements"); diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java new file mode 100644 index 000000000..78fb6157d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java @@ -0,0 +1,145 @@ +/* + * 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.builtin.structure.StructureAdjustment; +import art.arcane.iris.builtin.structure.StructureSetFrequency; +import art.arcane.iris.builtin.structure.StructureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import com.volmit.resource.ResourceId; +import com.volmit.vanilla.VanillaStructureAdjustment; +import com.volmit.vanilla.VanillaStructureFit; +import com.volmit.vanilla.VanillaStructureSetup; + +import java.util.List; +import java.util.Locale; +import java.util.Optional; + +/** + * What a dimension's {@link StructureSettings} say about the platform's own structures: which ones it disables, how + * the starts of the others are adjusted, and how the platform sets them up. Keys match ignoring case and surrounding + * space; a family pattern also matches the keys it starts at a namespace, slash or underscore boundary + * ({@link #matchesKey}). + */ +public final class ImportedStructures { + private final StructureSettings settings; + + public ImportedStructures(StructureSettings settings) { + this.settings = settings; + } + + /** The settings the dimension of {@code settings} declares, or the defaults when it declares none. */ + public static ImportedStructures of(PackSettings settings) { + List> declared = settings.declared(StructureSettings.class); + return new ImportedStructures(declared.isEmpty() ? new StructureSettings() : declared.getFirst().value()); + } + + /** Whether the dimension disables the platform structure {@code key}, by family or by its exact key. */ + public boolean disables(String key) { + String normalizedKey = normalize(key); + if (normalizedKey.isEmpty()) { + return false; + } + return settings.disabled().stream().anyMatch(pattern -> matchesKey(pattern, key)) + || settings.disabledExact().stream().map(ImportedStructures::normalize) + .anyMatch(exact -> !exact.isEmpty() && exact.equals(normalizedKey)); + } + + /** + * How the platform's own starts of {@code key} are adjusted: the underground shift for underground steps, then every + * matching adjustment in the order the pack lists them. + */ + public VanillaStructureAdjustment adjustment(String key, boolean underground) { + VanillaStructureAdjustment adjustment = VanillaStructureAdjustment.NONE.shifted(underground ? settings.undergroundYShift() : 0); + for (StructureAdjustment entry : settings.adjustments()) { + if (entry != null && matchesAny(entry.match(), key)) { + adjustment = adjustment.then(asAdjustment(entry)); + } + } + return adjustment; + } + + /** + * The structure set frequencies the dimension changes and whether it keeps data packs off the platform's definitions. + * An override naming no namespaced key can match no registered set and is left out. + */ + public VanillaStructureSetup setup() { + VanillaStructureSetup setup = settings.datapackOverrides() + ? VanillaStructureSetup.UNCHANGED + : VanillaStructureSetup.UNCHANGED.protectingVanillaDefinitions(); + for (StructureSetFrequency override : settings.frequencyOverrides()) { + Optional structureSet = override == null ? Optional.empty() : structureSetId(override.structureSet()); + if (structureSet.isPresent()) { + setup = setup.withFrequency(structureSet.get(), override.multiplier()); + } + } + return setup; + } + + private static Optional structureSetId(String key) { + try { + return Optional.of(ResourceId.parse(normalize(key))); + } catch (IllegalArgumentException notAnId) { + return Optional.empty(); + } + } + + /** + * Whether the family pattern {@code pattern} matches the structure {@code key}: equal keys, or a pattern the key + * starts with that ends in, or is followed in the key by, {@code :}, {@code /} or {@code _}. So + * {@code minecraft:village} matches {@code minecraft:village_plains} and {@code nova_structures:} a whole namespace. + */ + public static boolean matchesKey(String pattern, String key) { + if (pattern == null || key == null) { + return false; + } + String normalizedPattern = normalize(pattern); + String normalizedKey = normalize(key); + if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { + return false; + } + if (normalizedKey.length() == normalizedPattern.length()) { + return true; + } + char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); + if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { + return true; + } + char boundary = normalizedKey.charAt(normalizedPattern.length()); + return boundary == '/' || boundary == '_'; + } + + private static boolean matchesAny(List patterns, String key) { + return patterns.stream().anyMatch(pattern -> matchesKey(pattern, key)); + } + + private static VanillaStructureAdjustment asAdjustment(StructureAdjustment entry) { + VanillaStructureFit fit = VanillaStructureFit.SOURCE; + fit = entry.stilt().map(fit::withStilts).orElse(fit); + fit = entry.terrain().map(fit::withTerrain).orElse(fit); + VanillaStructureAdjustment adjustment = VanillaStructureAdjustment.NONE.shifted(entry.yShift()).withFit(fit); + adjustment = entry.yBand().map(adjustment::withYBand).orElse(adjustment); + return entry.preserveSourceY() ? adjustment.keepingSourceY() : adjustment; + } + + private static String normalize(String key) { + return key == null ? "" : key.trim().toLowerCase(Locale.ROOT); + } +} 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 new file mode 100644 index 000000000..bc21cf3d7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java @@ -0,0 +1,174 @@ +/* + * 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.engine.object.structure.IrisStructureAnchorMode; +import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; +import art.arcane.volmlib.util.collection.KList; +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(IrisStructurePlacement placement, IrisNativeStructure source, int chunkX, int chunkZ, int baseY) { + } + + public static List plansAt(Engine engine, int chunkX, int chunkZ) { + Map plansByStructure = new LinkedHashMap<>(); + for (IrisStructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { + Plan plan = planAt(engine, placement, chunkX, chunkZ); + if (plan == null) { + continue; + } + String structureKey = normalize(plan.source().getStructure()); + 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, IrisStructurePlacement 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); + IrisNativeStructure source = selectSource(placement.getNativeStructures(), 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(IrisStructurePlacement 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.getAnchor() != null + && placement.getAnchor() != IrisStructureAnchorMode.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 IrisNativeStructure selectSource(KList 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 (IrisNativeStructure source : sources) { + if (source == null || source.getStructure() == null || source.getStructure().isBlank()) { + throw new IllegalStateException("Native structure placement contains a blank source"); + } + if (source.getWeight() < 1) { + throw new IllegalStateException("Native structure source '" + source.getStructure() + + "' has invalid weight " + source.getWeight()); + } + totalWeight = Math.addExact(totalWeight, source.getWeight()); + } + if (totalWeight > Integer.MAX_VALUE) { + throw new IllegalStateException("Native structure source weights exceed " + Integer.MAX_VALUE); + } + int roll = rng.nextInt((int) totalWeight); + for (IrisNativeStructure source : sources) { + roll -= source.getWeight(); + if (roll < 0) { + return source; + } + } + throw new IllegalStateException("Native structure source selection produced no result"); + } + + private static Integer resolveBaseY(Engine engine, IrisStructurePlacement 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.isUnderwater() && isSubmerged(engine, blockX, blockZ)) { + return null; + } + if (!placement.isUnderground()) { + int surfaceY = engine.getHeight(blockX, blockZ, true) + engine.getMinHeight(); + if (surfaceY < placement.getMinHeight() || surfaceY > placement.getMaxHeight()) { + return null; + } + return surfaceY; + } + int bandMin = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight())); + int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + if (bandMin > bandMax) { + return null; + } + return bandMin == bandMax ? bandMin : bandMin + rng.nextInt((bandMax - bandMin) + 1); + } + + private static int comparePlacementPriority(IrisStructurePlacement left, IrisStructurePlacement 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/StructureVanillaHook.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java new file mode 100644 index 000000000..eb6475991 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java @@ -0,0 +1,115 @@ +/* + * 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.modules.IrisPackSettings; +import art.arcane.iris.core.modules.IrisPackWorld; +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.object.structure.IrisStructurePlacement; +import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; +import com.google.gson.Gson; +import com.volmit.resource.ResourceId; +import com.volmit.vanilla.JigsawOverrides; +import com.volmit.vanilla.StructureStilts; +import com.volmit.vanilla.StructureTerrain; +import com.volmit.vanilla.VanillaStructureAdjustment; +import com.volmit.vanilla.VanillaStructureContext; +import com.volmit.vanilla.VanillaStructureFit; +import com.volmit.vanilla.VanillaStructureHook; +import com.volmit.vanilla.VanillaStructureRule; +import com.volmit.vanilla.VanillaStructureSetup; +import com.volmit.vanilla.VanillaStructureStart; +import com.volmit.vanilla.VanillaStructureStartContext; + +import java.util.List; + +/** + * What {@code iris:structure} says about the platform's own structures. The dimension's {@code iris:structure} + * settings ({@link ImportedStructures}) disable, adjust and set them up; the pack's structure placements replace + * them ({@code vanillaSource} with native suppression), place them alongside ({@link IrisStructureLocator#isPlaced}) + * and start them where their {@code nativeStructures} grids say ({@link NativeStartPlanner}). + */ +public final class StructureVanillaHook implements VanillaStructureHook { + private static final Gson SAME_JSON = new Gson(); + + /** + * {@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 = IrisPackSettings.of(context.settings()).engine(); + 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 VanillaStructureAdjustment adjustment(ResourceId structure, boolean underground, VanillaStructureContext context) { + return ImportedStructures.of(context.settings()).adjustment(structure.toString(), underground); + } + + @Override + public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { + Engine engine = IrisPackWorld.of(context.world()).engine(); + return NativeStartPlanner.plansAt(engine, chunkX, chunkZ).stream() + .map(plan -> start(plan, engine.getMinHeight())) + .toList(); + } + + @Override + public VanillaStructureSetup setup(VanillaStructureContext context) { + return ImportedStructures.of(context.settings()).setup(); + } + + /** {@code plan} as the start the platform generates: heights above the bottom, the placement's fit and identity. */ + static VanillaStructureStart start(NativeStartPlanner.Plan plan, int minHeight) { + IrisStructurePlacement placement = plan.placement(); + VanillaStructureStart start = VanillaStructureStart.at(ResourceId.parse(plan.source().getStructure()), + plan.chunkX(), plan.chunkZ(), plan.baseY() - minHeight) + .withIdentity(StructurePlacementGrid.placementIdentity(placement)) + .withFit(fit(placement)); + if (placement.isUnderground()) { + start = start.underground(); + } + if (placement.getNativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE) { + start = start.replacingPlatformStart(); + } + if (plan.source().getJigsaw() != null) { + start = start.withJigsaw(sameJson(plan.source().getJigsaw(), JigsawOverrides.class)); + } + return start; + } + + private static VanillaStructureFit fit(IrisStructurePlacement placement) { + VanillaStructureFit fit = VanillaStructureFit.SOURCE.withTerrain(sameJson(placement.resolvedTerrain(), StructureTerrain.class)); + return placement.getStilt() == null ? fit : fit.withStilts(sameJson(placement.getStilt(), StructureStilts.class)); + } + + /** The placement classes are Iris's; the API values read the same JSON. */ + private static T sameJson(Object irisValue, Class apiType) { + return SAME_JSON.fromJson(SAME_JSON.toJsonTree(irisValue), apiType); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 5aa19e9b9..4f7952044 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.structure.StructureSettings; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.core.modules.IrisPackWorld; @@ -27,17 +28,15 @@ import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.StructureLocating; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.framework.structure.StructureValidator; +import art.arcane.iris.engine.framework.structure.StructureVanillaHook; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; import com.volmit.config.PackSettings; -import com.volmit.resource.ResourceId; import com.volmit.service.StructureLocator; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; -import com.volmit.vanilla.VanillaStructureContext; -import com.volmit.vanilla.VanillaStructureRule; import com.volmit.world.PackWorld; /** @@ -51,8 +50,9 @@ import com.volmit.world.PackWorld; * {@link StructureLocating}, and forgets a world's structure index when the world stops, which includes every reload of * the pack's structure files. *

- * It decides over the platform's own structures through its vanilla structure hook ({@link #vanillaRule}): a structure - * an Iris structure replaces is blocked, and one a structure placement of the pack places is reported as placed here. + * It decides over the platform's own structures through its vanilla structure hook ({@link StructureVanillaHook}): the + * dimension's {@code iris:structure} settings disable, adjust and set them up, and the pack's structure placements + * replace them, place them alongside, and start them where their {@code nativeStructures} grids say. */ public final class StructureModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @@ -70,11 +70,12 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { @Override public void register(FeatureRegistry registry) { + registry.registerSettings(StructureSettings.class); StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new StructureValidator()); registry.registerService(StructureLocator.class, new StructureLocating()); registry.registerLifecycle(this); - registry.registerVanillaStructureHook(StructureModule::vanillaRule); + registry.registerVanillaStructureHook(new StructureVanillaHook()); } /** The structure index is still kept per engine rather than in the world's state, so a stopping world drops it. */ @@ -83,20 +84,6 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { IrisStructureLocator.invalidate(IrisPackWorld.of(world).engine()); } - /** - * {@link VanillaStructureRule#REPLACE} for a platform structure that an Iris structure of the world's placements - * replaces (its {@code vanillaSource} with native suppression), {@link VanillaStructureRule#ALSO_PLACE} for one - * a placement of the world places itself, {@link VanillaStructureRule#GENERATE} otherwise. - */ - static VanillaStructureRule vanillaRule(ResourceId structure, VanillaStructureContext context) { - Engine engine = IrisPackSettings.of(context.settings()).engine(); - String key = structure.toString(); - if (IrisStructureLocator.suppressesVanilla(engine, key)) { - return VanillaStructureRule.REPLACE; - } - return IrisStructureLocator.isPlaced(engine, key) ? VanillaStructureRule.ALSO_PLACE : VanillaStructureRule.GENERATE; - } - private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java index 1560df858..7768b6818 100644 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructure.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.object.annotations; -import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; import java.lang.annotation.Retention; import java.lang.annotation.Target; @@ -30,12 +29,4 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) public @interface RegistryListVanillaStructure { - /** - * When true the field accepts family/namespace prefixes in addition to exact registered keys - * (the {@code IrisImportedStructureControl.matchesKey} contract: "minecraft:village" matches - * every village variant, "nova_structures:" matches a whole namespace). The generated editor - * schema then validates entries against the registry enum OR a key/prefix pattern instead of - * rejecting anything that is not an exact registered key. - */ - boolean prefixes() default false; } diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java deleted file mode 100644 index e877e6ff5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListVanillaStructureSet.java +++ /dev/null @@ -1,33 +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.annotations; - -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 RegistryListVanillaStructureSet { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java index bf44eb3bc..28a572d6c 100644 --- a/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java +++ b/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.decoration; -import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; +import art.arcane.iris.engine.framework.structure.ImportedStructures; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.volmlib.util.collection.KList; @@ -98,7 +98,7 @@ public class IrisImportedFeatureControl { KList deniedKeys = Objects.requireNonNull( disabled, "importedFeatures.disabled must not be null"); for (String entry : deniedKeys) { - if (IrisImportedStructureControl.matchesKey(entry, placedFeatureKey)) { + if (ImportedStructures.matchesKey(entry, placedFeatureKey)) { return NativeFeatureGenerationStatus.DISABLED_BY_PACK; } } diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java deleted file mode 100644 index 22824b12b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisImportedStructureControl.java +++ /dev/null @@ -1,184 +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.vanilla; - -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureYBand; -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.RegistryListVanillaStructure; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Locale; -import java.util.Objects; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension (set as the dimension's 'importedStructures' field). Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris structure list ' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") -@Data -public class IrisImportedStructureControl { - @ArrayType(type = String.class, min = 1) - @RegistryListVanillaStructure(prefixes = true) - @Desc("Structure keys to deny explicitly, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' disables every village variant and 'minecraft:ruined_portal' disables every ruined portal. Every key not matched here remains enabled.") - private KList disabled = new KList<>(); - - @ArrayType(type = String.class, min = 1) - @RegistryListVanillaStructure(prefixes = false) - @Desc("Exact structure keys to deny after trimming and case normalization. Unlike 'disabled', entries never match key families, so 'minecraft:ruined_portal' does not disable 'minecraft:ruined_portal_nether'.") - private KList disabledExact = new KList<>(); - - @MinNumber(-512) - @MaxNumber(512) - @Desc("Vertical block offset applied only to UNDERGROUND vanilla structures (the UNDERGROUND_STRUCTURES, UNDERGROUND_DECORATION, and STRONGHOLDS generation steps: strongholds, trial chambers, mineshafts, ancient cities, etc.). Surface structures (villages, outposts, etc.) are never shifted. Use a negative value to push deep structures lower when your dimension's sea/terrain level differs from vanilla's (e.g. -64 if you lowered the fluid height to 0). 0 = no shift.") - private int undergroundYShift = 0; - - @Desc("Controls whether ingested datapacks may replace minecraft-namespaced structure definitions, sets, pools, and templates. When false, those overrides are stripped from installed datapack copies so vanilla definitions stay intact. Non-minecraft structures from datapacks and mods remain governed by disabled because namespace alone cannot identify their origin. Resolved globally across loaded packs: if any dimension sets this false, minecraft-namespaced overrides are stripped from every installed datapack copy.") - private boolean datapackOverrides = true; - - @ArrayType(type = IrisStructureSetFrequencyOverride.class, min = 1) - @Desc("Exact registered structure-set frequency overrides for native generation. The last entry for a normalized structure-set key wins. These do not convert native structures into Iris placements and affect only newly generated chunks.") - private KList frequencyOverrides = new KList<>(); - - @ArrayType(type = IrisVanillaStructureAdjustment.class, min = 1) - @Desc("Per-structure adjustments applied to vanilla, mod, and datapack structures that still generate natively. Vertical shifts from every matching entry stack. A matching preserveSourceY option disables Iris burial repositioning for that structure. The last matching entry with stilt settings controls foundation columns, and likewise for terrain and yBand settings. A structure suppressed by an Iris placement is unaffected.") - private KList adjustments = new KList<>(); - - public boolean shouldGenerate(String key) { - return key != null && !key.isBlank() - && !matches(disabled, key) - && !matchesExact(disabledExact, key); - } - - public IrisNativeStructureDecision resolve(String key, boolean undergroundStep) { - KList activeAdjustments = Objects.requireNonNull( - adjustments, "importedStructures.adjustments must not be null"); - int y = undergroundStep ? undergroundYShift : 0; - boolean preserveSourceY = false; - IrisStructureStiltSettings stilt = null; - IrisStructureTerrain terrain = null; - IrisStructureYBand yBand = null; - for (IrisVanillaStructureAdjustment adjustment : activeAdjustments) { - if (adjustment != null && adjustment.matches(key)) { - y += adjustment.getYShift(); - preserveSourceY |= adjustment.isPreserveSourceY(); - if (adjustment.getStilt() != null) { - stilt = adjustment.getStilt(); - } - if (adjustment.getTerrain() != null) { - terrain = adjustment.getTerrain(); - } - if (adjustment.getYBand() != null) { - yBand = adjustment.getYBand(); - } - } - } - return new IrisNativeStructureDecision( - generationStatus(key), y, yBand, preserveSourceY, stilt, terrain); - } - - public double frequencyMultiplier(String structureSetKey) { - KList activeOverrides = Objects.requireNonNull( - frequencyOverrides, "importedStructures.frequencyOverrides must not be null"); - String normalizedKey = normalizeKey(structureSetKey); - if (normalizedKey.isEmpty()) { - return 1D; - } - double multiplier = 1D; - for (IrisStructureSetFrequencyOverride override : activeOverrides) { - if (override != null && normalizeKey(override.getStructureSet()).equals(normalizedKey)) { - multiplier = override.getMultiplier(); - } - } - return multiplier; - } - - public boolean hasFrequencyOverrides() { - return !Objects.requireNonNull( - frequencyOverrides, "importedStructures.frequencyOverrides must not be null").isEmpty(); - } - - private NativeStructureGenerationStatus generationStatus(String key) { - if (key == null || key.isBlank()) { - return NativeStructureGenerationStatus.INVALID_REGISTRY_KEY; - } - if (matches(disabled, key) || matchesExact(disabledExact, key)) { - return NativeStructureGenerationStatus.DISABLED_BY_PACK; - } - return NativeStructureGenerationStatus.GENERATE_NATIVE; - } - - private boolean matches(KList list, String key) { - if (key == null) { - return false; - } - KList activeList = Objects.requireNonNull( - list, "importedStructures.disabled must not be null"); - for (String entry : activeList) { - if (matchesKey(entry, key)) { - return true; - } - } - return false; - } - - private boolean matchesExact(KList list, String key) { - KList activeList = Objects.requireNonNull( - list, "importedStructures.disabledExact must not be null"); - String normalizedKey = normalizeKey(key); - for (String entry : activeList) { - String normalizedEntry = normalizeKey(entry); - if (!normalizedEntry.isEmpty() && normalizedEntry.equals(normalizedKey)) { - return true; - } - } - return false; - } - - public static boolean matchesKey(String pattern, String key) { - if (pattern == null || key == null) { - return false; - } - String normalizedPattern = pattern.trim().toLowerCase(Locale.ROOT); - String normalizedKey = key.trim().toLowerCase(Locale.ROOT); - if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { - return false; - } - if (normalizedKey.length() == normalizedPattern.length()) { - return true; - } - char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); - if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { - return true; - } - char boundary = normalizedKey.charAt(normalizedPattern.length()); - return boundary == '/' || boundary == '_'; - } - - private static String normalizeKey(String key) { - return key == null ? "" : key.trim().toLowerCase(Locale.ROOT); - } -} 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 index 206b1d1ee..53d3dcf40 100644 --- 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 @@ -32,7 +32,6 @@ import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.procedural.tree.IrisTreeSettings; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; @@ -292,8 +291,6 @@ public class IrisDimension extends IrisRegistrant { @Desc("Dimension-wide Iris structure placements, independent of biome/region placements") @ArrayType(type = IrisStructurePlacement.class, min = 1) private KList structures = new KList<>(); - @Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure is enabled by default; 'disabled' is the sole generation deny list and autocompletes live structure keys.") - private IrisImportedStructureControl importedStructures = new IrisImportedStructureControl(); @Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation (ores, trees, plants, springs, geodes) for this dimension. Disabled by default: leaving this out generates exactly the terrain Iris always has. Set 'enabled' true to run the vanilla decoration feature pass over Iris terrain. Carvers are never imported.") private IrisImportedFeatureControl importedFeatures = new IrisImportedFeatureControl(); @ArrayType(type = String.class, min = 1) From f7d11e5cf09d1c109ff0693908131a791530734a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:12:02 +0200 Subject: [PATCH 036/139] Carving settings as module-owned IrisApi types: cave profile, cave field module, anchor mode, carving mode --- .../carve}/CarvingMode.java | 4 +- .../carve/CaveAnchorMode.java} | 6 +- .../iris/builtin/carve/CaveFieldModule.java | 66 ++++ .../iris/builtin/carve/CaveProfile.java | 303 ++++++++++++++++++ .../engine/mantle/components/CaveCarving.java | 68 ++-- .../components/CaveFieldModuleState.java | 12 +- .../mantle/components/IrisCaveCarver3D.java | 64 ++-- .../mantle/components/ObjectPlacing.java | 82 ++--- .../iris/engine/modifier/CarveModule.java | 9 + .../engine/object/placement/AnchorModule.java | 2 +- .../engine/object/placement/BlocksModule.java | 2 +- .../object/placement/IrisObjectPlacement.java | 6 +- .../object/placement/ValidateModule.java | 2 +- .../object/procedural/coral/IrisCoral.java | 2 +- .../procedural/crystal/IrisCrystal.java | 2 +- .../procedural/formation/IrisFormation.java | 2 +- .../object/procedural/fungi/IrisFungus.java | 2 +- .../object/procedural/ruin/IrisRuin.java | 2 +- .../procedural/tree/IrisProceduralTree.java | 2 +- .../terrain/carving/IrisCaveFieldModule.java | 39 --- .../terrain/carving/IrisCaveProfile.java | 153 --------- .../carving/IrisCaveProfileSampler.java | 37 ++- .../terrain/carving/ResolvedCaveProfile.java | 123 +++++++ .../floating/IrisFloatingChildBiomes.java | 2 +- .../engine/object/world/biome/IrisBiome.java | 4 +- .../object/world/dimension/IrisDimension.java | 4 +- .../object/world/region/IrisRegion.java | 4 +- 27 files changed, 659 insertions(+), 345 deletions(-) rename src/main/java/art/arcane/iris/{engine/object/terrain/carving => builtin/carve}/CarvingMode.java (92%) rename src/main/java/art/arcane/iris/{engine/object/terrain/carving/IrisCaveAnchorMode.java => builtin/carve/CaveAnchorMode.java} (78%) create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingMode.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java rename to src/main/java/art/arcane/iris/builtin/carve/CarvingMode.java index 7d5aca7c2..8a12fbefd 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingMode.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingMode.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.terrain.carving; +package art.arcane.iris.builtin.carve; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Defines if an object is allowed to place in carvings, surfaces or both.") public enum CarvingMode { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java b/src/main/java/art/arcane/iris/builtin/carve/CaveAnchorMode.java similarity index 78% rename from src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java rename to src/main/java/art/arcane/iris/builtin/carve/CaveAnchorMode.java index a66f57a13..189e5739a 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveAnchorMode.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveAnchorMode.java @@ -1,9 +1,9 @@ -package art.arcane.iris.engine.object.terrain.carving; +package art.arcane.iris.builtin.carve; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Defines which carved-space anchor to target for cave object placement.") -public enum IrisCaveAnchorMode { +public enum CaveAnchorMode { @Desc("Use the active cave profile default anchor mode.") PROFILE_DEFAULT, diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java b/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java new file mode 100644 index 000000000..e2267807d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveFieldModule.java @@ -0,0 +1,66 @@ +/* + * 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.builtin.carve; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Range; +import com.volmit.noise.NoiseStyle; + +/** One more layer of noise a cave profile blends into its density, an entry of the profile's {@code modules}. */ +@Desc("Represents a modular cave-density layer.") +public final class CaveFieldModule { + @Desc("Density style used by this module.") + private NoiseStyle style = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); + @MinNumber(0) + @Desc("Layer contribution multiplier.") + private double weight = 1; + @MinNumber(-1) + @MaxNumber(1) + @Desc("Threshold offset applied to this layer before blending.") + private double threshold = 0; + @Desc("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private Range verticalRange = Range.of(0, 384); + @Desc("Invert this module before weighting.") + private boolean invert = false; + + public CaveFieldModule() { + } + + public NoiseStyle style() { + return style; + } + + public double weight() { + return weight; + } + + public double threshold() { + return threshold; + } + + public Range verticalRange() { + return verticalRange; + } + + public boolean invert() { + return invert; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java b/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java new file mode 100644 index 000000000..0884897b3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java @@ -0,0 +1,303 @@ +/* + * 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.builtin.carve; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Range; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * A 3D cave profile as packs write it for a dimension, region or biome ({@code caveProfile}) or under + * {@code snippet/cave-profile/}: the noise fields that decide where caves are, how they meet the surface, where + * cave fluid may sit and how objects find anchors in them. IrisApi types only; the carving module builds the noise. + */ +@Snippet("cave-profile") +@Desc("Represents a configurable 3D cave profile.") +public final class CaveProfile { + @Desc("Enable profile-driven cave carving.") + private boolean enabled = false; + + @Desc("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private Range verticalRange = Range.of(0, 384); + + @MinNumber(0) + @MaxNumber(128) + @Desc("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.") + private int verticalEdgeFade = 20; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Strength of the vertical edge fade at cave profile min/max bounds.") + private double verticalEdgeFadeStrength = 0.18; + + @Desc("Base density style for cave field generation.") + private NoiseStyle baseDensityStyle = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); + + @Desc("Detail density style blended into base caves.") + private NoiseStyle detailDensityStyle = NoiseStyle.of("SIMPLEX"); + + @Desc("Warp style used to distort cave coordinates.") + private NoiseStyle warpStyle = NoiseStyle.of("FLAT"); + + @MinNumber(0) + @Desc("Base cave field multiplier.") + private double baseWeight = 1; + + @MinNumber(0) + @Desc("Detail cave field multiplier.") + private double detailWeight = 0.35; + + @MinNumber(0) + @Desc("Coordinate warp strength for cave fields.") + private double warpStrength = 0; + + @Desc("Threshold range used for carve cutoff decisions.") + private StyledRange densityThreshold = StyledRange.of(-0.2, 0.2, NoiseStyle.of("CELLULAR_IRIS_DOUBLE")); + + @MinNumber(0) + @MaxNumber(1) + @Desc("Extra threshold bias subtracted from sampled threshold before carve tests.") + private double thresholdBias = 0.16; + + @MinNumber(1) + @MaxNumber(8) + @Desc("Vertical sample step used while evaluating cave density.") + private int sampleStep = 1; + + @Desc("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.") + private boolean adaptiveSampling = true; + + @MinNumber(2) + @MaxNumber(4) + @Desc("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.") + private int adaptiveSampleStep = 2; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.") + private double adaptiveThresholdMargin = 0.04; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum solid clearance below terrain surface where carving may occur.") + private int surfaceClearance = 4; + + @Desc("Allow profile-driven cave carving to break through terrain surface in selected columns.") + private boolean allowSurfaceBreak = true; + + @Desc("Noise style used to decide where surface-breaking cave columns are allowed.") + private NoiseStyle surfaceBreakStyle = NoiseStyle.of("SIMPLEX").withZoom(0.08); + + @MinNumber(-1) + @MaxNumber(1) + @Desc("Minimum signed surface-break noise value required before near-surface carving is allowed.") + private double surfaceBreakNoiseThreshold = 0.62; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Near-surface depth window used for surface-break carve logic.") + private int surfaceBreakDepth = 18; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Additional threshold boost applied while carving in the surface-break depth window.") + private double surfaceBreakThresholdBoost = 0.2; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum depth below terrain surface required for cave-only object anchor placement.") + private int objectMinDepthBelowSurface = 6; + + @MinItems(1) + @Desc("Additional layered cave-density modules.") + private List modules = List.of(); + + @Desc("Default cave anchor mode for cave-only object placement.") + private CaveAnchorMode defaultObjectAnchor = CaveAnchorMode.FLOOR; + + @Desc("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.") + private ObjectPlaceMode defaultObjectPlaceMode; + + @MinNumber(1) + @MaxNumber(8) + @Desc("Vertical scan step used while searching cave anchors.") + private int anchorScanStep = 1; + + @MinNumber(1) + @MaxNumber(64) + @Desc("Maximum random column retries while searching a valid cave object anchor in the chunk.") + private int anchorSearchAttempts = 6; + + @Desc("Allow cave fluid placement from the dimension fluid palette below fluid level.") + private boolean allowFluid = true; + + @MinNumber(0) + @MaxNumber(64) + @Desc("Minimum depth below terrain surface required before cave fluid may be placed.") + private int fluidMinDepthBelowSurface = 12; + + @Desc("Require solid floor support below cave fluid to reduce unsupported fluid flows.") + private boolean fluidRequiresFloor = true; + + @Desc("Allow cave lava placement based on lava height.") + private boolean allowLava = true; + + + public CaveProfile() { + } + + public boolean enabled() { + return enabled; + } + + public Range verticalRange() { + return verticalRange; + } + + public int verticalEdgeFade() { + return verticalEdgeFade; + } + + public double verticalEdgeFadeStrength() { + return verticalEdgeFadeStrength; + } + + public NoiseStyle baseDensityStyle() { + return baseDensityStyle; + } + + public NoiseStyle detailDensityStyle() { + return detailDensityStyle; + } + + public NoiseStyle warpStyle() { + return warpStyle; + } + + public double baseWeight() { + return baseWeight; + } + + public double detailWeight() { + return detailWeight; + } + + public double warpStrength() { + return warpStrength; + } + + public StyledRange densityThreshold() { + return densityThreshold; + } + + public double thresholdBias() { + return thresholdBias; + } + + public int sampleStep() { + return sampleStep; + } + + public boolean adaptiveSampling() { + return adaptiveSampling; + } + + public int adaptiveSampleStep() { + return adaptiveSampleStep; + } + + public double adaptiveThresholdMargin() { + return adaptiveThresholdMargin; + } + + public int surfaceClearance() { + return surfaceClearance; + } + + public boolean allowSurfaceBreak() { + return allowSurfaceBreak; + } + + public NoiseStyle surfaceBreakStyle() { + return surfaceBreakStyle; + } + + public double surfaceBreakNoiseThreshold() { + return surfaceBreakNoiseThreshold; + } + + public int surfaceBreakDepth() { + return surfaceBreakDepth; + } + + public double surfaceBreakThresholdBoost() { + return surfaceBreakThresholdBoost; + } + + public int objectMinDepthBelowSurface() { + return objectMinDepthBelowSurface; + } + + public List modules() { + return modules == null ? List.of() : Collections.unmodifiableList(modules); + } + + public CaveAnchorMode defaultObjectAnchor() { + return defaultObjectAnchor == null ? CaveAnchorMode.FLOOR : defaultObjectAnchor; + } + + /** The mode cave objects take where their placement has none of its own; empty when the profile sets none. */ + public Optional defaultObjectPlaceMode() { + return Optional.ofNullable(defaultObjectPlaceMode); + } + + public int anchorScanStep() { + return anchorScanStep; + } + + public int anchorSearchAttempts() { + return anchorSearchAttempts; + } + + public boolean allowFluid() { + return allowFluid; + } + + public int fluidMinDepthBelowSurface() { + return fluidMinDepthBelowSurface; + } + + public boolean fluidRequiresFloor() { + return fluidRequiresFloor; + } + + public boolean allowLava() { + return allowLava; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index c67e63461..2660dc3f2 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; 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.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -67,7 +67,7 @@ public class CaveCarving { private final Engine engine; private final Object profileCarverLock = new Object(); - private volatile Map profileCarvers = new IdentityHashMap<>(); + private volatile Map profileCarvers = new IdentityHashMap<>(); static { int kernelIndex = 0; @@ -132,7 +132,7 @@ public class CaveCarving { private static int maxSurfaceBreakDepth(List weightedProfiles) { int maxDepth = 0; for (WeightedProfile weightedProfile : weightedProfiles) { - maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.getSurfaceBreakDepth())); + maxDepth = Math.max(maxDepth, Math.max(0, weightedProfile.profile.surfaceBreakDepth())); } return maxDepth; } @@ -202,11 +202,11 @@ public class CaveCarving { private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState) { BlendScratch blendScratch = BLEND_SCRATCH.get(); - IrisCaveProfile[] profileField = blendScratch.profileField; - Map columnProfileWeights = blendScratch.columnProfileWeights; - IdentityHashMap activeProfiles = blendScratch.activeProfiles; - List profileOrder = blendScratch.profileOrder; - IrisCaveProfile[] kernelProfiles = blendScratch.kernelProfiles; + CaveProfile[] profileField = blendScratch.profileField; + Map columnProfileWeights = blendScratch.columnProfileWeights; + IdentityHashMap activeProfiles = blendScratch.activeProfiles; + List profileOrder = blendScratch.profileOrder; + CaveProfile[] kernelProfiles = blendScratch.kernelProfiles; double[] kernelProfileWeights = blendScratch.kernelProfileWeights; activeProfiles.clear(); profileOrder.clear(); @@ -222,7 +222,7 @@ public class CaveCarving { for (int kernelIndex = 0; kernelIndex < KERNEL_SIZE; kernelIndex++) { int sampleX = centerX + KERNEL_DX[kernelIndex]; int sampleZ = centerZ + KERNEL_DZ[kernelIndex]; - IrisCaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ]; + CaveProfile profile = profileField[(sampleX * FIELD_SIZE) + sampleZ]; if (!isProfileEnabled(profile)) { continue; } @@ -245,7 +245,7 @@ public class CaveCarving { int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); for (int profileIndex = 0; profileIndex < profileCount; profileIndex++) { - IrisCaveProfile profile = kernelProfiles[profileIndex]; + CaveProfile profile = kernelProfiles[profileIndex]; double kernelWeight = kernelProfileWeights[profileIndex]; kernelProfiles[profileIndex] = null; kernelProfileWeights[profileIndex] = 0D; @@ -271,7 +271,7 @@ public class CaveCarving { } List columnWeightedProfiles = new ArrayList<>(); - for (IrisCaveProfile profile : profileOrder) { + for (CaveProfile profile : profileOrder) { double[] weights = columnProfileWeights.get(profile); if (weights == null) { continue; @@ -319,8 +319,8 @@ public class CaveCarving { IrisDimensionCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new IrisDimensionCarvingEntry[CHUNK_AREA]); buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState); - Map rootProfileColumnWeights = new IdentityHashMap<>(); - List rootProfileOrder = new ArrayList<>(); + Map rootProfileColumnWeights = new IdentityHashMap<>(); + List rootProfileOrder = new ArrayList<>(); IrisRange worldYRange = entry.getWorldYRange(); for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { IrisDimensionCarvingEntry resolvedEntry = columnPlan[columnIndex]; @@ -329,7 +329,7 @@ public class CaveCarving { continue; } - IrisCaveProfile profile = resolvedBiome.getCaveProfile(); + CaveProfile profile = resolvedBiome.getCaveProfile(); if (!isProfileEnabled(profile)) { continue; } @@ -343,7 +343,7 @@ public class CaveCarving { columnWeights[columnIndex] = 1D; } - for (IrisCaveProfile profile : rootProfileOrder) { + for (CaveProfile profile : rootProfileOrder) { weightedProfiles.add(new WeightedProfile(profile, rootProfileColumnWeights.get(profile), -1D, worldYRange, weightedProfiles.size())); } } @@ -364,7 +364,7 @@ public class CaveCarving { } } - private void fillProfileField(IrisCaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { + private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; prefillProfileFieldSamples(startX, startZ, complex, blendScratch); @@ -387,7 +387,7 @@ public class CaveCarving { } } - private int findProfileIndex(IrisCaveProfile[] profiles, int size, IrisCaveProfile profile) { + private int findProfileIndex(CaveProfile[] profiles, int size, CaveProfile profile) { for (int index = 0; index < size; index++) { if (profiles[index] == profile) { return index; @@ -397,7 +397,7 @@ public class CaveCarving { return -1; } - private IrisCaveProfile resolveColumnProfile( + private CaveProfile resolveColumnProfile( int worldX, int worldZ, double surfaceHeight, @@ -406,21 +406,21 @@ public class CaveCarving { IrisBiome caveBiome, IrisDimensionCarvingResolver.State resolverState ) { - IrisCaveProfile resolved = null; - IrisCaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); + CaveProfile resolved = null; + CaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); if (isProfileEnabled(dimensionProfile)) { resolved = dimensionProfile; } if (region != null) { - IrisCaveProfile regionProfile = region.getCaveProfile(); + CaveProfile regionProfile = region.getCaveProfile(); if (isProfileEnabled(regionProfile)) { resolved = regionProfile; } } if (surfaceBiome != null) { - IrisCaveProfile surfaceProfile = surfaceBiome.getCaveProfile(); + CaveProfile surfaceProfile = surfaceBiome.getCaveProfile(); if (isProfileEnabled(surfaceProfile)) { resolved = surfaceProfile; } @@ -455,7 +455,7 @@ public class CaveCarving { } } - IrisCaveProfile caveProfile = effectiveCaveBiome.getCaveProfile(); + CaveProfile caveProfile = effectiveCaveBiome.getCaveProfile(); if (isProfileEnabled(caveProfile)) { resolved = caveProfile; } @@ -499,7 +499,7 @@ public class CaveCarving { } } - private IrisCaveCarver3D getCarver(IrisCaveProfile profile) { + private IrisCaveCarver3D getCarver(CaveProfile profile) { IrisCaveCarver3D carver = profileCarvers.get(profile); if (carver != null) { return carver; @@ -512,15 +512,15 @@ public class CaveCarving { return published; } - Map updated = new IdentityHashMap<>(profileCarvers); + Map updated = new IdentityHashMap<>(profileCarvers); updated.put(profile, createdCarver); profileCarvers = updated; return createdCarver; } } - private boolean isProfileEnabled(IrisCaveProfile profile) { - return profile != null && profile.isEnabled(); + private boolean isProfileEnabled(CaveProfile profile) { + return profile != null && profile.enabled(); } private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) { @@ -656,13 +656,13 @@ public class CaveCarving { } private static final class WeightedProfile { - private final IrisCaveProfile profile; + private final CaveProfile profile; private final double[] columnWeights; private final double averageWeight; private final IrisRange worldYRange; private final int sequence; - private WeightedProfile(IrisCaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { + private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { this.profile = profile; this.columnWeights = columnWeights; this.averageWeight = averageWeight; @@ -676,13 +676,13 @@ public class CaveCarving { } private static final class BlendScratch { - private final IrisCaveProfile[] profileField = new IrisCaveProfile[FIELD_SIZE * FIELD_SIZE]; - private final IrisCaveProfile[] kernelProfiles = new IrisCaveProfile[KERNEL_SIZE]; + private final CaveProfile[] profileField = new CaveProfile[FIELD_SIZE * FIELD_SIZE]; + private final CaveProfile[] kernelProfiles = new CaveProfile[KERNEL_SIZE]; private final double[] kernelProfileWeights = new double[KERNEL_SIZE]; - private final IdentityHashMap columnProfileWeights = new IdentityHashMap<>(); + private final IdentityHashMap columnProfileWeights = new IdentityHashMap<>(); private final IdentityHashMap dimensionColumnPlans = new IdentityHashMap<>(); - private final IdentityHashMap activeProfiles = new IdentityHashMap<>(); - private final List profileOrder = new ArrayList<>(); + private final IdentityHashMap activeProfiles = new IdentityHashMap<>(); + private final List profileOrder = new ArrayList<>(); private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; private final IrisRegion[] fieldRegions = new IrisRegion[FIELD_SIZE * FIELD_SIZE]; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java index 269876586..f07e069ce 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveFieldModule; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.util.project.noise.CNG; @@ -32,14 +32,14 @@ final class CaveFieldModuleState { final double minContribution; final double maxContribution; - CaveFieldModuleState(IrisCaveFieldModule module, CNG density) { - IrisRange range = module.getVerticalRange(); + CaveFieldModuleState(ResolvedCaveProfile.Module module, CNG density) { + IrisRange range = module.verticalRange(); this.density = density; this.minY = (int) Math.floor(range.getMin()); this.maxY = (int) Math.ceil(range.getMax()); - this.weight = module.getWeight(); - this.threshold = module.getThreshold(); - this.invert = module.isInvert(); + this.weight = module.weight(); + this.threshold = module.threshold(); + this.invert = module.invert(); double rawMin = invert ? threshold - 1D : -1D - threshold; double rawMax = invert ? threshold + 1D : 1D - threshold; this.minContribution = rawMin * weight; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java index 962aee6c9..3f219f4be 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; 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.terrain.carving.IrisCaveFieldModule; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.noise.IrisStyledRange; import art.arcane.iris.util.project.noise.CNG; @@ -53,7 +53,8 @@ public class IrisCaveCarver3D { private final Engine engine; private final IrisData data; - private final IrisCaveProfile profile; + private final CaveProfile profile; + private final ResolvedCaveProfile resolved; private final CNG baseDensity; private final CNG detailDensity; private final CNG warpDensity; @@ -81,10 +82,11 @@ public class IrisCaveCarver3D { private final int aquiferCeilingY; private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); - public IrisCaveCarver3D(Engine engine, IrisCaveProfile profile) { + public IrisCaveCarver3D(Engine engine, CaveProfile profile) { this.engine = engine; this.data = engine.getData(); this.profile = profile; + this.resolved = ResolvedCaveProfile.of(profile); this.carveAir = new MatterCavern(true, "", LIQUID_AIR); this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); @@ -92,26 +94,26 @@ public class IrisCaveCarver3D { List moduleStates = new ArrayList<>(); RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); - this.surfaceBreakDensity = profile.getSurfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); + this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); + this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); + this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); + this.surfaceBreakDensity = resolved.surfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); this.thresholdRng = baseRng.nextParallelRNG(489_112); - this.baseWeight = profile.getBaseWeight(); - this.detailWeight = profile.getDetailWeight(); - this.warpStrength = profile.getWarpStrength(); + this.baseWeight = profile.baseWeight(); + this.detailWeight = profile.detailWeight(); + this.warpStrength = profile.warpStrength(); this.hasWarp = this.warpStrength > 0D; this.warpResolution = 2; - this.allowFluid = profile.isAllowFluid(); - this.fluidRequiresFloor = profile.isFluidRequiresFloor(); - this.fluidMinDepthBelowSurface = Math.max(0, profile.getFluidMinDepthBelowSurface()); + this.allowFluid = profile.allowFluid(); + this.fluidRequiresFloor = profile.fluidRequiresFloor(); + this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface()); this.fluidHeight = engine.getDimension().getFluidHeight(); this.aquiferCeilingY = engine.getHeight() - 1; double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; - for (IrisCaveFieldModule module : profile.getModules()) { - CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + for (ResolvedCaveProfile.Module module : resolved.modules()) { + CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); @@ -217,7 +219,7 @@ public class IrisCaveCarver3D { double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); int worldHeight = writer.getMantle().getWorldHeight(); - IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.getVerticalRange(); + IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : resolved.verticalRange(); int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.getMin())); int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.getMax())); if (worldYRange != null) { @@ -227,16 +229,16 @@ public class IrisCaveCarver3D { minY = Math.max(minY, rangeMinY); maxY = Math.min(maxY, rangeMaxY); } - int sampleStep = Math.max(1, profile.getSampleStep()); + int sampleStep = Math.max(1, profile.sampleStep()); boolean exactSampling = sampleStep <= 2; - boolean adaptiveSampling = exactSampling && profile.isAdaptiveSampling(); - int adaptiveSampleStep = Math.max(2, profile.getAdaptiveSampleStep()); - double adaptiveThresholdMargin = Math.max(0D, profile.getAdaptiveThresholdMargin()); - int surfaceClearance = Math.max(0, profile.getSurfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.getSurfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.getSurfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0, profile.getSurfaceBreakThresholdBoost()); - boolean allowSurfaceBreak = profile.isAllowSurfaceBreak(); + boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); + int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); + double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); + int surfaceClearance = Math.max(0, profile.surfaceClearance()); + int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); + double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); + double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); + boolean allowSurfaceBreak = profile.allowSurfaceBreak(); if (maxY < minY) { return 0; } @@ -263,10 +265,10 @@ public class IrisCaveCarver3D { // IrisStyledRange.get() resolves its CNG per call, which costs a cache-key allocation, // a capturing lambda and a shared LRU touch. The CNG is constant for (thresholdRng, data), // so resolve it once here and replicate the min==max / isFlat short circuits verbatim. - IrisStyledRange densityThreshold = profile.getDensityThreshold(); + IrisStyledRange densityThreshold = resolved.densityThreshold(); double thresholdMin = densityThreshold.getMin(); double thresholdMax = densityThreshold.getMax(); - double thresholdBias = profile.getThresholdBias(); + double thresholdBias = profile.thresholdBias(); CNG thresholdDensity = null; double constantThreshold = 0D; if (thresholdMin == thresholdMax) { @@ -2180,7 +2182,7 @@ public class IrisCaveCarver3D { } MatterCavern[] matterByY = scratch.matterByY; - boolean allowLava = profile.isAllowLava(); + boolean allowLava = profile.allowLava(); int lavaHeight = engine.getDimension().getCaveLavaHeight(); for (int y = minY; y <= maxY; y++) { @@ -2354,8 +2356,8 @@ public class IrisCaveCarver3D { } double[] verticalEdgeFade = scratch.verticalEdgeFade; - int fadeRange = Math.max(0, profile.getVerticalEdgeFade()); - double fadeStrength = Math.max(0D, profile.getVerticalEdgeFadeStrength()); + int fadeRange = Math.max(0, profile.verticalEdgeFade()); + double fadeStrength = Math.max(0D, profile.verticalEdgeFadeStrength()); if (size <= 0 || fadeRange <= 0 || maxY <= minY || fadeStrength <= 0D) { Arrays.fill(verticalEdgeFade, 0, size, 0D); return verticalEdgeFade; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 5de9e197d..a36e987fb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -19,6 +19,9 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; @@ -31,12 +34,9 @@ import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.mantle.MantleWriter; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.engine.object.placement.DecayControlPlacer; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveAnchorMode; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; @@ -234,8 +234,8 @@ public class ObjectPlacing { int rejected = 0; int nullObjects = 0; int errors = 0; - IrisCaveProfile biomeCaveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); - IrisCaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome.getCaveProfile()); + CaveProfile biomeCaveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); + CaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome.getCaveProfile()); CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) { @@ -383,12 +383,12 @@ public class ObjectPlacing { @ChunkCoordinates private void placeProceduralObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region) { - IrisCaveProfile surfaceCaveProfile = resolveCaveProfile(surfaceBiome.getCaveProfile(), region.getCaveProfile()); - IrisCaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome == null ? null : caveBiome.getCaveProfile()); + CaveProfile surfaceCaveProfile = resolveCaveProfile(surfaceBiome.getCaveProfile(), region.getCaveProfile()); + CaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome == null ? null : caveBiome.getCaveProfile()); placeProceduralFrom(writer, rng, x, z, surfaceBiome.getProceduralObjects(), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); placeProceduralFrom(writer, rng, x, z, region.getProceduralObjects(), region.getName(), regionCaveProfile, null); if (caveBiome != null && caveBiome != surfaceBiome) { - IrisCaveProfile caveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); + CaveProfile caveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); placeProceduralFrom(writer, rng, x, z, caveBiome.getProceduralObjects(), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); } } @@ -401,7 +401,7 @@ public class ObjectPlacing { int z, IrisProceduralObjects proceduralObjects, String scope, - IrisCaveProfile caveProfile, + CaveProfile caveProfile, String expectedCaveBiomeKey ) { if (proceduralObjects == null || proceduralObjects.isEmpty()) { @@ -427,9 +427,9 @@ public class ObjectPlacing { IrisObjectPlacement placement = p.asPlacement(); boolean carving = placement.getCarvingSupport() == CarvingMode.CARVING_ONLY; - IrisCaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); + CaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); if (placement.getMode() == ObjectPlaceMode.CEILING_HANG) { - anchorMode = IrisCaveAnchorMode.CEILING; + anchorMode = CaveAnchorMode.CEILING; } int anchorScanStep = resolveAnchorScanStep(caveProfile); int minDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); @@ -558,7 +558,7 @@ public class ObjectPlacing { RNG rng, int minX, int minZ, - IrisCaveAnchorMode anchorMode, + CaveAnchorMode anchorMode, int anchorScanStep, int minDepthBelowSurface, int searchAttempts, @@ -774,7 +774,7 @@ public class ObjectPlacing { int chunkX, int chunkZ, IrisObjectPlacement objectPlacement, - IrisCaveProfile caveProfile, + CaveProfile caveProfile, IrisComplex complex, boolean traceRegen, int metricChunkX, @@ -791,9 +791,9 @@ public class ObjectPlacing { int minX = chunkX << 4; int minZ = chunkZ << 4; int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); - IrisCaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); + CaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) { - anchorMode = IrisCaveAnchorMode.CEILING; + anchorMode = CaveAnchorMode.CEILING; } int anchorScanStep = resolveAnchorScanStep(caveProfile); int objectMinDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); @@ -1107,7 +1107,7 @@ public class ObjectPlacing { IrisObject object, int densityIndex, int density, - IrisCaveAnchorMode anchorMode, + CaveAnchorMode anchorMode, int anchorSearchAttempts, int anchorScanStep, int objectMinDepthBelowSurface, @@ -1208,13 +1208,13 @@ public class ObjectPlacing { return effectivePlacement; } - private IrisObjectPlacement resolveCavePlacement(IrisObjectPlacement objectPlacement, IrisObject object, IrisCaveProfile caveProfile) { + private IrisObjectPlacement resolveCavePlacement(IrisObjectPlacement objectPlacement, IrisObject object, CaveProfile caveProfile) { IrisObjectPlacement resolvedPlacement = resolveEffectivePlacement(objectPlacement, object); if (resolvedPlacement.getMode() != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { return resolvedPlacement; } - ObjectPlaceMode profileMode = caveProfile.getDefaultObjectPlaceMode(); + ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null); if (profileMode == null) { return resolvedPlacement; } @@ -1237,7 +1237,7 @@ public class ObjectPlacing { return maxAnchorY + 1; } - private int findCaveAnchorY(MantleWriter writer, RNG rng, int x, int z, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, CaveAnchorCache anchorCache) { + private int findCaveAnchorY(MantleWriter writer, RNG rng, int x, int z, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, CaveAnchorCache anchorCache) { KList anchors = anchorCache.get(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z); if (anchors.isEmpty()) { return -1; @@ -1250,7 +1250,7 @@ public class ObjectPlacing { return anchors.get(rng.i(anchors.size())); } - private KList scanCaveAnchorColumn(MantleWriter writer, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z, CaveAnchorCache anchorCache) { + private KList scanCaveAnchorColumn(MantleWriter writer, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z, CaveAnchorCache anchorCache) { int height = engine.getHeight(); int step = Math.max(1, anchorScanStep); int surfaceY = anchorCache.getSurfaceHeight(x, z); @@ -1264,7 +1264,7 @@ public class ObjectPlacing { return scanCaveAnchorRange(anchorMode, step, carvedHeight, BEDROCK_CLEARANCE, maxAnchorExclusive, carvedColumn); } - private KList scanCaveAnchorRange(IrisCaveAnchorMode anchorMode, int step, int height, int minAnchorY, int maxAnchorY, byte[] carvedColumn) { + private KList scanCaveAnchorRange(CaveAnchorMode anchorMode, int step, int height, int minAnchorY, int maxAnchorY, byte[] carvedColumn) { KList anchors = new KList<>(); int startY = alignAnchorScanStart(minAnchorY, step); for (int y = startY; y < maxAnchorY; y += step) { @@ -1308,7 +1308,7 @@ public class ObjectPlacing { return false; } - private boolean matchesCaveAnchor(IrisCaveAnchorMode anchorMode, boolean solidBelow, boolean solidAbove) { + private boolean matchesCaveAnchor(CaveAnchorMode anchorMode, boolean solidBelow, boolean solidAbove) { return switch (anchorMode) { case PROFILE_DEFAULT, FLOOR -> solidBelow; case CEILING -> solidAbove; @@ -1317,13 +1317,13 @@ public class ObjectPlacing { }; } - private IrisCaveProfile resolveCaveProfile(IrisCaveProfile preferred, IrisCaveProfile secondary) { - IrisCaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); - if (preferred != null && preferred.isEnabled()) { + private CaveProfile resolveCaveProfile(CaveProfile preferred, CaveProfile secondary) { + CaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); + if (preferred != null && preferred.enabled()) { return preferred; } - if (secondary != null && secondary.isEnabled()) { + if (secondary != null && secondary.enabled()) { return secondary; } @@ -1331,49 +1331,49 @@ public class ObjectPlacing { return dimensionProfile; } - return new IrisCaveProfile(); + return new CaveProfile(); } - private IrisCaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, IrisCaveProfile caveProfile) { - IrisCaveAnchorMode placementMode = objectPlacement.getCaveAnchorMode(); - if (placementMode != null && !placementMode.equals(IrisCaveAnchorMode.PROFILE_DEFAULT)) { + private CaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, CaveProfile caveProfile) { + CaveAnchorMode placementMode = objectPlacement.getCaveAnchorMode(); + if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { return placementMode; } if (caveProfile == null) { - return IrisCaveAnchorMode.FLOOR; + return CaveAnchorMode.FLOOR; } - IrisCaveAnchorMode profileMode = caveProfile.getDefaultObjectAnchor(); - if (profileMode == null || profileMode.equals(IrisCaveAnchorMode.PROFILE_DEFAULT)) { - return IrisCaveAnchorMode.FLOOR; + CaveAnchorMode profileMode = caveProfile.defaultObjectAnchor(); + if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return CaveAnchorMode.FLOOR; } return profileMode; } - private int resolveAnchorScanStep(IrisCaveProfile caveProfile) { + private int resolveAnchorScanStep(CaveProfile caveProfile) { if (caveProfile == null) { return 1; } - return Math.max(1, caveProfile.getAnchorScanStep()); + return Math.max(1, caveProfile.anchorScanStep()); } - private int resolveObjectMinDepthBelowSurface(IrisCaveProfile caveProfile) { + private int resolveObjectMinDepthBelowSurface(CaveProfile caveProfile) { if (caveProfile == null) { return 6; } - return Math.max(0, caveProfile.getObjectMinDepthBelowSurface()); + return Math.max(0, caveProfile.objectMinDepthBelowSurface()); } - private int resolveAnchorSearchAttempts(IrisCaveProfile caveProfile) { + private int resolveAnchorSearchAttempts(CaveProfile caveProfile) { if (caveProfile == null) { return 6; } - return Math.max(1, caveProfile.getAnchorSearchAttempts()); + return Math.max(1, caveProfile.anchorSearchAttempts()); } private boolean isRegenTraceThread() { @@ -1602,7 +1602,7 @@ public class ObjectPlacing { this.surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); } - private KList get(MantleWriter writer, IrisCaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z) { + private KList get(MantleWriter writer, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z) { if (anchorScanStep > 65535 || objectMinDepthBelowSurface > 65535) { return scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 2cb64c468..d69592f3d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -18,6 +18,9 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.carve.CaveFieldModule; +import art.arcane.iris.builtin.carve.CaveProfile; +import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisMantleChunk; @@ -46,6 +49,12 @@ public final class CarveModule implements IrisModule { return ModuleInfo.of("iris:carve", "Caves", VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(CaveProfile.class); + registry.registerHeldType(CaveFieldModule.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index 6b40570a3..acbf04d8d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.AnchorHeight; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.PlacementStageContext; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index f9abd4bb8..80c8e2469 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.blocks.ObjectReplace; import com.volmit.FeatureRegistry; @@ -32,7 +33,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectShaping; import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.collection.KList; 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 index 08c9f9d24..f548a9404 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.carve.CarvingMode; +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; @@ -39,8 +41,6 @@ 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.engine.object.terrain.carving.CarvingMode; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveAnchorMode; import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.core.loader.IrisData; @@ -153,7 +153,7 @@ public class IrisObjectPlacement { @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 IrisCaveAnchorMode caveAnchorMode = IrisCaveAnchorMode.PROFILE_DEFAULT; + 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.") diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 3a3b5a815..1987e39c2 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.validate.ObjectLimit; import com.volmit.FeatureRegistry; @@ -27,7 +28,6 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.NativeStructureVolume; import art.arcane.iris.engine.framework.PlacedObject; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import com.volmit.IrisModule; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java index e9de0ef73..dde80bf4b 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.procedural.coral; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; @@ -28,7 +29,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.Desc; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java index 7cb60c2bb..6de4cedff 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.procedural.crystal; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; @@ -28,7 +29,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.Desc; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java index 810fb3b50..eaf4a1478 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; @@ -28,7 +29,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.Desc; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java index 66e6a6e92..f22fad06e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; @@ -28,7 +29,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.Desc; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java index 004da5435..c092881a5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.procedural.ruin; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; @@ -29,7 +30,6 @@ import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java index 2b7d32351..fcb71f56a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; @@ -28,7 +29,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.terrain.carving.CarvingMode; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java deleted file mode 100644 index 7c5b700d2..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveFieldModule.java +++ /dev/null @@ -1,39 +0,0 @@ -package art.arcane.iris.engine.object.terrain.carving; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.value.IrisRange; -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("cave-field-module") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a modular cave-density layer.") -@Data -public class IrisCaveFieldModule { - @Desc("Density style used by this module.") - private IrisGeneratorStyle style = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @MinNumber(0) - @Desc("Layer contribution multiplier.") - private double weight = 1; - - @MinNumber(-1) - @MaxNumber(1) - @Desc("Threshold offset applied to this layer before blending.") - private double threshold = 0; - - @Desc("Vertical bounds where this module can contribute, in engine-local Y where 0 is the bottom of the dimension, not world Y.") - private IrisRange verticalRange = new IrisRange(0, 384); - - @Desc("Invert this module before weighting.") - private boolean invert = false; -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java deleted file mode 100644 index 04db427b4..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfile.java +++ /dev/null @@ -1,153 +0,0 @@ -package art.arcane.iris.engine.object.terrain.carving; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.value.IrisRange; -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.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("cave-profile") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a configurable 3D cave profile.") -@Data -public class IrisCaveProfile { - @Desc("Enable profile-driven cave carving.") - private boolean enabled = false; - - @Desc("Global vertical bounds for profile cave carving, in engine-local Y where 0 is the bottom of the dimension, not world Y.") - private IrisRange verticalRange = new IrisRange(0, 384); - - @MinNumber(0) - @MaxNumber(128) - @Desc("Vertical fade range applied near cave profile min/max bounds to avoid abrupt hard-stop ceilings/floors.") - private int verticalEdgeFade = 20; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Strength of the vertical edge fade at cave profile min/max bounds.") - private double verticalEdgeFadeStrength = 0.18; - - @Desc("Base density style for cave field generation.") - private IrisGeneratorStyle baseDensityStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @Desc("Detail density style blended into base caves.") - private IrisGeneratorStyle detailDensityStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX); - - @Desc("Warp style used to distort cave coordinates.") - private IrisGeneratorStyle warpStyle = new IrisGeneratorStyle(NoiseStyle.FLAT); - - @MinNumber(0) - @Desc("Base cave field multiplier.") - private double baseWeight = 1; - - @MinNumber(0) - @Desc("Detail cave field multiplier.") - private double detailWeight = 0.35; - - @MinNumber(0) - @Desc("Coordinate warp strength for cave fields.") - private double warpStrength = 0; - - @Desc("Threshold range used for carve cutoff decisions.") - private IrisStyledRange densityThreshold = new IrisStyledRange(-0.2, 0.2, NoiseStyle.CELLULAR_IRIS_DOUBLE.style()); - - @MinNumber(0) - @MaxNumber(1) - @Desc("Extra threshold bias subtracted from sampled threshold before carve tests.") - private double thresholdBias = 0.16; - - @MinNumber(1) - @MaxNumber(8) - @Desc("Vertical sample step used while evaluating cave density.") - private int sampleStep = 1; - - @Desc("Use adaptive cave density prediction so only threshold-adjacent cells fall back to full-resolution evaluation.") - private boolean adaptiveSampling = true; - - @MinNumber(2) - @MaxNumber(4) - @Desc("Horizontal adaptive predictor tuning. The carver always samples the predictor grid at a fixed step of 8; values below 8 only widen the ambiguity margin slightly and do not tighten the grid.") - private int adaptiveSampleStep = 2; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Additional adaptive ambiguity margin used before the cave predictor falls back to exact sampling.") - private double adaptiveThresholdMargin = 0.04; - - @MinNumber(0) - @MaxNumber(64) - @Desc("Minimum solid clearance below terrain surface where carving may occur.") - private int surfaceClearance = 4; - - @Desc("Allow profile-driven cave carving to break through terrain surface in selected columns.") - private boolean allowSurfaceBreak = true; - - @Desc("Noise style used to decide where surface-breaking cave columns are allowed.") - private IrisGeneratorStyle surfaceBreakStyle = new IrisGeneratorStyle(NoiseStyle.SIMPLEX).zoomed(0.08); - - @MinNumber(-1) - @MaxNumber(1) - @Desc("Minimum signed surface-break noise value required before near-surface carving is allowed.") - private double surfaceBreakNoiseThreshold = 0.62; - - @MinNumber(0) - @MaxNumber(64) - @Desc("Near-surface depth window used for surface-break carve logic.") - private int surfaceBreakDepth = 18; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Additional threshold boost applied while carving in the surface-break depth window.") - private double surfaceBreakThresholdBoost = 0.2; - - @MinNumber(0) - @MaxNumber(64) - @Desc("Minimum depth below terrain surface required for cave-only object anchor placement.") - private int objectMinDepthBelowSurface = 6; - - @ArrayType(type = IrisCaveFieldModule.class, min = 1) - @Desc("Additional layered cave-density modules.") - private KList modules = new KList<>(); - - @Desc("Default cave anchor mode for cave-only object placement.") - private IrisCaveAnchorMode defaultObjectAnchor = IrisCaveAnchorMode.FLOOR; - - @Desc("Default placement mode for cave objects. Only applies to placements that are still on the default CENTER_HEIGHT mode; an explicit mode on the placement always wins. Stilt modes tile the object base block down to the cave floor surface. FAST_MIN_STILT is recommended for cave objects to prevent floating.") - private ObjectPlaceMode defaultObjectPlaceMode = null; - - @MinNumber(1) - @MaxNumber(8) - @Desc("Vertical scan step used while searching cave anchors.") - private int anchorScanStep = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("Maximum random column retries while searching a valid cave object anchor in the chunk.") - private int anchorSearchAttempts = 6; - - @Desc("Allow cave fluid placement from the dimension fluid palette below fluid level.") - private boolean allowFluid = true; - - @MinNumber(0) - @MaxNumber(64) - @Desc("Minimum depth below terrain surface required before cave fluid may be placed.") - private int fluidMinDepthBelowSurface = 12; - - @Desc("Require solid floor support below cave fluid to reduce unsupported fluid flows.") - private boolean fluidRequiresFloor = true; - - @Desc("Allow cave lava placement based on lava height.") - private boolean allowLava = true; -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java index 490fa0840..4eaef2997 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.terrain.carving; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; @@ -31,7 +32,8 @@ public final class IrisCaveProfileSampler { private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; private final IrisData data; - private final IrisCaveProfile profile; + private final CaveProfile profile; + private final ResolvedCaveProfile resolved; private final CNG baseDensity; private final CNG detailDensity; private final CNG warpDensity; @@ -45,24 +47,25 @@ public final class IrisCaveProfileSampler { private final boolean hasWarp; private final boolean hasModules; - public IrisCaveProfileSampler(Engine engine, IrisCaveProfile profile) { + public IrisCaveProfileSampler(Engine engine, CaveProfile profile) { this.data = engine.getData(); this.profile = profile; + this.resolved = ResolvedCaveProfile.of(profile); List moduleStates = new ArrayList<>(); RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = profile.getBaseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = profile.getDetailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = profile.getWarpStyle().create(baseRng.nextParallelRNG(770_713), data); + this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); + this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); + this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); this.thresholdRng = baseRng.nextParallelRNG(489_112); - this.baseWeight = profile.getBaseWeight(); - this.detailWeight = profile.getDetailWeight(); - this.warpStrength = profile.getWarpStrength(); + this.baseWeight = profile.baseWeight(); + this.detailWeight = profile.detailWeight(); + this.warpStrength = profile.warpStrength(); this.hasWarp = warpStrength > 0D; double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; - for (IrisCaveFieldModule module : profile.getModules()) { - CNG moduleDensity = module.getStyle().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + for (ResolvedCaveProfile.Module module : resolved.modules()) { + CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); ModuleState state = new ModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); @@ -73,7 +76,7 @@ public final class IrisCaveProfileSampler { double normalization = weight <= 0 ? 1D : weight; this.inverseNormalization = 1D / normalization; this.hasModules = modules.length > 0; - this.enabled = profile.isEnabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); + this.enabled = profile.enabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); } public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { @@ -81,7 +84,7 @@ public final class IrisCaveProfileSampler { return false; } - double threshold = profile.getDensityThreshold().get(thresholdRng, x, z, data) - profile.getThresholdBias(); + double threshold = resolved.densityThreshold().get(thresholdRng, x, z, data) - profile.thresholdBias(); threshold += floatingThresholdBias(floatingCarveThreshold); return sampleDensity(x, y, z) <= threshold; } @@ -144,14 +147,14 @@ public final class IrisCaveProfileSampler { private final double threshold; private final boolean invert; - private ModuleState(IrisCaveFieldModule module, CNG density) { - IrisRange range = module.getVerticalRange(); + private ModuleState(ResolvedCaveProfile.Module module, CNG density) { + IrisRange range = module.verticalRange(); this.density = density; this.minY = (int) Math.floor(range.getMin()); this.maxY = (int) Math.ceil(range.getMax()); - this.weight = module.getWeight(); - this.threshold = module.getThreshold(); - this.invert = module.isInvert(); + this.weight = module.weight(); + this.threshold = module.threshold(); + this.invert = module.invert(); } private boolean isActive(int y) { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java new file mode 100644 index 000000000..c4cdb4918 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java @@ -0,0 +1,123 @@ +/* + * 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.terrain.carving; + +import art.arcane.iris.builtin.carve.CaveFieldModule; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.core.modules.IrisValues; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.noise.IrisStyledRange; +import art.arcane.iris.engine.object.value.IrisRange; + +import java.util.List; + +/** + * The parts of a {@link CaveProfile} that the carvers read as Iris's own noise and range types, made once per carver: + * the generator styles that build the cave fields, the ranges and the extra field modules. The carvers read these + * through Iris's generators because those keep Iris's coordinate caches and fast signed reads, which the cave + * hot paths rely on. + */ +public final class ResolvedCaveProfile { + private final IrisRange verticalRange; + private final IrisGeneratorStyle baseDensityStyle; + private final IrisGeneratorStyle detailDensityStyle; + private final IrisGeneratorStyle warpStyle; + private final IrisGeneratorStyle surfaceBreakStyle; + private final IrisStyledRange densityThreshold; + private final List modules; + + private ResolvedCaveProfile(CaveProfile settings) { + this.verticalRange = IrisValues.range(settings.verticalRange()); + this.baseDensityStyle = IrisValues.generatorStyle(settings.baseDensityStyle()); + this.detailDensityStyle = IrisValues.generatorStyle(settings.detailDensityStyle()); + this.warpStyle = IrisValues.generatorStyle(settings.warpStyle()); + this.surfaceBreakStyle = IrisValues.generatorStyle(settings.surfaceBreakStyle()); + this.densityThreshold = IrisValues.styledRange(settings.densityThreshold()); + this.modules = settings.modules().stream().map(Module::new).toList(); + } + + public static ResolvedCaveProfile of(CaveProfile settings) { + return new ResolvedCaveProfile(settings); + } + + public IrisRange verticalRange() { + return verticalRange; + } + + public IrisGeneratorStyle baseDensityStyle() { + return baseDensityStyle; + } + + public IrisGeneratorStyle detailDensityStyle() { + return detailDensityStyle; + } + + public IrisGeneratorStyle warpStyle() { + return warpStyle; + } + + public IrisGeneratorStyle surfaceBreakStyle() { + return surfaceBreakStyle; + } + + public IrisStyledRange densityThreshold() { + return densityThreshold; + } + + public List modules() { + return modules; + } + + /** One {@link CaveFieldModule} with its style and range as Iris's types. */ + public static final class Module { + private final IrisGeneratorStyle style; + private final double weight; + private final double threshold; + private final IrisRange verticalRange; + private final boolean invert; + + private Module(CaveFieldModule settings) { + this.style = IrisValues.generatorStyle(settings.style()); + this.weight = settings.weight(); + this.threshold = settings.threshold(); + this.verticalRange = IrisValues.range(settings.verticalRange()); + this.invert = settings.invert(); + } + + public IrisGeneratorStyle style() { + return style; + } + + public double weight() { + return weight; + } + + public double threshold() { + return threshold; + } + + public IrisRange verticalRange() { + return verticalRange; + } + + public boolean invert() { + return invert; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java index 151f17205..3d28b0afb 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java @@ -125,7 +125,7 @@ public class IrisFloatingChildBiomes implements IRare { return carvingProfileSamplerCache.aquire(() -> { IrisBiome resolved = resolveCarvingBiome(carving, engine, data); - if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().isEnabled()) { + if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().enabled()) { return null; } 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 index 10f40aafc..63e72a717 100644 --- 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 @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.world.biome; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.decoration.IrisDecorationPart; import art.arcane.iris.engine.object.decoration.IrisDecorator; import art.arcane.iris.engine.object.entity.IrisEffect; @@ -31,7 +32,6 @@ import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.terrain.IrisBiomeLayerGenerator; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.deposit.IrisBiomeOres; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; @@ -151,7 +151,7 @@ public class IrisBiome extends IrisRegistrant implements IRare { @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") private int lockLayersMax = 7; @Desc("Profile-driven 3D cave configuration") - private IrisCaveProfile caveProfile = new IrisCaveProfile(); + private CaveProfile caveProfile = new CaveProfile(); @MinNumber(1) @MaxNumber(512) @Desc("The rarity of this biome (integer)") 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 index 206b1d1ee..6c268f50e 100644 --- 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 @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.world.dimension; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.image.IrisImageMap; @@ -33,7 +34,6 @@ import art.arcane.iris.engine.object.procedural.tree.IrisTreeSettings; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.vanilla.IrisImportedStructureControl; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; @@ -191,7 +191,7 @@ public class IrisDimension extends IrisRegistrant { @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") private KList carving = new KList<>(); @Desc("Profile-driven 3D cave configuration") - private IrisCaveProfile caveProfile = new IrisCaveProfile(); + private CaveProfile caveProfile = new CaveProfile(); @Desc("Refuse to place surface objects and trees over carved surface openings.") private boolean requireObjectSurfaceSupport = true; @MinNumber(0) 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 index b128642a1..8c03c3310 100644 --- 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 @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.world.region; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.entity.IrisEffect; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.loot.IrisBlockDrops; @@ -25,7 +26,6 @@ import art.arcane.iris.engine.object.loot.IrisLootReference; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfile; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; @@ -131,7 +131,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { @Desc("How large cave biomes are in this region") private double caveBiomeZoom = 1; @Desc("Profile-driven 3D cave configuration") - private IrisCaveProfile caveProfile = new IrisCaveProfile(); + private CaveProfile caveProfile = new CaveProfile(); @RegistryListResource(IrisBiome.class) @Required @ArrayType(min = 1, type = String.class) From 910eab1f7992c8c0413a688deedac388a37eb9ad Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:16:35 +0200 Subject: [PATCH 037/139] iris:spawn: EntitySpawns provider; entity, item and attribute Bukkit behaviour moved out of the model classes --- source-patterns.txt | 1 + .../object/entity/IrisAttributeModifier.java | 88 ---- .../iris/engine/object/entity/IrisEffect.java | 35 -- .../iris/engine/object/entity/IrisEntity.java | 395 ------------------ .../engine/object/entity/IrisEntitySpawn.java | 173 -------- .../object/entity/spawn/IrisSurface.java | 28 -- .../engine/object/loot/IrisEnchantment.java | 40 -- .../iris/engine/object/loot/IrisLoot.java | 188 +-------- .../engine/object/loot/IrisLootTable.java | 34 -- .../object/loot/IrisVanillaLootTable.java | 44 +- .../engine/object/marker/IrisCommand.java | 18 +- .../iris/engine/spawn/EntityResolution.java | 128 ++++++ .../iris/engine/spawn/EntitySpawning.java | 269 ++++++++++++ .../arcane/iris/engine/spawn/SpawnModule.java | 48 +++ 14 files changed, 453 insertions(+), 1036 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java diff --git a/source-patterns.txt b/source-patterns.txt index f4f3d130d..31bac204e 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -17,3 +17,4 @@ 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/object/entity/IrisAttributeModifier.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java index fe7b4fe91..52e4d068c 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java @@ -23,25 +23,12 @@ 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.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; -import org.bukkit.attribute.Attributable; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.attribute.AttributeModifier.Operation; -import org.bukkit.inventory.EquipmentSlotGroup; -import org.bukkit.inventory.meta.ItemMeta; -import java.util.Locale; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; @Snippet("attribute-modifier") @Accessors(chain = true) @@ -50,8 +37,6 @@ import java.util.concurrent.ConcurrentHashMap; @Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") @Data public class IrisAttributeModifier { - private static final Set WARNED_ATTRIBUTES = ConcurrentHashMap.newKeySet(); - @Required @Desc("The Attribute type key such as max_health or minecraft:armor. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.") private String attribute = null; @@ -75,80 +60,7 @@ public class IrisAttributeModifier { @Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.") private double chance = 1; - public void apply(RNG rng, ItemMeta meta) { - if (rng.nextDouble() < getChance()) { - Attribute resolved = resolveAttribute(); - if (resolved == null) { - return; - } - meta.addAttributeModifier(resolved, createModifier(rng)); - } - } - - public void apply(RNG rng, Attributable meta) { - if (rng.nextDouble() < getChance()) { - Attribute resolved = resolveAttribute(); - if (resolved == null) { - return; - } - meta.getAttribute(resolved).addModifier(createModifier(rng)); - } - } - public double getAmount(RNG rng) { return rng.d(getMinAmount(), getMaxAmount()); } - - private Attribute resolveAttribute() { - if (attribute == null || attribute.isBlank()) { - return null; - } - String value = attribute.trim().toLowerCase(Locale.ROOT); - Attribute resolved; - if (value.contains(":")) { - NamespacedKey key = NamespacedKey.fromString(value); - resolved = key == null ? null : Registry.ATTRIBUTE.get(key); - } else { - resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value)); - if (resolved == null && value.startsWith("generic_")) { - resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic_".length()))); - } - if (resolved == null && value.startsWith("generic.")) { - resolved = Registry.ATTRIBUTE.get(NamespacedKey.minecraft(value.substring("generic.".length()))); - } - } - if (resolved == null && WARNED_ATTRIBUTES.add(value)) { - IrisLogging.warn("Unknown attribute '" + attribute + "' in attribute-modifier '" + name + "'"); - } - return resolved; - } - - private Operation resolveOperation() { - if (operation == null || operation.isBlank()) { - return Operation.ADD_NUMBER; - } - try { - return Operation.valueOf(operation.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return Operation.ADD_NUMBER; - } - } - - private AttributeModifier createModifier(RNG rng) { - NamespacedKey key = NamespacedKey.minecraft(generateModifierKey()); - return new AttributeModifier(key, getAmount(rng), resolveOperation(), EquipmentSlotGroup.ANY); - } - - private String generateModifierKey() { - String source = getName() == null ? "modifier" : getName(); - String normalized = source.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9/._-]", "_"); - if (normalized.isBlank()) { - normalized = "modifier"; - } - if (normalized.length() > 32) { - normalized = normalized.substring(0, 32); - } - String random = UUID.randomUUID().toString().replace("-", ""); - return normalized + "_" + random; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java index 93e9baa77..b07f836ad 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java @@ -285,39 +285,4 @@ public class IrisEffect { } }); } - - public void apply(Entity p) { - if (!shouldApplyNow()) { - return; - } - - J.runEntity(p, () -> { - Sound soundType = getSound(); - Particle particleType = getParticleEffect(); - if (soundType != null) { - Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); - p.getWorld().playSound(part, soundType, (float) volume, (float) RNG.r.d(minPitch, maxPitch)); - } - - if (particleType != null) { - Location part = p.getLocation().clone().add(0, 0.25, 0).add(new Vector(1, 1, 1).multiply(RNG.r.d())).subtract(new Vector(1, 1, 1).multiply(RNG.r.d())); - part.add(RNG.r.d(), 0, RNG.r.d()); - if (extra != 0) { - p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), - part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, - extra); - } else { - p.getWorld().spawnParticle(particleType, part.getX(), part.getY() + RNG.r.i(particleOffset), part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ); - } - } - }); - } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java index 5821b383b..709d4c2b1 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java @@ -19,70 +19,20 @@ package art.arcane.iris.engine.object.entity; import art.arcane.iris.engine.object.entity.spawn.IrisSurface; -import art.arcane.iris.engine.object.loot.InventorySlotType; import art.arcane.iris.engine.object.loot.IrisLoot; import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.marker.IrisCommand; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.core.link.Identifier; import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.service.EntityRiseSVC; -import art.arcane.iris.core.service.ExternalDataSVC; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.platform.EngineBukkitOps; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.RegistryListEntityType; import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity; import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.util.common.data.registry.RegistryUtil; -import art.arcane.iris.platform.bukkit.BukkitWorld; -import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.common.format.C; -import art.arcane.volmlib.util.math.M; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.common.plugin.Chunks; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.Sound; -import org.bukkit.attribute.Attributable; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Mob; -import org.bukkit.entity.Panda; -import org.bukkit.entity.Villager; -import org.bukkit.entity.Panda.Gene; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.loot.LootContext; -import org.bukkit.loot.LootTable; -import org.bukkit.loot.Lootable; -import org.bukkit.util.Vector; - -import java.util.Collection; -import java.util.Locale; -import java.util.Random; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static art.arcane.iris.util.common.data.registry.Particles.ITEM; @SuppressWarnings("ALL") @Accessors(chain = true) @@ -194,355 +144,10 @@ public class IrisEntity extends IrisRegistrant { @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") private KList rawCommands = new KList<>(); - public EntityType getBukkitType() { - if (type == null || type.isBlank()) { - return EntityType.UNKNOWN; - } - - NamespacedKey key = NamespacedKey.fromString(type.trim().toLowerCase(Locale.ROOT)); - - if (key == null) { - return EntityType.UNKNOWN; - } - - EntityType entityType = RegistryUtil.lookup(EntityType.class).get(key); - return entityType == null ? EntityType.UNKNOWN : entityType; - } - - public CreatureSpawnEvent.SpawnReason getBukkitReason() { - if (reason == null || reason.isBlank()) { - return CreatureSpawnEvent.SpawnReason.NATURAL; - } - - try { - return CreatureSpawnEvent.SpawnReason.valueOf(reason.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return CreatureSpawnEvent.SpawnReason.NATURAL; - } - } - - public Gene getBukkitPandaMainGene() { - return resolveGene(pandaMainGene); - } - - public Gene getBukkitPandaHiddenGene() { - return resolveGene(pandaHiddenGene); - } - - private static Gene resolveGene(String gene) { - if (gene == null || gene.isBlank()) { - return Gene.NORMAL; - } - - try { - return Gene.valueOf(gene.trim().toUpperCase(Locale.ROOT)); - } catch (IllegalArgumentException e) { - return Gene.NORMAL; - } - } - - public Entity spawn(Engine gen, Location at) { - return spawn(gen, at, new RNG(at.hashCode())); - } - - public Entity spawn(Engine gen, Location at, RNG rng) { - if (!Chunks.isSafe(at)) { - return null; - } - if (isSpawnEffectRiseOutOfGround()) { - AtomicReference f = new AtomicReference<>(at); - try { - J.sfut(() -> { - if (Chunks.hasPlayersNearby(f.get())) { - Location b = f.get().clone(); - Location start = new Location(b.getWorld(), b.getX(), b.getY() - 5, b.getZ()); - f.set(start); - } - }).get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - IrisLogging.reportError("Iris entity spawn preparation was interrupted.", e); - } catch (ExecutionException e) { - IrisLogging.reportError("Iris entity spawn preparation failed.", e); - } - at = f.get(); - } - - Entity ee = doSpawn(at); - - if (ee == null && !Chunks.isSafe(at)) { - return null; - } - - if (isSpecialType() && !applySettingsToCustomMobAnyways) { - return ee; - } - - if (ee == null) { - return null; - } - - Entity e = ee; - e.setCustomName(getCustomName() != null ? C.translateAlternateColorCodes('&', getCustomName()) : null); - e.setCustomNameVisible(isCustomNameVisible()); - e.setGlowing(isGlowing()); - e.setGravity(isGravity()); - e.setInvulnerable(isInvulnerable()); - e.setSilent(isSilent()); - e.setPersistent(isKeepEntity() || IrisSettings.get().getWorld().isForcePersistEntities()); - - int gg = 0; - for (IrisEntity i : passengers) { - Entity passenger = i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++)); - if (passenger == null) { - continue; - } - - if (Bukkit.isPrimaryThread()) { - e.addPassenger(passenger); - } else { - J.runEntity(e, () -> e.addPassenger(passenger)); - } - } - - if (e instanceof Attributable) { - Attributable a = (Attributable) e; - - for (IrisAttributeModifier i : getAttributes()) { - i.apply(rng, a); - } - } - - if (e instanceof Lootable) { - Lootable l = (Lootable) e; - - if (getLoot().getTables().isNotEmpty()) { - BukkitOps.bindLoot(this, gen, l, at, rng); - } - } - - if (e instanceof LivingEntity) { - LivingEntity l = (LivingEntity) e; - l.setAI(isAi()); - l.setCanPickupItems(isPickupItems()); - - if (getLeashHolder() != null) { - l.setLeashHolder(getLeashHolder().spawn(gen, at, rng.nextParallelRNG(234548))); - } - - l.setRemoveWhenFarAway(isRemovable()); - - if (getHelmet() != null && LootResolver.oneIn(rng, getHelmet().getRarity())) { - l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng)); - } - - if (getChestplate() != null && LootResolver.oneIn(rng, getChestplate().getRarity())) { - l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng)); - } - - if (getLeggings() != null && LootResolver.oneIn(rng, getLeggings().getRarity())) { - l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng)); - } - - if (getBoots() != null && LootResolver.oneIn(rng, getBoots().getRarity())) { - l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng)); - } - - if (getMainHand() != null && LootResolver.oneIn(rng, getMainHand().getRarity())) { - l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng)); - } - - if (getOffHand() != null && LootResolver.oneIn(rng, getOffHand().getRarity())) { - l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng)); - } - } - - if (e instanceof Ageable && isBaby()) { - ((Ageable) e).setBaby(); - } - - if (e instanceof Panda) { - ((Panda) e).setMainGene(getBukkitPandaMainGene()); - ((Panda) e).setHiddenGene(getBukkitPandaHiddenGene()); - } - - if (e instanceof Villager) { - Villager villager = (Villager) e; - villager.setRemoveWhenFarAway(false); - BukkitOps.persistVillager(villager); - } - - if (e instanceof Mob) { - Mob m = (Mob) e; - m.setAware(isAware()); - } - - if (spawnEffect != null) { - spawnEffect.apply(e); - } - - if (rawCommands.isNotEmpty()) { - final Location fat = at; - final PlatformWorld commandWorld = new BukkitWorld(fat.getWorld()); - rawCommands.forEach(r -> r.run(commandWorld, fat.getBlockX(), fat.getBlockY(), fat.getBlockZ())); - } - - Location finalAt1 = at; - - J.runEntity(e, () -> { - if (isSpawnEffectRiseOutOfGround() && e instanceof LivingEntity && Chunks.hasPlayersNearby(finalAt1)) { - LivingEntity living = (LivingEntity) e; - Location start = finalAt1.clone(); - boolean originalInvulnerable = e.isInvulnerable(); - boolean originalAi = living.hasAI(); - boolean originalCollidable = living.isCollidable(); - int originalNoDamageTicks = living.getNoDamageTicks(); - EntityRiseSVC.stamp(e, originalInvulnerable, originalAi, originalCollidable); - e.setInvulnerable(true); - living.setAI(false); - living.setCollidable(false); - living.setNoDamageTicks(100000); - Runnable restore = () -> restoreRiseState(e, living, originalInvulnerable, originalAi, - originalCollidable, originalNoDamageTicks); - AtomicInteger t = new AtomicInteger(0); - Runnable[] loop = new Runnable[1]; - loop[0] = () -> { - if (t.get() > 100 || e.isDead()) { - restore.run(); - return; - } - - t.incrementAndGet(); - if (e.getLocation().getBlock().getType().isSolid() || living.getEyeLocation().getBlock().getType().isSolid()) { - e.teleport(start.add(new Vector(0, 0.1, 0))); - ItemStack itemCrackData = new ItemStack(living.getEyeLocation().clone().subtract(0, 2, 0).getBlock().getBlockData().getMaterial()); - e.getWorld().spawnParticle(ITEM, living.getEyeLocation(), 6, 0.2, 0.4, 0.2, 0.06f, itemCrackData); - if (M.r(0.2)) { - e.getWorld().playSound(e.getLocation(), Sound.BLOCK_CHORUS_FLOWER_GROW, 0.8f, 0.1f); - } - if (!J.runEntity(e, loop[0], 1, restore)) { - restore.run(); - } - } else { - restore.run(); - } - }; - if (!J.runEntity(e, loop[0], 0, restore)) { - restore.run(); - } - } - }); - - - return e; - } - - private static void restoreRiseState(Entity entity, LivingEntity living, boolean invulnerable, - boolean ai, boolean collidable, int noDamageTicks) { - living.setNoDamageTicks(noDamageTicks); - living.setCollidable(collidable); - living.setAI(ai); - entity.setInvulnerable(invulnerable); - EntityRiseSVC.clearStamp(entity); - } - - private int surfaceY(Location l) { - int m = l.getBlockY(); - - while (m-- > 0) { - Location ll = l.clone(); - ll.setY(m); - - if (ll.getBlock().getType().isSolid()) { - return m; - } - } - - return 0; - } - - private Entity doSpawn(Location at) { - if (!Chunks.isSafe(at)) { - return null; - } - - if (EntityType.UNKNOWN.equals(getBukkitType()) && !isSpecialType()) { - return null; - } - - if (!Bukkit.isPrimaryThread()) { - // Someone called spawn (worldedit maybe?) on a non server thread - // Due to the structure of iris, we will call it sync and busy wait until it's done. - AtomicReference ae = new AtomicReference<>(); - - try { - if (!J.runAt(at, () -> ae.set(doSpawn(at)))) { - return null; - } - } catch (Throwable e) { - return null; - } - PrecisionStopwatch p = PrecisionStopwatch.start(); - - while (ae.get() == null) { - J.sleep(25); - - if (p.getMilliseconds() > 500) { - return null; - } - } - - return ae.get(); - } - - if (isSpecialType()) { - return IrisServices.get(ExternalDataSVC.class).spawnMob(at, Identifier.fromString(specialType)); - } - - - return BukkitPlatform.spawnEntity(at, getBukkitType(), getBukkitReason()); - } - public boolean isSpecialType() { return specialType != null && !specialType.equals(""); } - private static final class BukkitOps { - private static void persistVillager(Villager villager) { - villager.setPersistent(true); - } - - private static void bindLoot(IrisEntity entity, Engine gen, Lootable l, Location finalAt, RNG rng) { - l.setLootTable(new LootTable() { - @Override - public NamespacedKey getKey() { - return new NamespacedKey("iris", "loot-" + entity.hashCode()); - } - - @Override - public Collection populateLoot(Random random, LootContext context) { - KList items = new KList<>(); - - for (String fi : entity.getLoot().getTables()) { - IrisLootTable i = gen.getData().getLootLoader().load(fi); - items.addAll(i.getLoot(gen.isStudio(), gen.getSeedManager().getLoot(), InventorySlotType.STORAGE, finalAt.getWorld(), finalAt.getBlockX(), finalAt.getBlockY(), finalAt.getBlockZ())); - } - - return items; - } - - @Override - public void fillInventory(Inventory inventory, Random random, LootContext context) { - for (ItemStack i : populateLoot(random, context)) { - inventory.addItem(i); - } - - EngineBukkitOps.scramble(gen, inventory, rng); - } - }); - } - } - @Override public String getFolderName() { return "entities"; diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java index 726b501b3..b68abf83c 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java @@ -21,34 +21,18 @@ package art.arcane.iris.engine.object.entity; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.platform.bukkit.BukkitWorldBinding; -import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.Desc; 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.spi.IrisLogging; -import art.arcane.iris.util.common.format.C; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.math.Vector3d; -import art.arcane.volmlib.util.matter.MatterMarker; -import art.arcane.volmlib.util.matter.slices.MarkerMatter; -import art.arcane.iris.util.common.scheduling.J; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.entity.Entity; @Snippet("entity-spawn") @Accessors(chain = true) @@ -75,164 +59,7 @@ public class IrisEntitySpawn implements IRare { private transient IrisSpawner referenceSpawner; private transient IrisMarker referenceMarker; - public int spawn(Engine gen, Chunk c, RNG rng) { - int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns); - int s = 0; - - if (spawns > 0) { - for (int id = 0; id < spawns; id++) { - int x = (c.getX() * 16) + rng.i(16); - int z = (c.getZ() * 16) + rng.i(16); - World world = BukkitWorldBinding.tryBind(gen.getWorld()) ? BukkitWorldBinding.world(gen.getWorld()) : null; - int h = gen.getHeight(x, z, true) + (world == null ? -64 : world.getMinHeight()); - int hf = gen.getHeight(x, z, false) + (world == null ? -64 : world.getMinHeight()); - Location l = switch (getReferenceSpawner().getGroup()) { - case NORMAL -> new Location(c.getWorld(), x, hf + 1, z); - case CAVE -> findCaveSpawnLocation(gen, c, rng); - case UNDERWATER, BEACH -> new Location(c.getWorld(), x, rng.i(h + 1, hf), z); - }; - - if (l != null) { - if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { - if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { - if (spawn100(gen, l) != null) { - s++; - } - } - } else { - if (spawn100(gen, l) != null) { - s++; - } - } - } - } - } - - return s; - } - - public int spawn(Engine gen, IrisPosition c, RNG rng) { - int spawns = LootResolver.inclusive(rng, minSpawns, maxSpawns); - int s = 0; - - if (!BukkitWorldBinding.tryBind(gen.getWorld())) { - return 0; - } - - World world = BukkitWorldBinding.world(gen.getWorld()); - if (spawns > 0) { - - if (referenceMarker != null && referenceMarker.shouldExhaust()) { - if (J.isFolia()) { - J.a(() -> gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class)); - } else { - gen.getMantle().getMantle().remove(c.getX(), c.getY() - gen.getWorld().minHeight(), c.getZ(), MatterMarker.class); - } - } - - for (int id = 0; id < spawns; id++) { - Location l = BukkitPlatform.toLocation(c, world).add(0, 1, 0); - - if (referenceSpawner.getAllowedLightLevels().getMin() > 0 || referenceSpawner.getAllowedLightLevels().getMax() < 15) { - if (referenceSpawner.getAllowedLightLevels().contains(l.getBlock().getLightLevel())) { - if (spawn100(gen, l, true) != null) { - s++; - } - } - } else { - if (spawn100(gen, l, true) != null) { - s++; - } - } - } - } - - return s; - } - public IrisEntity getRealEntity(Engine g) { return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); } - - public Entity spawn(Engine g, Location at) { - if (getRealEntity(g) == null) { - return null; - } - - if (LootResolver.oneIn(rng.aquire(() -> new RNG(g.getSeedManager().getEntity())), getRarity())) { - return spawn100(g, at); - } - - return null; - } - - static Location findCaveSpawnLocation(Engine engine, Chunk chunk, RNG rng) { - if (J.isFolia()) { - return null; - } - KList markers = engine.getMantle().findMarkers(chunk.getX(), chunk.getZ(), MarkerMatter.CAVE_FLOOR); - return selectCaveSpawnLocation(markers, chunk.getWorld(), rng); - } - - static Location selectCaveSpawnLocation(KList markers, World world, RNG rng) { - return markers.convert((marker) -> BukkitPlatform.toLocation(marker, world).add(0, 1, 0)).getRandom(rng); - } - - private Entity spawn100(Engine g, Location at) { - return spawn100(g, at, false); - } - - private Entity spawn100(Engine g, Location at, boolean ignoreSurfaces) { - try { - IrisEntity irisEntity = getRealEntity(g); - if (irisEntity == null) { // No entity - IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); - return null; - } - - if (!ignoreSurfaces && !irisEntity.getSurface().matches(at.clone().subtract(0, 1, 0).getBlock())) { - return null; - } - - Vector3d boundingBox = BukkitPlatform.entityBoundingBox(irisEntity.getBukkitType()); - if (!ignoreSurfaces && boundingBox != null) { - boolean isClearForSpawn = isAreaClearForSpawn(at, boundingBox); - if (!isClearForSpawn) { - return null; - } - } - - Entity e = irisEntity.spawn(g, at.add(0.5, 0.5, 0.5), rng.aquire(() -> new RNG(g.getSeedManager().getEntity()))); - if (e != null) { - IrisLogging.debug("Spawned " + C.DARK_AQUA + "Entity<" + getEntity() + "> " + C.GREEN + e.getType() + C.LIGHT_PURPLE + " @ " + C.GRAY + e.getLocation().getX() + ", " + e.getLocation().getY() + ", " + e.getLocation().getZ()); - } - - return e; - } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.error(" Failed to retrieve real entity @ " + at + " (entity: " + getEntity() + ")"); - return null; - } - } - - private boolean isAreaClearForSpawn(Location center, Vector3d boundingBox) { - World world = center.getWorld(); - int startX = center.getBlockX() - (int) (boundingBox.x / 2); - int endX = center.getBlockX() + (int) (boundingBox.x / 2); - int startY = center.getBlockY(); - int endY = center.getBlockY() + (int) boundingBox.y; - int startZ = center.getBlockZ() - (int) (boundingBox.z / 2); - int endZ = center.getBlockZ() + (int) (boundingBox.z / 2); - - for (int x = startX; x <= endX; x++) { - for (int y = startY; y <= endY; y++) { - for (int z = startZ; z <= endZ; z++) { - if (world.getBlockAt(x, y, z).getType() != Material.AIR) { - return false; - } - } - } - } - return true; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java index 5924802b6..8a7677d15 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java @@ -19,9 +19,6 @@ package art.arcane.iris.engine.object.entity.spawn; import art.arcane.iris.engine.object.annotations.Desc; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.data.Waterlogged; @Desc("The type of surface entities should spawn on") public enum IrisSurface { @@ -40,29 +37,4 @@ public enum IrisSurface { @Desc("Within lava") LAVA; - - /** - * Check if this Iris surface matches the blockstate provided - * - * @param state The blockstate - * @return True if it matches - */ - public boolean matches(Block state) { - Material type = state.getType(); - if (type.isSolid()) { - return this == LAND || this == OVERWORLD || (this == ANIMAL - && (type == Material.GRASS_BLOCK || type == Material.DIRT - || type == Material.DIRT_PATH || type == Material.COARSE_DIRT - || type == Material.ROOTED_DIRT || type == Material.PODZOL - || type == Material.MYCELIUM || type == Material.SNOW_BLOCK)); - } - if (type == Material.LAVA) return this == LAVA; - if (type == Material.WATER || type == Material.SEAGRASS - || type == Material.TALL_SEAGRASS || type == Material.KELP_PLANT - || type == Material.KELP || - (state instanceof Waterlogged && ((Waterlogged) state).isWaterlogged())) - return this == WATER || this == OVERWORLD; - - return false; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java index bd104ca0a..b3253cc09 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java @@ -31,13 +31,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.ItemMeta; -import java.util.Locale; @Snippet("enchantment") @@ -65,40 +59,6 @@ public class IrisEnchantment { @Desc("The chance that this enchantment is applied (0 to 1)") private double chance = 1; - public void apply(RNG rng, ItemMeta meta) { - try { - Enchantment enchant = resolve(); - if (enchant == null) { - IrisLogging.warn("Unknown Enchantment: " + getEnchantment()); - return; - } - if (rng.nextDouble() < chance) { - if (meta instanceof EnchantmentStorageMeta) { - ((EnchantmentStorageMeta) meta).addStoredEnchant(enchant, getLevel(rng), true); - return; - } - meta.addEnchant(enchant, getLevel(rng), true); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - - } - } - - /** - * Resolves the authored key against the live enchantment registry. Accepts a bare path - * ({@code sharpness}) or a full namespaced key ({@code mymod:vorpal}) - parity with the modded resolver. - */ - private Enchantment resolve() { - String raw = getEnchantment(); - if (raw == null || raw.isBlank()) { - return null; - } - String value = raw.trim().toLowerCase(Locale.ROOT).replace(' ', '_'); - NamespacedKey key = value.indexOf(':') >= 0 ? NamespacedKey.fromString(value) : NamespacedKey.minecraft(value); - return key == null ? null : Registry.ENCHANTMENT.get(key); - } - public int getLevel(RNG rng) { return LootResolver.inclusive(rng, getMinLevel(), getMaxLevel()); } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java index 30251684e..57f699664 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java @@ -19,13 +19,6 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.platform.bukkit.BukkitBlockResolution; - -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.core.link.Identifier; -import art.arcane.iris.core.service.ExternalDataSVC; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MaxNumber; @@ -33,32 +26,14 @@ import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.RegistryListItemType; import art.arcane.iris.engine.object.annotations.Required; import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; -import art.arcane.iris.util.common.format.C; -import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.Accessors; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.components.CustomModelDataComponent; -import org.bukkit.material.Colorable; - -import java.awt.Color; -import java.util.List; -import java.util.Optional; @Snippet("loot") @Accessors(chain = true) @@ -71,7 +46,6 @@ import java.util.Optional; public class IrisLoot { public static final int MAX_AMOUNT = 64; - private final transient AtomicCache dyeColorResolved = new AtomicCache<>(); @Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.") private InventorySlotType slotTypes = InventorySlotType.STORAGE; @MinNumber(1) @@ -123,175 +97,17 @@ public class IrisLoot { @Desc("Defines a custom NBT Tag for the item.") private KMap customNbt; - public Material getType() { - return BukkitBlockResolution.getMaterial(type); - } - /** - * The authored item key, exactly as written in the pack. Platform-neutral: {@link #getType()} resolves it against - * Bukkit, mod loaders resolve it against their own item registry. + * The authored item key, exactly as written in the pack. Each platform resolves it against its own item registry. */ public String getTypeKey() { return type; } /** - * The authored dye colour name, or null when unset. Platform-neutral counterpart to {@link #getDyeColor()}. + * The authored dye colour name, or null when unset. */ public String getDyeColorKey() { return dyeColor; } - - public DyeColor getDyeColor() { - if (dyeColor == null) { - return null; - } - return dyeColorResolved.aquire(() -> { - try { - return DyeColor.valueOf(dyeColor); - } catch (IllegalArgumentException e) { - return null; - } - }); - } - - private KList getResolvedItemFlags() { - KList resolved = new KList<>(); - for (String flag : itemFlags) { - if (flag == null) { - continue; - } - try { - resolved.add(ItemFlag.valueOf(flag)); - } catch (IllegalArgumentException ignored) { - } - } - return resolved; - } - - public ItemStack get(boolean debug, RNG rng) { - try { - ItemStack is = getItemStack(rng); - if (is == null) - return new ItemStack(Material.AIR); - is.setItemMeta(applyProperties(is, rng, debug, null)); - return BukkitPlatform.applyCustomNbt(is, customNbt); - } catch (Throwable e) { - IrisLogging.reportError(e); - return new ItemStack(Material.AIR); - } - } - - public ItemStack get(boolean debug, IrisLootTable table, RNG rng, long lootSeed, int entryIndex, int x, int y, int z) { - long combinedRarity = LootResolver.combinedRarity(rarity, table.getRarity()); - if (!art.arcane.iris.engine.loot.LootTables.spatialOneIn(lootSeed, table, entryIndex, x, y, z, combinedRarity)) { - return null; - } - - try { - ItemStack is = getItemStack(rng); - if (is == null) - return null; - is.setItemMeta(applyProperties(is, rng, debug, table)); - return BukkitPlatform.applyCustomNbt(is, customNbt); - } catch (Throwable e) { - IrisLogging.reportError(e); - } - - return null; - } - - // TODO Better Third Party Item Acquisition - private ItemStack getItemStack(RNG rng) { - if (!type.startsWith("minecraft:") && type.contains(":")) { - Optional opt = IrisServices.get(ExternalDataSVC.class).getItemStack(Identifier.fromString(type), customNbt); - if (opt.isEmpty()) { - IrisLogging.warn("Unknown Material: " + type); - return new ItemStack(Material.AIR); - } - ItemStack is = opt.get(); - is.setAmount(Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount()))); - return is; - } - return new ItemStack(getType(), Math.max(1, LootResolver.inclusive(rng, getMinAmount(), getMaxAmount()))); - } - - private ItemMeta applyProperties(ItemStack is, RNG rng, boolean debug, IrisLootTable table) { - ItemMeta m = is.getItemMeta(); - if (m == null) { - return null; - } - - for (IrisEnchantment i : getEnchantments()) { - i.apply(rng, m); - } - - for (IrisAttributeModifier i : getAttributes()) { - i.apply(rng, m); - } - - m.setUnbreakable(isUnbreakable()); - for (ItemFlag i : getResolvedItemFlags()) { - m.addItemFlags(i); - } - - if (getCustomModel() != null) { - CustomModelDataComponent customModelData = m.getCustomModelDataComponent(); - customModelData.setFloats(List.of(getCustomModel().floatValue())); - m.setCustomModelDataComponent(customModelData); - } - - if (is.getType().getMaxDurability() > 0 && m instanceof Damageable d) { - int max = is.getType().getMaxDurability(); - d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); - } - - if (getLeatherColor() != null && m instanceof LeatherArmorMeta leather) { - Color c = Color.decode(getLeatherColor()); - leather.setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); - } - - if (getDyeColor() != null && m instanceof Colorable colorable) { - colorable.setColor(getDyeColor()); - } - - if (displayName != null) { - m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); - } - - KList lore = new KList<>(); - - getLore().forEach((i) -> - { - String mf = C.translateAlternateColorCodes('&', i); - - if (mf.length() > 24) { - for (String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { - lore.add(g.trim()); - } - } else { - lore.add(mf); - } - }); - - if (debug) { - if (table == null) { - if (lore.isNotEmpty()) { - lore.add(C.GRAY + "--------------------"); - } - lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")"); - } else { - if (lore.isNotEmpty()) { - lore.add(C.GRAY + "--------------------"); - } - - lore.add(C.GRAY + "From: " + table.getName() + " (" + Form.pc(1D / table.getRarity(), 5) + ")"); - lore.add(C.GRAY + "1 in " + (table.getRarity() * getRarity()) + " Chance (" + Form.pc(1D / (table.getRarity() * getRarity()), 5) + ")"); - } - } - - m.setLore(lore); - - return m; - } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java index 9b85aac40..d92ff93ee 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java @@ -19,22 +19,17 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.framework.LootResolver; 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.volmlib.util.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.inventory.ItemStack; @Accessors(chain = true) @NoArgsConstructor @@ -74,35 +69,6 @@ public class IrisLootTable extends IrisRegistrant { @ArrayType(min = 1, type = IrisLoot.class) private KList loot = new KList<>(); - public KList getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) { - KList lootf = new KList<>(); - if (loot.isEmpty() || maxTries <= 0) { - return lootf; - } - - RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); - int m = 0; - int c = 0; - int mx = Math.max(0, LootResolver.inclusive(rng, getMinPicked(), getMaxPicked())); - - while (m < mx && c++ < getMaxTries()) { - int num = rng.nextInt(loot.size()); - - IrisLoot l = loot.get(num); - - if (l != null && l.getSlotTypes() == slot) { - ItemStack item = l.get(debug, this, rng, lootSeed, num, x, y, z); - - if (item != null && item.getType() != Material.AIR) { - lootf.add(item); - m++; - } - } - } - - return lootf; - } - @Override public String getFolderName() { return "loot"; diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java index e61521405..d4a207804 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java @@ -1,20 +1,9 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; import lombok.Data; import lombok.EqualsAndHashCode; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.World; -import org.bukkit.inventory.ItemStack; -import org.bukkit.loot.LootContext; -import org.bukkit.loot.LootTable; import java.io.File; @@ -25,22 +14,13 @@ public class IrisVanillaLootTable extends IrisLootTable { * The vanilla loot table key ("minecraft:chests/simple_dungeon"), not the LootTable itself. A * raw org.bukkit.loot.LootTable field - and the constructor lombok would generate for it - makes * every reflective walk over the IrisLootTable hierarchy (Gson, schema generation, the purity - * gate) resolve a Bukkit class. The table is resolved lazily at pull time, which only ever - * happens on Bukkit. The key text is identical to what {@code LootTable.getKey().toString()} - * produced before, so {@code LootResolver.tableIdentity} (which falls back to + * gate) resolve a Bukkit class. The host resolves the table when it pulls loot from it. The key text is + * identical to what {@code LootTable.getKey().toString()} produced before, so + * {@code LootTables.identity} (which falls back to * {@link #getName()}) yields the same loot seed. */ private final String lootTableKey; - /** - * The resolved table, looked up once. Every chest pull resolved it again - a NamespacedKey parse plus a registry - * lookup per container, and a dungeon room is a lot of containers. - *

- * Transient for the same reason the field above is a String: it keeps the Bukkit type argument out of the Gson - * field walk and out of the pack purity gate, both of which resolve generic field types for the fields they visit. - */ - private final transient AtomicCache resolvedTable = new AtomicCache<>(); - @Override public String getName() { return "Vanilla " + lootTableKey; @@ -71,24 +51,6 @@ public class IrisVanillaLootTable extends IrisLootTable { return new KList<>(); } - @Override - public KList getLoot(boolean debug, long lootSeed, InventorySlotType slot, World world, int x, int y, int z) { - LootTable table = resolveTable(); - if (table == null) { - IrisLogging.warn("Unknown vanilla loot table " + lootTableKey); - return new KList<>(); - } - RNG rng = art.arcane.iris.engine.loot.LootTables.rng(lootSeed, this, x, y, z); - return new KList<>(table.populateLoot(rng, new LootContext.Builder(new Location(world, x, y, z)).build())); - } - - private LootTable resolveTable() { - return resolvedTable.aquire(() -> { - NamespacedKey key = NamespacedKey.fromString(lootTableKey); - return key == null ? null : Bukkit.getLootTable(key); - }); - } - @Override public String getFolderName() { throw new UnsupportedOperationException("VanillaLootTables do not have a folder name"); diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java index f7e6cf5af..5062b80b5 100644 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java @@ -24,9 +24,8 @@ 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.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformWorld; -import art.arcane.iris.util.common.scheduling.J; +import art.arcane.iris.util.common.scheduling.ConsoleCommands; import art.arcane.volmlib.util.collection.KList; import lombok.Data; import lombok.NoArgsConstructor; @@ -68,19 +67,6 @@ public class IrisCommand { return; } - for (String command : commands) { - command = (command.startsWith("/") ? command.replaceFirst("/", "") : command) - .replaceAll("\\Q{x}\\E", String.valueOf(x)) - .replaceAll("\\Q{y}\\E", String.valueOf(y)) - .replaceAll("\\Q{z}\\E", String.valueOf(z)); - final String finalCommand = command; - int safeDelay = (int) Math.max(0, Math.min(Integer.MAX_VALUE, delay)); - if (repeat) { - int safeRepeatDelay = (int) Math.max(1, Math.min(Integer.MAX_VALUE, repeatDelay)); - J.s(() -> J.sr(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeRepeatDelay), safeDelay); - } else { - J.s(() -> IrisPlatforms.get().dispatchConsoleCommand(finalCommand), safeDelay); - } - } + ConsoleCommands.run(commands, delay, repeat, repeatDelay, x, y, z); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java new file mode 100644 index 000000000..a5277349e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -0,0 +1,128 @@ +/* + * 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.spawn; + +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.object.entity.IrisAttributeModifier; +import art.arcane.iris.engine.object.entity.IrisEffect; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.marker.IrisCommand; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.entity.EntitySpec; +import com.volmit.item.ItemAttribute; +import com.volmit.item.ItemDrop; + +import java.util.ArrayList; +import java.util.List; + +/** + * Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris + * always made them: the passengers, the attribute modifiers, the leash holder and then the six pieces of equipment. + */ +final class EntityResolution { + private static final long PASSENGER_STREAM_BASE = 234858L; + private static final long LEASH_HOLDER_STREAM = 234548L; + + private final LootItems items; + private final PlatformWorld world; + + /** @param world the world the entity appears in, whose time and weather decide which of its commands run */ + EntityResolution(LootItems items, PlatformWorld world) { + this.items = items; + this.world = world; + } + + EntitySpec resolve(IrisEntity entity, RNG rng) { + List passengers = new ArrayList<>(); + long passengerIndex = 0; + for (IrisEntity passenger : entity.getPassengers()) { + passengers.add(resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++))); + } + + List attributes = drawAttributes(entity, rng); + List lootTables = List.copyOf(entity.getLoot().getTables()); + long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong(); + EntitySpec leashHolder = entity.getLeashHolder() == null ? null : resolve(entity.getLeashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); + EntitySpec.Equipment equipment = new EntitySpec.Equipment( + equip(entity.getHelmet(), rng), equip(entity.getChestplate(), rng), equip(entity.getLeggings(), rng), + equip(entity.getBoots(), rng), equip(entity.getMainHand(), rng), equip(entity.getOffHand(), rng)); + + return new EntitySpec( + entity.getType() == null ? "" : entity.getType(), + entity.getSpecialType() == null ? "" : entity.getSpecialType(), + entity.getReason(), + entity.getCustomName() == null ? "" : entity.getCustomName(), + flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, leashHolder, + spawnEffectOf(entity), entity.isSpawnEffectRiseOutOfGround(), entity.getPandaMainGene(), + entity.getPandaHiddenGene(), entity.isApplySettingsToCustomMobAnyways(), commandsOf(entity)); + } + + private static EntitySpec.Flags flagsOf(IrisEntity entity) { + return new EntitySpec.Flags(entity.isCustomNameVisible(), entity.isAware(), entity.isAi(), entity.isGlowing(), + entity.isGravity(), entity.isInvulnerable(), entity.isSilent(), entity.isPickupItems(), entity.isRemovable(), + entity.isKeepEntity(), entity.isBaby()); + } + + private static List drawAttributes(IrisEntity entity, RNG rng) { + List attributes = new ArrayList<>(); + for (IrisAttributeModifier modifier : entity.getAttributes()) { + if (rng.nextDouble() >= modifier.getChance()) { + continue; + } + String attribute = modifier.getAttribute(); + if (attribute == null || attribute.isBlank()) { + continue; + } + attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng))); + } + return attributes; + } + + private ItemDrop equip(IrisLoot piece, RNG rng) { + if (piece == null || !LootResolver.oneIn(rng, piece.getRarity())) { + return null; + } + return items.give(piece, rng); + } + + /** The entity's spawn effect when it shows this time: an effect only shows now and then, as its interval and chance say. */ + private static EntitySpec.SpawnEffect spawnEffectOf(IrisEntity entity) { + IrisEffect effect = entity.getSpawnEffect(); + if (effect == null || !effect.shouldApplyNow()) { + return null; + } + return new EntitySpec.SpawnEffect(effect.getSoundKey(), effect.getSoundDistance(), effect.getMinPitch(), + effect.getMaxPitch(), effect.getVolume(), effect.getParticleEffectKey(), effect.getParticleOffset(), + effect.getParticleCount(), effect.getParticleAltX(), effect.getParticleAltY(), effect.getParticleAltZ(), + effect.isRandomAltX(), effect.isRandomAltY(), effect.isRandomAltZ(), effect.getExtra()); + } + + private List commandsOf(IrisEntity entity) { + List commands = new ArrayList<>(); + for (IrisCommand command : entity.getRawCommands()) { + if (command.isValid(world)) { + commands.add(new EntitySpec.Command(command.getCommands(), command.getDelay(), command.isRepeat(), command.getRepeatDelay())); + } + } + return commands; + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java new file mode 100644 index 000000000..5c9bec4f1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -0,0 +1,269 @@ +/* + * 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.spawn; + +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.entity.IrisEntitySpawn; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.entity.spawn.IrisSurface; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.engine.object.value.IrisRange; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.matter.slices.MarkerMatter; +import com.volmit.entity.EntitySpec; +import com.volmit.service.EntitySpawns; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * How {@code iris:spawn} spawns entities: the spawners of the dimension, region and surface biome that may fire in a + * chunk, or the spawners of a marker, each with the entities it spawns and the places it picks for them. What the + * platform decides (light, the surface, free space, the entity itself) is the host's, the plan only names it. + */ +public final class EntitySpawning implements EntitySpawns { + private static final int BLOCKS_TO_CHUNK_CENTRE = 8; + private static final int CHUNK_SIZE = 16; + private static final String CAVE_FLOOR_MARKER = "cave_floor"; + private static final String CAVE_CEILING_MARKER = "cave_ceiling"; + private static final int AIR_ABOVE_MARKER = 1; + + @Override + public Optional plan(PackWorld world, Site site) { + Engine engine = engine(world); + return switch (site) { + case Chunk chunk -> planChunk(world, engine, chunk); + case Marker marker -> planMarker(world, engine, marker); + }; + } + + @Override + public void spawned(PackWorld world, Plan plan, int count) { + if (count <= 0) { + return; + } + IrisSpawner spawner = engine(world).getData().getSpawnerLoader().load(plan.spawner()); + if (spawner != null) { + spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ()); + } + } + + @Override + public Optional entity(PackWorld world, String key) { + IrisEntity entity = engine(world).getData().getEntityLoader().load(key); + if (entity == null) { + return Optional.empty(); + } + return Optional.of(resolution(world, engine(world)).resolve(entity, entityRandom(world).rng())); + } + + @Override + public Optional marker(PackWorld world, String tag) { + if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) { + return Optional.empty(); + } + Engine engine = engine(world); + IrisMarker marker = engine.getData().getMarkerLoader().load(tag); + if (marker == null) { + return Optional.empty(); + } + + List spawners = new ArrayList<>(); + for (String key : marker.getSpawners()) { + if (engine.getData().getSpawnerLoader().load(key) == null) { + IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag); + continue; + } + spawners.add(key); + } + return Optional.of(new MarkerRule(spawners, marker.isEmptyAbove(), marker.isRemoveOnChange())); + } + + private Optional planChunk(PackWorld world, Engine engine, Chunk chunk) { + Predicate canSpawn = spawner -> spawner.canSpawn(engine, chunk.chunkX(), chunk.chunkZ()); + int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); + int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); + IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); + IrisRegion region = engine.getRegion(blockX, blockZ); + IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ); + + List candidates = Stream.concat( + shuffled(engine, engine.getDimension().getEntitySpawners()).stream() + .filter(canSpawn).filter(spawner -> spawner.isValid(centreBiome)), + Stream.concat( + shuffled(engine, region.getEntitySpawners()).stream().filter(canSpawn), + shuffled(engine, biome.getEntitySpawners()).stream().filter(canSpawn))) + .filter(spawner -> chunk.livingEntities() < spawner.getMaxEntitiesPerChunk()) + .toList(); + + List spawns = candidates.stream().flatMap(spawner -> spawnsOf(spawner, chunk.initial())).collect(Collectors.toList()); + Candidate chosen = IRare.expandWeighted(spawns).getRandom(); + if (chosen == null) { + return Optional.empty(); + } + return planChunkSpawn(world, engine, chunk, chosen); + } + + private Optional planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) { + IrisSpawner spawner = chosen.spawner(); + IrisEntitySpawn spawn = chosen.spawn(); + int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns()); + List attempts = new ArrayList<>(); + for (int i = 0; i < count; i++) { + int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); + int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); + BlockPosition at = spawnPosition(engine, spawner, chunk.chunkX(), chunk.chunkZ(), x, z); + if (at != null) { + addAttempt(attempts, world, engine, chosen, at, true); + } + } + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); + } + + /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ + private static BlockPosition spawnPosition(Engine engine, IrisSpawner spawner, int chunkX, int chunkZ, int x, int z) { + int height = engine.getHeight(x, z, true); + int heightWithFluid = engine.getHeight(x, z, false); + return switch (spawner.getGroup()) { + case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); + case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ); + case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); + }; + } + + static BlockPosition caveSpawnPosition(Engine engine, int chunkX, int chunkZ) { + if (J.isFolia()) { + return null; + } + KList floors = engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR); + IrisPosition floor = floors.getRandom(RNG.r); + return floor == null ? null : new BlockPosition(floor.getX(), floor.getY() - engine.getMinHeight() + AIR_ABOVE_MARKER, floor.getZ()); + } + + private Optional planMarker(PackWorld world, Engine engine, Marker marker) { + IrisSpawner spawner = engine.getData().getSpawnerLoader().load(marker.spawner()); + IrisMarker irisMarker = engine.getData().getMarkerLoader().load(marker.marker()); + if (spawner == null) { + return Optional.empty(); + } + + KList candidates = marker.initial() ? spawner.getInitialSpawns() : spawner.getSpawns(); + if (candidates.isEmpty()) { + return Optional.empty(); + } + IrisEntitySpawn spawn = IRare.expandWeighted(candidates).getRandom(); + + BlockPosition position = marker.position(); + int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); + int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); + if (!spawner.canSpawn(engine, chunkX, chunkZ)) { + return Optional.empty(); + } + + int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns()); + if (count <= 0) { + return Optional.empty(); + } + boolean exhaustsMarker = irisMarker != null && irisMarker.shouldExhaust(); + List attempts = new ArrayList<>(); + BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); + for (int i = 0; i < count; i++) { + addAttempt(attempts, world, engine, new Candidate(spawner, spawn), above, false); + } + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunkX, chunkZ, exhaustsMarker, attempts)); + } + + private void addAttempt(List attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) { + IrisEntity entity = candidate.spawn().getRealEntity(engine); + if (entity == null) { + IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); + return; + } + + IrisRange light = candidate.spawner().getAllowedLightLevels(); + EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng()); + attempts.add(new Attempt(at, spec, surfaceOf(entity.getSurface()), + (int) Math.ceil(light.getMin()), (int) Math.floor(light.getMax()), checkSurface)); + } + + private static EntityResolution resolution(PackWorld world, Engine engine) { + LootItems items = new LootItems(world.resources().items(), engine.isStudio()); + return new EntityResolution(items, engine.getWorld().platformWorld()); + } + + private static EntityRandom entityRandom(PackWorld world) { + return world.state(EntityRandom.class, EntityRandom::new); + } + + private static Surface surfaceOf(IrisSurface surface) { + return Surface.valueOf(surface.name()); + } + + private static KList shuffled(Engine engine, KList keys) { + return engine.getData().getSpawnerLoader().loadAll(keys).shuffleCopy(RNG.r); + } + + private static Stream spawnsOf(IrisSpawner spawner, boolean initial) { + KList spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); + return spawns.stream().map(spawn -> new Candidate(spawner, spawn)); + } + + /** A spawn of a spawner, which picks as often as the spawn's rarity says. */ + private record Candidate(IrisSpawner spawner, IrisEntitySpawn spawn) implements IRare { + @Override + public int getRarity() { + return spawn.getRarity(); + } + } + + private static Engine engine(PackWorld world) { + return IrisPackWorld.of(world).engine(); + } + + /** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */ + private static final class EntityRandom { + private final RNG rng; + + private EntityRandom(PackWorld world) { + this.rng = new RNG(IrisPackWorld.of(world).engine().getSeedManager().getEntity()); + } + + private RNG rng() { + return rng; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java new file mode 100644 index 000000000..d0663b44f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -0,0 +1,48 @@ +/* + * 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.spawn; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.service.EntitySpawns; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:spawn}: the spawners, entities and markers of the pack, and the entities that appear in the world + * over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for + * something to spawn in a chunk or at a marker. + */ +public final class SpawnModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:spawn", "Spawn", VERSION); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerService(EntitySpawns.class, new EntitySpawning()); + } +} From feaa1e88c42f71bff69456c68c01021ec366279d Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:19:44 +0200 Subject: [PATCH 038/139] Floating settings as module-owned IrisApi types: FloatingChildBiome and its enums; ResolvedFloatingChild holds the noise and object resolution --- .../floating/FloatingBottomPaletteMode.java | 4 +- .../floating/FloatingChildBiome.java} | 412 +++++++++--------- .../floating/OverrideMode.java | 4 +- .../floating/TopShapeMode.java | 4 +- .../components/FloatingObjectPlacing.java | 49 ++- .../mantle/components/IslandObjectPlacer.java | 12 +- .../iris/engine/modifier/FloatingIslands.java | 52 +-- .../iris/engine/modifier/FloatingModule.java | 7 + .../terrain/floating/FloatingChildren.java | 56 +++ .../FloatingIslandBoundarySampler.java | 24 +- .../floating/FloatingIslandSample.java | 85 ++-- .../floating/ResolvedFloatingChild.java | 226 ++++++++++ .../engine/object/world/biome/IrisBiome.java | 6 +- .../object/world/dimension/IrisDimension.java | 10 +- 14 files changed, 635 insertions(+), 316 deletions(-) rename src/main/java/art/arcane/iris/{engine/object/terrain => builtin}/floating/FloatingBottomPaletteMode.java (91%) rename src/main/java/art/arcane/iris/{engine/object/terrain/floating/IrisFloatingChildBiomes.java => builtin/floating/FloatingChildBiome.java} (55%) rename src/main/java/art/arcane/iris/{engine/object/terrain => builtin}/floating/OverrideMode.java (92%) rename src/main/java/art/arcane/iris/{engine/object/terrain => builtin}/floating/TopShapeMode.java (92%) create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingBottomPaletteMode.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java rename to src/main/java/art/arcane/iris/builtin/floating/FloatingBottomPaletteMode.java index 2a3407e14..a8de3246d 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingBottomPaletteMode.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingBottomPaletteMode.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.terrain.floating; +package art.arcane.iris.builtin.floating; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls how floating-child island underside blocks choose their palette.") public enum FloatingBottomPaletteMode { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java similarity index 55% rename from src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java rename to src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java index 3d28b0afb..608be30c7 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/IrisFloatingChildBiomes.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,148 +16,44 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.terrain.floating; +package art.arcane.iris.builtin.floating; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -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.RegistryListBlockType; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * A floating island above a biome's terrain, an entry of the biome's {@code floatingChildBiomes}: where its footprint + * is, how high it floats, how its top, underside and walls are shaped, and which objects, decorators and water it + * gets. Noise and options are IrisApi types; the object placements and palette layers the island hosts are + * Iris's own classes, which the host describes itself, so this class leaves the pack module jar only when those + * become settings of modules. + */ @Snippet("floating-child-biome") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@EqualsAndHashCode @Desc("Declares a floating biome layer above this biome's terrain. A 2D footprint noise decides which columns are part of the island (threshold + style control blankets, swirls, scattered blobs). The top profile is driven by the target biome's own terrain generators (so a mountains biome produces real peaks, desert produces real dunes). The bottom tail hanging below is a separately configurable noise (pick VASCULAR for drippy roots, FRACTAL_RM_SIMPLEX for crystalline spikes, PERLIN for smooth rounded bowls).") -@Data -public class IrisFloatingChildBiomes implements IRare { - private final transient AtomicCache resolvedBiome = new AtomicCache<>(); - private final transient AtomicCache footprintCache = new AtomicCache<>(); - private final transient AtomicCache edgeTaperProfileCache = new AtomicCache<>(); - private final transient AtomicCache pickerCache = new AtomicCache<>(); - private final transient AtomicCache altitudeCache = new AtomicCache<>(); - private final transient AtomicCache topShapeCache = new AtomicCache<>(); - private final transient AtomicCache bottomCache = new AtomicCache<>(); - private final transient AtomicCache wallWarpCache = new AtomicCache<>(); - private final transient AtomicCache carveCache = new AtomicCache<>(); - private final transient AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); - private final transient AtomicCache shrinkScaleCache = new AtomicCache<>(); +public final class FloatingChildBiome { + public static final int DEFAULT_EDGE_TAPER_WIDTH = 10; + public static final double DEFAULT_EDGE_TAPER_EXPONENT = 1.0D; + private static final NoiseStyle DEFAULT_BOTTOM_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_TOP_SHAPE_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_ALTITUDE_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_PICKER_STYLE = NoiseStyle.of("SIMPLEX"); + private static final NoiseStyle DEFAULT_EDGE_TAPER_VARIATION_STYLE = NoiseStyle.of("SIMPLEX").withZoom(0.18D); + private static final NoiseStyle DEFAULT_FOOTPRINT_STYLE = NoiseStyle.of("SIMPLEX"); - public CNG getFootprintCng(long baseSeed, IrisData data) { - return footprintCache.aquire(() -> getFootprintStyle().create(new RNG(baseSeed ^ 0xF007B17DL), data)); - } - - public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) { - return edgeTaperProfileCache.aquire(() -> { - int width = FloatingIslandEdgeProfile.clampWidth(getEdgeTaperWidth()); - double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude( - getEdgeTaperVariationAmplitude(), width); - IrisGeneratorStyle style = getEdgeTaperVariationStyle(); - CNG variation = amplitude > 0.0D && style != null - ? style.create(new RNG(baseSeed ^ 0xED6E7A9E5L), data) - : null; - return new FloatingIslandEdgeProfile(width, getEdgeTaperExponent(), amplitude, variation); - }); - } - - public CNG getPickerCng(long baseSeed, IrisData data) { - return pickerCache.aquire(() -> getPickerStyle().create(new RNG(baseSeed ^ 0x91C4E72DL), data)); - } - - public CNG getAltitudeCng(long baseSeed, IrisData data) { - return altitudeCache.aquire(() -> getAltitudeStyle().create(new RNG(baseSeed ^ 0xA17DEBBL), data)); - } - - public CNG getTopShapeCng(long baseSeed, IrisData data) { - return topShapeCache.aquire(() -> getTopShapeStyle().create(new RNG(baseSeed ^ 0x70970601DEFL), data)); - } - - public CNG getBottomCng(long baseSeed, IrisData data) { - return bottomCache.aquire(() -> getBottomStyle().create(new RNG(baseSeed ^ 0xB0770075CAFEL), data)); - } - - public CNG getWallWarpCng(long baseSeed, IrisData data) { - IrisGeneratorStyle style = getWallWarpStyle(); - if (style == null) { - return null; - } - return wallWarpCache.aquire(() -> style.create(new RNG(baseSeed ^ 0xA117BA17E0FL), data)); - } - - public CNG getCarveCng(long baseSeed, IrisData data) { - IrisGeneratorStyle style = getCarveStyle(); - if (style == null) { - return null; - } - return carveCache.aquire(() -> style.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); - } - - public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { - if (!hasCarvingReference()) { - return null; - } - - return carvingProfileSamplerCache.aquire(() -> { - IrisBiome resolved = resolveCarvingBiome(carving, engine, data); - if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().enabled()) { - return null; - } - - return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); - }); - } - - public boolean hasCarvingReference() { - return carving != null && !carving.isBlank(); - } - - static IrisBiome resolveCarvingBiome(String carving, Engine engine, IrisData data) { - if (carving == null || carving.isBlank() || engine == null || data == null) { - return null; - } - - IrisDimension dimension = engine.getDimension(); - if (dimension != null && dimension.getCarvingEntryIndex() != null) { - IrisDimensionCarvingEntry entry = dimension.getCarvingEntryIndex().get(carving); - if (entry != null) { - return IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry); - } - } - - if (data.getBiomeLoader() == null) { - return null; - } - - return data.getBiomeLoader().load(carving); - } - - @RegistryListResource(IrisBiome.class) + @Ref(Reference.PACK_BIOME) @Desc("The target biome whose visual design (layers, palette, decorators, surface objects, derivative, and — when topShapeMode=BIOME — generator profile) drives the floating island. Leave empty to reuse the parent biome (self).") private String biome = ""; @@ -167,7 +63,7 @@ public class IrisFloatingChildBiomes implements IRare { private int rarity = 1; @Desc("2D noise that decides which columns are part of this island. Set feature size via the style's own zoom field (e.g. {\"style\":\"CELLULAR\",\"zoom\":0.3} for ~30-block shards, {\"style\":\"SIMPLEX\",\"zoom\":1.0} for ~100-block blobs). Pick SIMPLEX for smooth blobs, CELLULAR for angular shards, VASCULAR for vein/branch strips, FRACTAL_FBM_SIMPLEX for large irregular blanket regions. Fracture (domain warp) this to get swirly silhouettes.") - private IrisGeneratorStyle footprintStyle = NoiseStyle.SIMPLEX.style(); + private NoiseStyle footprintStyle = DEFAULT_FOOTPRINT_STYLE; @MinNumber(0) @MaxNumber(1) @@ -177,15 +73,15 @@ public class IrisFloatingChildBiomes implements IRare { @MinNumber(2) @MaxNumber(32) @Desc("Width in blocks of the rounded transition from the floating island contour to its full thickness. Smaller values make a tighter edge; larger values make a broader rounded underside.") - private int edgeTaperWidth = FloatingIslandEdgeProfile.DEFAULT_WIDTH; + private int edgeTaperWidth = DEFAULT_EDGE_TAPER_WIDTH; @MinNumber(0.25) @MaxNumber(4) @Desc("Shape exponent for the rounded edge. Values below 1 fill into a softer, fuller curve; values above 1 keep the rim thinner before rising into the island interior.") - private double edgeTaperExponent = FloatingIslandEdgeProfile.DEFAULT_EXPONENT; + private double edgeTaperExponent = DEFAULT_EDGE_TAPER_EXPONENT; @Desc("Broad 2D noise that organically varies the rounded edge without changing the island footprint. Low-frequency SIMPLEX or PERLIN styles give coherent natural contours; high-frequency or cellular styles can look speckled.") - private IrisGeneratorStyle edgeTaperVariationStyle = NoiseStyle.SIMPLEX.style().zoomed(0.18D); + private NoiseStyle edgeTaperVariationStyle = DEFAULT_EDGE_TAPER_VARIATION_STYLE; @MinNumber(0) @MaxNumber(8) @@ -193,10 +89,10 @@ public class IrisFloatingChildBiomes implements IRare { private double edgeTaperVariationAmplitude = 0.0D; @Desc("Picker noise used when multiple floating child entries exist. Samples once per column to deterministically choose which entry's footprint is tested there. Use a large style zoom (e.g. zoom: 4 for ~400-block regions) so each entry owns broad coherent areas.") - private IrisGeneratorStyle pickerStyle = NoiseStyle.SIMPLEX.style(); + private NoiseStyle pickerStyle = DEFAULT_PICKER_STYLE; @Desc("Altitude noise — varies the base platform Y across one island so it isn't a flat plane. Use a large style zoom (e.g. zoom: 2 for ~200-block altitude patches) so an island sits at roughly one altitude.") - private IrisGeneratorStyle altitudeStyle = NoiseStyle.SIMPLEX.style(); + private NoiseStyle altitudeStyle = DEFAULT_ALTITUDE_STYLE; @MinNumber(0) @MaxNumber(2032) @@ -223,7 +119,7 @@ public class IrisFloatingChildBiomes implements IRare { private int maxTopHeight = 40; @Desc("Used only when topShapeMode=NOISE. 2D noise driving the top heightmap. Set feature scale via the style's zoom field (small zoom = rugged peaks, large zoom = broad rolling shapes).") - private IrisGeneratorStyle topShapeStyle = NoiseStyle.SIMPLEX.style(); + private NoiseStyle topShapeStyle = DEFAULT_TOP_SHAPE_STYLE; @MinNumber(0) @MaxNumber(1) @@ -231,7 +127,7 @@ public class IrisFloatingChildBiomes implements IRare { private double topShapeAmp = 1.0; @Desc("2D noise driving the bottom tail hanging below the island base. VASCULAR = drippy organic roots. FRACTAL_RM_SIMPLEX = crystalline spikes. CELLULAR = jagged chunks. PERLIN = smooth rounded bowl. SIMPLEX = gentle lobes. Set feature scale via the style's zoom field.") - private IrisGeneratorStyle bottomStyle = NoiseStyle.SIMPLEX.style(); + private NoiseStyle bottomStyle = DEFAULT_BOTTOM_STYLE; @MinNumber(0) @MaxNumber(512) @@ -251,9 +147,9 @@ public class IrisFloatingChildBiomes implements IRare { @Desc("Controls the material palette near the island underside. DEPTH keeps the old top-down depth behavior. MIRROR_TOP uses the target biome's shallow/top palette from the underside upward. CUSTOM uses bottomPalette near the underside while keeping the target biome palette near the top.") private FloatingBottomPaletteMode bottomPaletteMode = FloatingBottomPaletteMode.DEPTH; - @ArrayType(min = 1, type = IrisBiomePaletteLayer.class) + @MinItems(1) @Desc("Custom palette layers used near the underside when bottomPaletteMode=CUSTOM. The layer format is the same as normal biome layers.") - private KList bottomPalette = new KList<>(); + private List bottomPalette = List.of(); @MinNumber(1) @MaxNumber(512) @@ -261,7 +157,7 @@ public class IrisFloatingChildBiomes implements IRare { private int maxThickness = 96; @Desc("Optional 3D noise that shifts the footprint's XZ sample position per Y layer — naturalizes the walls so they stop looking like a straight extrusion of the 2D footprint. Leave null to disable and keep straight vertical walls. Good defaults: {\"style\":\"SIMPLEX\",\"zoom\":0.25} for gentle undulation, {\"style\":\"FRACTAL_FBM_SIMPLEX\",\"zoom\":0.4} for craggier walls.") - private IrisGeneratorStyle wallWarpStyle = null; + private NoiseStyle wallWarpStyle; @MinNumber(0) @MaxNumber(64) @@ -269,7 +165,7 @@ public class IrisFloatingChildBiomes implements IRare { private double wallWarpAmplitude = 6.0; @Desc("Optional 3D noise that swiss-cheeses the island interior by marking individual blocks as air when the noise exceeds carveThreshold. Leave null to keep the island solid. Good defaults: {\"style\":\"CELLULAR\",\"zoom\":0.3} for bubble pockets, {\"style\":\"VASCULAR\",\"zoom\":0.25} for wormy tunnels.") - private IrisGeneratorStyle carveStyle = null; + private NoiseStyle carveStyle; @Desc("Optional carving biome key or dimension carving entry id whose caveProfile drives floating-island internal air pockets. Dimension carving ids resolve first; biome keys such as carving/mushroom resolve second. When set, this overrides carveStyle while carveThreshold remains a final tuning bias.") private String carving = ""; @@ -283,7 +179,7 @@ public class IrisFloatingChildBiomes implements IRare { private Integer localFluidHeight = null; @Desc("Block used for the internal water pool when localFluidHeight is positive.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String fluidBlock = "minecraft:water"; @Desc("When true, the target biome's decorators apply to the island's top surface.") @@ -297,13 +193,13 @@ public class IrisFloatingChildBiomes implements IRare { @Desc("Uniform shrink factor applied to every object placed on this floating island (inherited, extra, and free-floating). 1.0 = native size, 0.5 = half size, 0.25 = quarter. Useful for making small floating biomes feel believable.") private double objectShrinkFactor = 1.0; - @ArrayType(min = 1, type = IrisObjectPlacement.class) + @MinItems(1) @Desc("Additional object placements anchored to the island top.") - private KList extraObjects = new KList<>(); + private List extraObjects = List.of(); - @ArrayType(min = 1, type = IrisObjectPlacement.class) + @MinItems(1) @Desc("Additional object placements that float freely in air, independent of the island. Forced to ObjectPlaceMode.FLOATING.") - private KList floatingObjects = new KList<>(); + private List floatingObjects = List.of(); @Desc("Visualization color for this floating child in Iris Studio.") private String color = null; @@ -314,63 +210,187 @@ public class IrisFloatingChildBiomes implements IRare { @Desc("Controls how bottomObjectOverrides are combined. INHERIT_ONLY (default) = no bottom objects placed (there is no inherited bottom set). MERGE = same as REPLACE for bottom (no inherited source). REPLACE = uses bottomObjectOverrides list only.") private OverrideMode bottomObjectMode = OverrideMode.INHERIT_ONLY; - @ArrayType(min = 1, type = IrisObjectPlacement.class) + @MinItems(1) @Desc("Object placements that override or supplement the inherited surface objects on the island TOP. Behaviour depends on topObjectMode. INHERIT_ONLY = this list is ignored. MERGE = appended after inherited. REPLACE = used instead of inherited.") - private KList topObjectOverrides = new KList<>(); + private List topObjectOverrides = List.of(); - @ArrayType(min = 1, type = IrisObjectPlacement.class) + @MinItems(1) @Desc("Object placements anchored to the island BOTTOM face. Each entry is auto-inverted 180 degrees around the X axis and placed flush against the lowest solid face of the island, so objects appear to hang upside-down from the underside. WARNING: directional blocks (stairs, doors, slabs) will not render correctly when flipped — use non-directional content (logs, leaves, stone, mycelium, ice, glass) for bottom placements.") - private KList bottomObjectOverrides = new KList<>(); + private List bottomObjectOverrides = List.of(); - public KList resolveTopObjects(IrisBiome target) { - KList surfaceObjects = (inheritObjects && target != null) ? target.getSurfaceObjects() : new KList<>(); - return resolveTopObjectsFromSurface(surfaceObjects); + public FloatingChildBiome() { } - KList resolveTopObjectsFromSurface(KList surfaceObjects) { - return switch (topObjectMode) { - case REPLACE -> new KList<>(topObjectOverrides); - case MERGE -> { - KList merged = new KList<>(); - merged.addAll(surfaceObjects); - merged.addAll(topObjectOverrides); - yield merged; - } - case INHERIT_ONLY -> surfaceObjects; - }; + public String biome() { + return biome == null ? "" : biome; } - public KList resolveBottomObjects(IrisBiome target) { - return switch (bottomObjectMode) { - case INHERIT_ONLY -> new KList<>(); - case MERGE, REPLACE -> bottomObjectOverrides; - }; + public int rarity() { + return rarity; } - public boolean hasObjectShrink() { - return objectShrinkFactor > 0 && objectShrinkFactor < 1.0; + public NoiseStyle footprintStyle() { + return footprintStyle == null ? DEFAULT_FOOTPRINT_STYLE : footprintStyle; } - public IrisObjectScale getShrinkScale() { - return shrinkScaleCache.aquire(() -> { - IrisObjectScale s = new IrisObjectScale(); - s.setSize(Math.max(0.01, Math.min(1.0, objectShrinkFactor))); - return s; - }); + public double footprintThreshold() { + return footprintThreshold; } - public IrisBiome getRealBiome(IrisBiome parent, IrisData data) { - return resolvedBiome.aquire(() -> { - if (biome == null || biome.isBlank() || biome.equals(parent.getLoadKey())) { - return parent; - } + public int edgeTaperWidth() { + return edgeTaperWidth; + } - IrisBiome loaded = data.getBiomeLoader().load(biome); - if (loaded == null) { - return parent; - } + public double edgeTaperExponent() { + return edgeTaperExponent; + } - return loaded; - }); + public NoiseStyle edgeTaperVariationStyle() { + return edgeTaperVariationStyle == null ? DEFAULT_EDGE_TAPER_VARIATION_STYLE : edgeTaperVariationStyle; + } + + public double edgeTaperVariationAmplitude() { + return edgeTaperVariationAmplitude; + } + + public NoiseStyle pickerStyle() { + return pickerStyle == null ? DEFAULT_PICKER_STYLE : pickerStyle; + } + + public NoiseStyle altitudeStyle() { + return altitudeStyle == null ? DEFAULT_ALTITUDE_STYLE : altitudeStyle; + } + + public int minHeightAboveSurface() { + return minHeightAboveSurface; + } + + public int maxHeightAboveSurface() { + return maxHeightAboveSurface; + } + + /** Empty where the pack sets none. */ + public OptionalInt minAbsoluteY() { + return minAbsoluteY == null ? OptionalInt.empty() : OptionalInt.of(minAbsoluteY); + } + + /** Empty where the pack sets none. */ + public OptionalInt maxAbsoluteY() { + return maxAbsoluteY == null ? OptionalInt.empty() : OptionalInt.of(maxAbsoluteY); + } + + public TopShapeMode topShapeMode() { + return topShapeMode == null ? TopShapeMode.BIOME : topShapeMode; + } + + public int maxTopHeight() { + return maxTopHeight; + } + + public NoiseStyle topShapeStyle() { + return topShapeStyle == null ? DEFAULT_TOP_SHAPE_STYLE : topShapeStyle; + } + + public double topShapeAmp() { + return topShapeAmp; + } + + public NoiseStyle bottomStyle() { + return bottomStyle == null ? DEFAULT_BOTTOM_STYLE : bottomStyle; + } + + public int bottomDepthMin() { + return bottomDepthMin; + } + + public int bottomDepthMax() { + return bottomDepthMax; + } + + public double bottomExponent() { + return bottomExponent; + } + + public FloatingBottomPaletteMode bottomPaletteMode() { + return bottomPaletteMode == null ? FloatingBottomPaletteMode.DEPTH : bottomPaletteMode; + } + + public List bottomPalette() { + return bottomPalette == null ? List.of() : Collections.unmodifiableList(bottomPalette); + } + + public int maxThickness() { + return maxThickness; + } + + /** Empty where the pack sets none. */ + public Optional wallWarpStyle() { + return Optional.ofNullable(wallWarpStyle); + } + + public double wallWarpAmplitude() { + return wallWarpAmplitude; + } + + /** Empty where the pack sets none. */ + public Optional carveStyle() { + return Optional.ofNullable(carveStyle); + } + + public String carving() { + return carving == null ? "" : carving; + } + + public double carveThreshold() { + return carveThreshold; + } + + /** Empty where the pack sets none. */ + public OptionalInt localFluidHeight() { + return localFluidHeight == null ? OptionalInt.empty() : OptionalInt.of(localFluidHeight); + } + + public String fluidBlock() { + return fluidBlock == null ? "" : fluidBlock; + } + + public boolean inheritDecorators() { + return inheritDecorators; + } + + public boolean inheritObjects() { + return inheritObjects; + } + + public double objectShrinkFactor() { + return objectShrinkFactor; + } + + public List extraObjects() { + return extraObjects == null ? List.of() : Collections.unmodifiableList(extraObjects); + } + + public List floatingObjects() { + return floatingObjects == null ? List.of() : Collections.unmodifiableList(floatingObjects); + } + + public String color() { + return color == null ? "" : color; + } + + public OverrideMode topObjectMode() { + return topObjectMode == null ? OverrideMode.INHERIT_ONLY : topObjectMode; + } + + public OverrideMode bottomObjectMode() { + return bottomObjectMode == null ? OverrideMode.INHERIT_ONLY : bottomObjectMode; + } + + public List topObjectOverrides() { + return topObjectOverrides == null ? List.of() : Collections.unmodifiableList(topObjectOverrides); + } + + public List bottomObjectOverrides() { + return bottomObjectOverrides == null ? List.of() : Collections.unmodifiableList(bottomObjectOverrides); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java b/src/main/java/art/arcane/iris/builtin/floating/OverrideMode.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java rename to src/main/java/art/arcane/iris/builtin/floating/OverrideMode.java index 866821177..a9c77a468 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/OverrideMode.java +++ b/src/main/java/art/arcane/iris/builtin/floating/OverrideMode.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.terrain.floating; +package art.arcane.iris.builtin.floating; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls how an override list is combined with the inherited object set from the target biome.") public enum OverrideMode { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java b/src/main/java/art/arcane/iris/builtin/floating/TopShapeMode.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java rename to src/main/java/art/arcane/iris/builtin/floating/TopShapeMode.java index f6151c6e3..873128902 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/TopShapeMode.java +++ b/src/main/java/art/arcane/iris/builtin/floating/TopShapeMode.java @@ -16,9 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.terrain.floating; +package art.arcane.iris.builtin.floating; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("How the top profile of a floating-child island is shaped.") public enum TopShapeMode { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 5878a5282..999bef590 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -18,6 +18,9 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.core.loader.IrisData; @@ -29,7 +32,6 @@ import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; @@ -47,6 +49,7 @@ import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -91,10 +94,10 @@ public class FloatingObjectPlacing { // The IdentityHashMaps are lookup indices only. Iteration MUST follow the encounter // order of the deterministic 0..255 column scan: identity-hash order changes per JVM // run, and the shared chunkRng makes placement output depend on iteration order. - IdentityHashMap> entryColumns = new IdentityHashMap<>(); - IdentityHashMap> bottomEntryColumns = new IdentityHashMap<>(); - KList entryOrder = new KList<>(); - KList bottomEntryOrder = new KList<>(); + IdentityHashMap> entryColumns = new IdentityHashMap<>(); + IdentityHashMap> bottomEntryColumns = new IdentityHashMap<>(); + KList entryOrder = new KList<>(); + KList bottomEntryOrder = new KList<>(); for (int i = 0; i < 256; i++) { FloatingIslandSample s = samples[i]; if (s == null || s.entry == null) { @@ -104,7 +107,7 @@ public class FloatingObjectPlacing { entryOrder.add(e); return new KList<>(); }).add(i); - IrisFloatingChildBiomes bottomEntry = s.bottomEntry(); + ResolvedFloatingChild bottomEntry = s.bottomEntry(); if (bottomEntry != null) { bottomEntryColumns.computeIfAbsent(bottomEntry, e -> { bottomEntryOrder.add(e); @@ -113,7 +116,7 @@ public class FloatingObjectPlacing { } } - for (IrisFloatingChildBiomes entry : entryOrder) { + for (ResolvedFloatingChild entry : entryOrder) { KList columns = entryColumns.get(entry); if (columns.isEmpty()) { continue; @@ -123,7 +126,7 @@ public class FloatingObjectPlacing { IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4)); IrisBiome target = entry.getRealBiome(parent, data); - KList floating = entry.getFloatingObjects(); + KList floating = new KList<>(entry.settings().floatingObjects()); if (floating != null && !floating.isEmpty()) { for (IrisObjectPlacement placement : floating) { tryPlaceFloatingChunk(writer, complex, chunkRng, data, placement, columns, minX, minZ, entry); @@ -131,7 +134,7 @@ public class FloatingObjectPlacing { } KList surface = target != null ? entry.resolveTopObjects(target) : null; - KList extras = entry.getExtraObjects(); + KList extras = new KList<>(entry.settings().extraObjects()); boolean hasSurface = surface != null && !surface.isEmpty(); boolean hasExtras = extras != null && !extras.isEmpty(); KList interior = null; @@ -150,7 +153,7 @@ public class FloatingObjectPlacing { } } - for (IrisFloatingChildBiomes entry : bottomEntryOrder) { + for (ResolvedFloatingChild entry : bottomEntryOrder) { KList columns = bottomEntryColumns.get(entry); if (columns.isEmpty()) { continue; @@ -170,7 +173,7 @@ public class FloatingObjectPlacing { } @ChunkCoordinates - private void tryPlaceFloatingChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, KList columns, int minX, int minZ, IrisFloatingChildBiomes entry) { + private void tryPlaceFloatingChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, KList columns, int minX, int minZ, ResolvedFloatingChild entry) { if (placement == null || columns == null || columns.isEmpty()) { return; } @@ -216,7 +219,7 @@ public class FloatingObjectPlacing { } @ChunkCoordinates - private void tryPlaceAnchoredChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, IrisFloatingChildBiomes entry) { + private void tryPlaceAnchoredChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, ResolvedFloatingChild entry) { if (placement == null || columns.isEmpty()) { return; } @@ -301,7 +304,7 @@ public class FloatingObjectPlacing { } @ChunkCoordinates - private void tryPlaceInvertedChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, IrisFloatingChildBiomes entry) { + private void tryPlaceInvertedChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, ResolvedFloatingChild entry) { if (placement == null || columns.isEmpty()) { return; } @@ -405,7 +408,7 @@ public class FloatingObjectPlacing { static boolean isFootprintFlatBottom(FloatingObjectFootprint fp, IrisObjectRotation rotation, int pickedX, int pickedZ, int pickBottomY, IslandObjectPlacer.SampleProvider samples, - IrisFloatingChildBiomes entry, int tolerance) { + ResolvedFloatingChild entry, int tolerance) { IrisBlockVector anchor = invertedFootprintAnchor(fp, rotation); long[] cells = fp.footprintXZ(); if (cells.length == 0) { @@ -475,7 +478,7 @@ public class FloatingObjectPlacing { static boolean isFootprintFlat(FloatingObjectFootprint fp, int pickedX, int pickedZ, int pickTopY, IslandObjectPlacer.SampleProvider samples, - IrisFloatingChildBiomes entry, int tolerance) { + ResolvedFloatingChild entry, int tolerance) { int tallestKx = fp.getTallestKx(); int tallestKz = fp.getTallestKz(); long[] cells = fp.footprintXZ(); @@ -499,7 +502,7 @@ public class FloatingObjectPlacing { private static KList interiorColumns(IslandObjectPlacer.SampleProvider samples, KList columns, int minX, int minZ, - IrisFloatingChildBiomes entry, + ResolvedFloatingChild entry, IslandObjectPlacer.AnchorFace face) { KList interior = new KList<>(); for (int key : columns) { @@ -554,15 +557,15 @@ public class FloatingObjectPlacing { try { IrisData data = engine.getData(); for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - KList entries = biome.getFloatingChildBiomes(); - if (entries == null || entries.isEmpty()) { + List settings = biome.getFloatingChildBiomes(); + if (settings == null || settings.isEmpty()) { continue; } - for (IrisFloatingChildBiomes entry : entries) { - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getFloatingObjects(), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getExtraObjects(), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getTopObjectOverrides(), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.getBottomObjectOverrides(), data, sizeCache, warnedLargeObjects)); + for (ResolvedFloatingChild entry : FloatingChildren.of(engine).of(settings)) { + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().floatingObjects()), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().extraObjects()), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().topObjectOverrides()), data, sizeCache, warnedLargeObjects)); + maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().bottomObjectOverrides()), data, sizeCache, warnedLargeObjects)); try { IrisBiome target = entry.getRealBiome(biome, data); if (target != null) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java index 11cd38d58..6462a1af3 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; 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.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.spi.PlatformBlockState; import org.jetbrains.annotations.Nullable; @@ -34,7 +34,7 @@ public final class IslandObjectPlacer implements IObjectPlacer { private final MantleWriter wrapped; private final SampleProvider samples; - private final IrisFloatingChildBiomes entry; + private final ResolvedFloatingChild entry; private final int anchorY; private final AnchorFace face; @@ -47,12 +47,12 @@ public final class IslandObjectPlacer implements IObjectPlacer { } public static IslandObjectPlacer top(MantleWriter wrapped, SampleProvider samples, - IrisFloatingChildBiomes entry, int anchorY) { + ResolvedFloatingChild entry, int anchorY) { return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.TOP)); } public static IslandObjectPlacer bottom(MantleWriter wrapped, SampleProvider samples, - IrisFloatingChildBiomes entry, int anchorY) { + ResolvedFloatingChild entry, int anchorY) { return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.BOTTOM)); } @@ -157,7 +157,7 @@ public final class IslandObjectPlacer implements IObjectPlacer { return wrapped == null ? null : wrapped.getEngine(); } - static boolean matchesAnchor(FloatingIslandSample sample, IrisFloatingChildBiomes entry, AnchorFace face) { + static boolean matchesAnchor(FloatingIslandSample sample, ResolvedFloatingChild entry, AnchorFace face) { if (sample == null) { return false; } @@ -212,7 +212,7 @@ public final class IslandObjectPlacer implements IObjectPlacer { private record AnchorSettings( SampleProvider samples, - IrisFloatingChildBiomes entry, + ResolvedFloatingChild entry, int anchorY, AnchorFace face ) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 713740fc3..2d0c865de 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -19,6 +19,8 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; +import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; import art.arcane.iris.core.loader.IrisData; @@ -27,14 +29,12 @@ import art.arcane.iris.engine.decorator.FloatingDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineDecorator; -import art.arcane.iris.engine.object.terrain.floating.FloatingBottomPaletteMode; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.decoration.IrisDecorationPart; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.context.ChunkContext; @@ -65,11 +65,11 @@ public class FloatingIslands { private final RNG rng; private final EngineDecorator seaSurfaceDecorator; - private static KList generateBottomPaletteLayers(IrisFloatingChildBiomes entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { - if (entry == null || entry.getBottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.getBottomPalette() == null || entry.getBottomPalette().isEmpty()) { + private static KList generateBottomPaletteLayers(ResolvedFloatingChild entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { + if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette() == null || entry.settings().bottomPalette().isEmpty()) { return null; } - return generatePaletteLayers(dimension, entry.getBottomPalette(), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex); + return generatePaletteLayers(dimension, new KList<>(entry.settings().bottomPalette()), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex); } private static KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) { @@ -127,8 +127,8 @@ public class FloatingIslands { return generated; } - private static boolean usesBottomPalette(IrisFloatingChildBiomes entry) { - FloatingBottomPaletteMode mode = entry == null || entry.getBottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.getBottomPaletteMode(); + private static boolean usesBottomPalette(ResolvedFloatingChild entry) { + FloatingBottomPaletteMode mode = entry == null || entry.settings().bottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode(); return mode != FloatingBottomPaletteMode.DEPTH; } @@ -138,7 +138,7 @@ public class FloatingIslands { bottomDepths[i] = -1; } - IdentityHashMap depthByEntry = new IdentityHashMap<>(); + IdentityHashMap depthByEntry = new IdentityHashMap<>(); int max = Math.min(sample.topIdx, sample.solidMask.length - 1); for (int k = 0; k <= max; k++) { if (!sample.solidMask[k]) { @@ -148,7 +148,7 @@ public class FloatingIslands { if (y < 0 || y >= chunkHeight) { continue; } - IrisFloatingChildBiomes entry = sample.entryAt(k); + ResolvedFloatingChild entry = sample.entryAt(k); int depth = depthByEntry.getOrDefault(entry, 0); bottomDepths[k] = depth; depthByEntry.put(entry, depth + 1); @@ -157,8 +157,8 @@ public class FloatingIslands { return bottomDepths; } - private static PlatformBlockState selectPaletteBlock(IrisFloatingChildBiomes entry, KList topBlocks, KList bottomBlocks, int topDepth, int bottomDepth, PlatformBlockState fallbackSolid) { - FloatingBottomPaletteMode mode = entry == null || entry.getBottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.getBottomPaletteMode(); + private static PlatformBlockState selectPaletteBlock(ResolvedFloatingChild entry, KList topBlocks, KList bottomBlocks, int topDepth, int bottomDepth, PlatformBlockState fallbackSolid) { + FloatingBottomPaletteMode mode = entry == null || entry.settings().bottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode(); if (mode == FloatingBottomPaletteMode.MIRROR_TOP) { return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth), fallbackSolid); } @@ -179,9 +179,9 @@ public class FloatingIslands { return block == null ? fallbackSolid : block; } - private PaletteContext createPaletteContext(IrisBiome parent, IrisFloatingChildBiomes entry, IrisDimension dimension, int wx, int wz, long colSeed, int paletteDepth, IrisData data, IrisComplex complex) { + private PaletteContext createPaletteContext(IrisBiome parent, ResolvedFloatingChild entry, IrisDimension dimension, int wx, int wz, long colSeed, int paletteDepth, IrisData data, IrisComplex complex) { IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); - int entrySeed = entry == null || entry.getBiome() == null ? 0 : entry.getBiome().hashCode(); + int entrySeed = entry == null || entry.settings().biome() == null ? 0 : entry.settings().biome().hashCode(); RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed)); KList topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); if (topBlocks == null || topBlocks.isEmpty()) { @@ -235,8 +235,8 @@ public class FloatingIslands { long colSeed = FloatingIslandSample.columnSeed(baseSeed, wx, wz); int paletteDepth = Math.max(4, sample.solidCount + 4); - IdentityHashMap paletteContexts = new IdentityHashMap<>(); - IdentityHashMap topDepthByEntry = new IdentityHashMap<>(); + IdentityHashMap paletteContexts = new IdentityHashMap<>(); + IdentityHashMap topDepthByEntry = new IdentityHashMap<>(); int[] bottomDepths = bottomDepths(sample, chunkHeight); for (int k = sample.topIdx; k >= 0; k--) { if (!sample.solidMask[k]) { @@ -246,7 +246,7 @@ public class FloatingIslands { if (y < 0 || y >= chunkHeight) { continue; } - IrisFloatingChildBiomes entry = sample.entryAt(k); + ResolvedFloatingChild entry = sample.entryAt(k); PaletteContext paletteContext = paletteContexts.get(entry); if (paletteContext == null) { paletteContext = createPaletteContext(parent, entry, dimension, wx, wz, colSeed, paletteDepth, data, complex); @@ -261,10 +261,10 @@ public class FloatingIslands { topDepthByEntry.put(entry, depth + 1); } - IrisFloatingChildBiomes entry = sample.entry; - Integer localFluidHeight = entry.getLocalFluidHeight(); - if (localFluidHeight != null && localFluidHeight > 0) { - PlatformBlockState fluid = B.getStateOrNull(entry.getFluidBlock()); + ResolvedFloatingChild entry = sample.entry; + int localFluidHeight = entry.settings().localFluidHeight().orElse(0); + if (localFluidHeight > 0) { + PlatformBlockState fluid = B.getStateOrNull(entry.settings().fluidBlock()); if (fluid == null) { fluid = B.getState("minecraft:water"); } @@ -317,10 +317,10 @@ public class FloatingIslands { if (sample == null) { continue; } - IrisFloatingChildBiomes entry = sample.entry; + ResolvedFloatingChild entry = sample.entry; IrisBiome target = entry.getRealBiome(parent, data); - if (!entry.isInheritDecorators() || target == null) { + if (!entry.settings().inheritDecorators() || target == null) { continue; } @@ -338,8 +338,8 @@ public class FloatingIslands { } } - Integer localFluidHeight = entry.getLocalFluidHeight(); - if (localFluidHeight != null && localFluidHeight > 0) { + int localFluidHeight = entry.settings().localFluidHeight().orElse(0); + if (localFluidHeight > 0) { int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); int fluidTopY = -1; for (int k = 1; k <= fluidCap; k++) { @@ -375,7 +375,7 @@ public class FloatingIslands { private void writeIslandSkyBiomes(IrisBiome parent, int wx, int wz, FloatingIslandSample sample, int chunkHeight, IrisData data) { try { - IdentityHashMap matterByEntry = new IdentityHashMap<>(); + IdentityHashMap matterByEntry = new IdentityHashMap<>(); for (int k = 0; k <= sample.topIdx; k++) { if (!sample.solidMask[k]) { continue; @@ -384,7 +384,7 @@ public class FloatingIslands { if (y < 0 || y >= chunkHeight) { continue; } - IrisFloatingChildBiomes entry = sample.entryAt(k); + ResolvedFloatingChild entry = sample.entryAt(k); MatterBiomeInject matter = matterByEntry.get(entry); if (matter == null) { IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 61687340b..691d6ba22 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisMantleChunk; @@ -46,6 +48,11 @@ public final class FloatingModule implements IrisModule { return ModuleInfo.of("iris:floating", "Floating islands", VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(FloatingChildBiome.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE.ref()).reach(FloatingModule::objectReach) diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java new file mode 100644 index 000000000..2a7492f4c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java @@ -0,0 +1,56 @@ +/* + * 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.terrain.floating; + +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.Engine; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** The {@link ResolvedFloatingChild} of every {@link FloatingChildBiome} an engine runtime has met, one per decoded entry. */ +public final class FloatingChildren { + private final Map resolved = new ConcurrentHashMap<>(); + + public FloatingChildren(Engine engine) { + } + + FloatingChildren() { + } + + /** The children of the engine {@code data} serves, or of {@code data} alone when no engine runs it. */ + public static FloatingChildren of(IrisData data) { + Engine engine = data.getEngine(); + return engine == null ? new FloatingChildren() : of(engine); + } + + public static FloatingChildren of(Engine engine) { + return engine.getGeneration().state(FloatingChildren.class, FloatingChildren::new); + } + + public ResolvedFloatingChild of(FloatingChildBiome settings) { + return resolved.computeIfAbsent(settings, ResolvedFloatingChild::new); + } + + public List of(List settings) { + return settings.stream().map(this::of).toList(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java index e9d3403b4..4e0575a6a 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java @@ -83,11 +83,11 @@ public final class FloatingIslandBoundarySampler { return field.sample(x, z); } - public OwnershipSample ownership(KList entries, CNG picker, int x, int z) { + public OwnershipSample ownership(KList entries, CNG picker, int x, int z) { return ownership(entries, picker, x, z, EDGE_TAPER_WIDTH); } - public OwnershipSample ownership(KList entries, CNG picker, int x, int z, + public OwnershipSample ownership(KList entries, CNG picker, int x, int z, int taperWidth) { int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); int chunkX = Math.floorDiv(x, CHUNK_SIZE); @@ -131,7 +131,7 @@ public final class FloatingIslandBoundarySampler { int boundaryDistance, double edgeFade) { } - public record OwnershipSample(IrisFloatingChildBiomes owner, int boundaryDistance, double edgeFade) { + public record OwnershipSample(ResolvedFloatingChild owner, int boundaryDistance, double edgeFade) { } private record ParentFieldKey(long chunkKey, int taperWidth) { @@ -175,13 +175,13 @@ public final class FloatingIslandBoundarySampler { } private static final class OwnershipFieldKey { - private final KList entries; + private final KList entries; private final CNG picker; private final int chunkX; private final int chunkZ; private final int taperWidth; - private OwnershipFieldKey(KList entries, CNG picker, int chunkX, int chunkZ, + private OwnershipFieldKey(KList entries, CNG picker, int chunkX, int chunkZ, int taperWidth) { this.entries = entries; this.picker = picker; @@ -394,15 +394,15 @@ public final class FloatingIslandBoundarySampler { private final FieldGeometry geometry; private final int minX; private final int minZ; - private final IrisFloatingChildBiomes[] owners; - private final IdentityHashMap distances; + private final ResolvedFloatingChild[] owners; + private final IdentityHashMap distances; - private OwnershipField(KList entries, CNG picker, int chunkX, int chunkZ, + private OwnershipField(KList entries, CNG picker, int chunkX, int chunkZ, int taperWidth) { this.geometry = FieldGeometry.forWidth(taperWidth); this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); this.minZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); - this.owners = new IrisFloatingChildBiomes[geometry.area()]; + this.owners = new ResolvedFloatingChild[geometry.area()]; this.distances = new IdentityHashMap<>(); for (int z = 0; z < geometry.fieldSize(); z++) { for (int x = 0; x < geometry.fieldSize(); x++) { @@ -410,7 +410,7 @@ public final class FloatingIslandBoundarySampler { owners[geometry.index(x, z)] = IRare.pick(entries, value); } } - for (IrisFloatingChildBiomes entry : entries) { + for (ResolvedFloatingChild entry : entries) { if (entry != null && !distances.containsKey(entry)) { distances.put(entry, buildDistanceField(entry)); } @@ -419,7 +419,7 @@ public final class FloatingIslandBoundarySampler { private OwnershipSample sample(int x, int z) { int index = geometry.index(x - minX, z - minZ); - IrisFloatingChildBiomes owner = owners[index]; + ResolvedFloatingChild owner = owners[index]; if (owner == null) { return new OwnershipSample(null, 0, 0.0D); } @@ -435,7 +435,7 @@ public final class FloatingIslandBoundarySampler { return new OwnershipSample(owner, boundaryDistance, fade); } - private ComponentDistanceField buildDistanceField(IrisFloatingChildBiomes owner) { + private ComponentDistanceField buildDistanceField(ResolvedFloatingChild owner) { boolean[] owned = new boolean[owners.length]; byte[] distance = new byte[owners.length]; boolean[] viable = new boolean[owners.length]; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index abbaa1257..7fc7b6f1c 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.terrain.floating; +import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.core.loader.IrisData; @@ -28,6 +29,8 @@ import art.arcane.volmlib.util.collection.KList; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.util.Arrays; +import java.util.List; +import java.util.OptionalInt; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.concurrent.atomic.AtomicBoolean; @@ -99,20 +102,20 @@ public final class FloatingIslandSample { } } - public final IrisFloatingChildBiomes entry; + public final ResolvedFloatingChild entry; public final int islandBaseY; public final int thickness; public final int topIdx; public final int solidCount; public final boolean[] solidMask; - private final IrisFloatingChildBiomes[] entryMask; + private final ResolvedFloatingChild[] entryMask; private transient int cachedBottomIdx = -2; - private FloatingIslandSample(IrisFloatingChildBiomes entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask) { + private FloatingIslandSample(ResolvedFloatingChild entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask) { this(entry, islandBaseY, thickness, topIdx, solidCount, solidMask, null); } - private FloatingIslandSample(IrisFloatingChildBiomes entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, IrisFloatingChildBiomes[] entryMask) { + private FloatingIslandSample(ResolvedFloatingChild entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, ResolvedFloatingChild[] entryMask) { this.entry = entry; this.islandBaseY = islandBaseY; this.thickness = thickness; @@ -126,7 +129,7 @@ public final class FloatingIslandSample { return new FloatingIslandSample(null, islandBaseY, thickness, topIdx, solidCount, solidMask); } - static FloatingIslandSample constructForTest(IrisFloatingChildBiomes entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, IrisFloatingChildBiomes[] entryMask) { + static FloatingIslandSample constructForTest(ResolvedFloatingChild entry, int islandBaseY, int thickness, int topIdx, int solidCount, boolean[] solidMask, ResolvedFloatingChild[] entryMask) { return new FloatingIslandSample(entry, islandBaseY, thickness, topIdx, solidCount, solidMask, entryMask); } @@ -147,7 +150,7 @@ public final class FloatingIslandSample { return cachedBottomIdx == -1 ? -1 : islandBaseY + cachedBottomIdx; } - public IrisFloatingChildBiomes entryAt(int maskIndex) { + public ResolvedFloatingChild entryAt(int maskIndex) { if (entryMask != null && maskIndex >= 0 && maskIndex < entryMask.length && entryMask[maskIndex] != null) { return entryMask[maskIndex]; } @@ -155,7 +158,7 @@ public final class FloatingIslandSample { return entry; } - public IrisFloatingChildBiomes bottomEntry() { + public ResolvedFloatingChild bottomEntry() { int bottomY = bottomY(); if (bottomY < 0) { return entry; @@ -172,17 +175,17 @@ public final class FloatingIslandSample { return baseSeed ^ ((long) wx * 341873128712L) ^ ((long) wz * 132897987541L); } - private static int maximumEdgeFieldWidth(KList entries, long baseSeed, + private static int maximumEdgeFieldWidth(KList entries, long baseSeed, IrisData data, IrisBiome parent) { int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH; - for (IrisFloatingChildBiomes entry : entries) { + for (ResolvedFloatingChild entry : entries) { FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent); maximumWidth = Math.max(maximumWidth, profile.fieldWidth()); } return maximumWidth; } - private static FloatingIslandEdgeProfile resolveEdgeProfile(IrisFloatingChildBiomes entry, long baseSeed, + private static FloatingIslandEdgeProfile resolveEdgeProfile(ResolvedFloatingChild entry, long baseSeed, IrisData data, IrisBiome parent) { FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data); if (profile != null) { @@ -193,11 +196,15 @@ public final class FloatingIslandSample { } public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { - KList entries = parent.getFloatingChildBiomes(); - if (entries == null || entries.isEmpty()) { + List settings = parent.getFloatingChildBiomes(); + if (settings == null || settings.isEmpty()) { return reject(REJECT_NO_ENTRIES); } + KList entries = new KList<>(FloatingChildren.of(data).of(settings)); + return sample(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); + } + static FloatingIslandSample sample(IrisBiome parent, KList entries, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent); int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); @@ -206,12 +213,12 @@ public final class FloatingIslandSample { parentBoundaryDistance, boundaryFieldWidth); } - IrisFloatingChildBiomes entry; + ResolvedFloatingChild entry; int ownershipBoundaryDistance = boundaryFieldWidth + 1; if (entries.size() == 1) { entry = entries.getFirst(); } else { - IrisFloatingChildBiomes reference = entries.getFirst(); + ResolvedFloatingChild reference = entries.getFirst(); CNG picker = reference.getPickerCng(baseSeed, data); if (picker == null) { warnNullCng("pickerStyle", parent); @@ -230,7 +237,7 @@ public final class FloatingIslandSample { parentBoundaryDistance, ownershipBoundaryDistance); } - private static FloatingIslandSample sampleMerged(IrisBiome parent, KList entries, + private static FloatingIslandSample sampleMerged(IrisBiome parent, KList entries, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, int parentBoundaryDistance, int boundaryFieldWidth) { @@ -238,7 +245,7 @@ public final class FloatingIslandSample { int minY = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; - for (IrisFloatingChildBiomes entry : entries) { + for (ResolvedFloatingChild entry : entries) { FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1); if (sample == null) { @@ -266,7 +273,7 @@ public final class FloatingIslandSample { int thickness = maxY - minY + 1; boolean[] solidMask = new boolean[thickness]; - IrisFloatingChildBiomes[] entryMask = new IrisFloatingChildBiomes[thickness]; + ResolvedFloatingChild[] entryMask = new ResolvedFloatingChild[thickness]; int[] entryTopY = new int[thickness]; Arrays.fill(entryTopY, Integer.MIN_VALUE); int solidCount = 0; @@ -296,12 +303,12 @@ public final class FloatingIslandSample { return reject(REJECT_NO_SOLID); } - IrisFloatingChildBiomes topEntry = entryMask[topIdx] == null ? samples.getFirst().entry : entryMask[topIdx]; + ResolvedFloatingChild topEntry = entryMask[topIdx] == null ? samples.getFirst().entry : entryMask[topIdx]; LAST_REJECT.get()[0] = REJECT_NONE; return new FloatingIslandSample(topEntry, minY, thickness, topIdx, solidCount, solidMask, entryMask); } - private static FloatingIslandSample sampleEntry(IrisBiome parent, IrisFloatingChildBiomes entry, int wx, int wz, + private static FloatingIslandSample sampleEntry(IrisBiome parent, ResolvedFloatingChild entry, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, int parentBoundaryDistance, int ownershipBoundaryDistance) { @@ -311,7 +318,7 @@ public final class FloatingIslandSample { warnNullCng("footprintStyle", parent); return reject(REJECT_NO_SEED); } - double threshold = Math.max(0, Math.min(1, entry.getFootprintThreshold())); + double threshold = Math.max(0, Math.min(1, entry.settings().footprintThreshold())); double signedCut = (threshold * 2.0) - 1.0; FloatingIslandBoundarySampler.FootprintSample footprint = boundarySampler.footprint( footprintCng, wx, wz, signedCut, edgeProfile.fieldWidth()); @@ -340,8 +347,8 @@ public final class FloatingIslandSample { double altNoise = altitudeCng.noise(wx, wz); double altClamped = Math.max(0, Math.min(1, altNoise)); int worldMin = engine.getWorld().minHeight(); - int minAlt = Math.max(0, entry.getMinHeightAboveSurface() - worldMin); - int maxAlt = Math.max(minAlt, entry.getMaxHeightAboveSurface() - worldMin); + int minAlt = Math.max(0, entry.settings().minHeightAboveSurface() - worldMin); + int maxAlt = Math.max(minAlt, entry.settings().maxHeightAboveSurface() - worldMin); int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); IrisBiome target = entry.getRealBiome(parent, data); @@ -355,9 +362,9 @@ public final class FloatingIslandSample { } double bottomNoise = bottomCng.noise(wx, wz); double bottomClamped = Math.max(0, Math.min(1, bottomNoise)); - double bottomShaped = Math.pow(bottomClamped, Math.max(0.1, entry.getBottomExponent())); - int minDepth = Math.max(0, entry.getBottomDepthMin()); - int maxDepth = Math.max(minDepth, entry.getBottomDepthMax()); + double bottomShaped = Math.pow(bottomClamped, Math.max(0.1, entry.settings().bottomExponent())); + int minDepth = Math.max(0, entry.settings().bottomDepthMin()); + int maxDepth = Math.max(minDepth, entry.settings().bottomDepthMax()); int depth = roundedEdgeDepth(minDepth, maxDepth, bottomShaped, edgeFade); if (topH == 0 && depth == 0) { double fullDepth = minDepth + (bottomShaped * (maxDepth - minDepth)); @@ -372,13 +379,13 @@ public final class FloatingIslandSample { int topY = baseY + topH; int botY = baseY - depth; - Integer minAbsoluteY = entry.getMinAbsoluteY(); - if (minAbsoluteY != null && botY < minAbsoluteY - worldMin) { - botY = minAbsoluteY - worldMin; + OptionalInt minAbsoluteY = entry.settings().minAbsoluteY(); + if (minAbsoluteY.isPresent() && botY < minAbsoluteY.getAsInt() - worldMin) { + botY = minAbsoluteY.getAsInt() - worldMin; } - Integer maxAbsoluteY = entry.getMaxAbsoluteY(); - if (maxAbsoluteY != null && topY > maxAbsoluteY - worldMin) { - topY = maxAbsoluteY - worldMin; + OptionalInt maxAbsoluteY = entry.settings().maxAbsoluteY(); + if (maxAbsoluteY.isPresent() && topY > maxAbsoluteY.getAsInt() - worldMin) { + topY = maxAbsoluteY.getAsInt() - worldMin; } if (botY < 0) { @@ -392,7 +399,7 @@ public final class FloatingIslandSample { } int thickness = topY - botY + 1; - int maxThickness = Math.max(1, entry.getMaxThickness()); + int maxThickness = Math.max(1, entry.settings().maxThickness()); if (thickness > maxThickness) { botY = topY - maxThickness + 1; if (botY < 0) { @@ -406,11 +413,11 @@ public final class FloatingIslandSample { boolean[] solidMask = new boolean[thickness]; CNG wallWarp = entry.getWallWarpCng(baseSeed, data); - double warpAmp = Math.max(0, entry.getWallWarpAmplitude()); + double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude()); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; - double carveThreshold = entry.getCarveThreshold(); + double carveThreshold = entry.settings().carveThreshold(); boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; boolean useProfileCarve = carvingProfileSampler != null; boolean useCarve = directCarveEnabled(entry, carvingProfileSampler, carve, carveThreshold); @@ -477,7 +484,7 @@ public final class FloatingIslandSample { return amplitude * fade; } - static boolean directCarveEnabled(IrisFloatingChildBiomes entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { + static boolean directCarveEnabled(ResolvedFloatingChild entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; } @@ -768,12 +775,12 @@ public final class FloatingIslandSample { } } - private static int computeTopHeight(IrisFloatingChildBiomes entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) { - int maxTopHeight = Math.max(0, entry.getMaxTopHeight()); + private static int computeTopHeight(ResolvedFloatingChild entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) { + int maxTopHeight = Math.max(0, entry.settings().maxTopHeight()); if (maxTopHeight == 0) { return 0; } - return switch (entry.getTopShapeMode()) { + return switch (entry.settings().topShapeMode()) { case FLAT -> maxTopHeight; case NOISE -> { CNG topCng = entry.getTopShapeCng(baseSeed, data); @@ -783,7 +790,7 @@ public final class FloatingIslandSample { } double n = topCng.noise(wx, wz); double clamped = Math.max(0, Math.min(1, n)); - double amp = Math.max(0, Math.min(1, entry.getTopShapeAmp())); + double amp = Math.max(0, Math.min(1, entry.settings().topShapeAmp())); yield (int) Math.round(clamped * amp * maxTopHeight); } case BIOME -> { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java new file mode 100644 index 000000000..e50ec5226 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -0,0 +1,226 @@ +/* + * 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.terrain.floating; + +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisValues; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.prefab.IrisObjectScale; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; +import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.value.IRare; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +/** + * A {@link FloatingChildBiome} made ready for one engine: the noise its styles build (each from the world seed it is first + * asked with), the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. The + * settings class held these on itself; the engine now keeps one of these per decoded entry ({@link FloatingChildren}). + */ +public final class ResolvedFloatingChild implements IRare { + private final FloatingChildBiome settings; + private final IrisGeneratorStyle footprintStyle; + private final IrisGeneratorStyle edgeTaperVariationStyle; + private final IrisGeneratorStyle pickerStyle; + private final IrisGeneratorStyle altitudeStyle; + private final IrisGeneratorStyle topShapeStyle; + private final IrisGeneratorStyle bottomStyle; + private final IrisGeneratorStyle wallWarpStyle; + private final IrisGeneratorStyle carveStyle; + private final AtomicCache resolvedBiome = new AtomicCache<>(); + private final AtomicCache footprintCache = new AtomicCache<>(); + private final AtomicCache edgeTaperProfileCache = new AtomicCache<>(); + private final AtomicCache pickerCache = new AtomicCache<>(); + private final AtomicCache altitudeCache = new AtomicCache<>(); + private final AtomicCache topShapeCache = new AtomicCache<>(); + private final AtomicCache bottomCache = new AtomicCache<>(); + private final AtomicCache wallWarpCache = new AtomicCache<>(); + private final AtomicCache carveCache = new AtomicCache<>(); + private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); + private final AtomicCache shrinkScaleCache = new AtomicCache<>(); + + public ResolvedFloatingChild(FloatingChildBiome settings) { + this.settings = settings; + this.footprintStyle = IrisValues.generatorStyle(settings.footprintStyle()); + this.edgeTaperVariationStyle = IrisValues.generatorStyle(settings.edgeTaperVariationStyle()); + this.pickerStyle = IrisValues.generatorStyle(settings.pickerStyle()); + this.altitudeStyle = IrisValues.generatorStyle(settings.altitudeStyle()); + this.topShapeStyle = IrisValues.generatorStyle(settings.topShapeStyle()); + this.bottomStyle = IrisValues.generatorStyle(settings.bottomStyle()); + this.wallWarpStyle = settings.wallWarpStyle().map(IrisValues::generatorStyle).orElse(null); + this.carveStyle = settings.carveStyle().map(IrisValues::generatorStyle).orElse(null); + } + + public FloatingChildBiome settings() { + return settings; + } + + @Override + public int getRarity() { + return settings.rarity(); + } + + public CNG getFootprintCng(long baseSeed, IrisData data) { + return footprintCache.aquire(() -> footprintStyle.create(new RNG(baseSeed ^ 0xF007B17DL), data)); + } + + public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) { + return edgeTaperProfileCache.aquire(() -> { + int width = FloatingIslandEdgeProfile.clampWidth(settings.edgeTaperWidth()); + double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude( + settings.edgeTaperVariationAmplitude(), width); + CNG variation = amplitude > 0.0D + ? edgeTaperVariationStyle.create(new RNG(baseSeed ^ 0xED6E7A9E5L), data) + : null; + return new FloatingIslandEdgeProfile(width, settings.edgeTaperExponent(), amplitude, variation); + }); + } + + public CNG getPickerCng(long baseSeed, IrisData data) { + return pickerCache.aquire(() -> pickerStyle.create(new RNG(baseSeed ^ 0x91C4E72DL), data)); + } + + public CNG getAltitudeCng(long baseSeed, IrisData data) { + return altitudeCache.aquire(() -> altitudeStyle.create(new RNG(baseSeed ^ 0xA17DEBBL), data)); + } + + public CNG getTopShapeCng(long baseSeed, IrisData data) { + return topShapeCache.aquire(() -> topShapeStyle.create(new RNG(baseSeed ^ 0x70970601DEFL), data)); + } + + public CNG getBottomCng(long baseSeed, IrisData data) { + return bottomCache.aquire(() -> bottomStyle.create(new RNG(baseSeed ^ 0xB0770075CAFEL), data)); + } + + public CNG getWallWarpCng(long baseSeed, IrisData data) { + if (wallWarpStyle == null) { + return null; + } + return wallWarpCache.aquire(() -> wallWarpStyle.create(new RNG(baseSeed ^ 0xA117BA17E0FL), data)); + } + + public CNG getCarveCng(long baseSeed, IrisData data) { + if (carveStyle == null) { + return null; + } + return carveCache.aquire(() -> carveStyle.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); + } + + public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { + if (!hasCarvingReference()) { + return null; + } + + return carvingProfileSamplerCache.aquire(() -> { + IrisBiome resolved = resolveCarvingBiome(settings.carving(), engine, data); + if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().enabled()) { + return null; + } + + return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); + }); + } + + public boolean hasCarvingReference() { + String carving = settings.carving(); + return !carving.isBlank(); + } + + static IrisBiome resolveCarvingBiome(String carving, Engine engine, IrisData data) { + if (carving == null || carving.isBlank() || engine == null || data == null) { + return null; + } + + IrisDimension dimension = engine.getDimension(); + if (dimension != null && dimension.getCarvingEntryIndex() != null) { + IrisDimensionCarvingEntry entry = dimension.getCarvingEntryIndex().get(carving); + if (entry != null) { + return IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry); + } + } + + if (data.getBiomeLoader() == null) { + return null; + } + + return data.getBiomeLoader().load(carving); + } + + public KList resolveTopObjects(IrisBiome target) { + KList surfaceObjects = (settings.inheritObjects() && target != null) ? target.getSurfaceObjects() : new KList<>(); + return resolveTopObjectsFromSurface(surfaceObjects); + } + + KList resolveTopObjectsFromSurface(KList surfaceObjects) { + return switch (settings.topObjectMode()) { + case REPLACE -> new KList<>(settings.topObjectOverrides()); + case MERGE -> { + KList merged = new KList<>(); + merged.addAll(surfaceObjects); + merged.addAll(settings.topObjectOverrides()); + yield merged; + } + case INHERIT_ONLY -> surfaceObjects; + }; + } + + public KList resolveBottomObjects(IrisBiome target) { + return switch (settings.bottomObjectMode()) { + case INHERIT_ONLY -> new KList<>(); + case MERGE, REPLACE -> new KList<>(settings.bottomObjectOverrides()); + }; + } + + public boolean hasObjectShrink() { + double shrink = settings.objectShrinkFactor(); + return shrink > 0 && shrink < 1.0; + } + + public IrisObjectScale getShrinkScale() { + return shrinkScaleCache.aquire(() -> { + IrisObjectScale s = new IrisObjectScale(); + s.setSize(Math.max(0.01, Math.min(1.0, settings.objectShrinkFactor()))); + return s; + }); + } + + public IrisBiome getRealBiome(IrisBiome parent, IrisData data) { + return resolvedBiome.aquire(() -> { + String biome = settings.biome(); + if (biome.isBlank() || biome.equals(parent.getLoadKey())) { + return parent; + } + + IrisBiome loaded = data.getBiomeLoader().load(biome); + if (loaded == null) { + return parent; + } + + return loaded; + }); + } +} 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 index 63e72a717..fd7d21bb0 100644 --- 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 @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.world.biome; +import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.decoration.IrisDecorationPart; import art.arcane.iris.engine.object.decoration.IrisDecorator; @@ -36,7 +37,6 @@ import art.arcane.iris.engine.object.terrain.deposit.IrisBiomeOres; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; -import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; 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; @@ -216,9 +216,9 @@ public class IrisBiome extends IrisRegistrant implements IRare { @ArrayType(min = 1, type = IrisStructurePlacement.class) @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this biome") private KList structures = new KList<>(); - @ArrayType(min = 1, type = IrisFloatingChildBiomes.class) + @ArrayType(min = 1, type = FloatingChildBiome.class) @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") - private KList floatingChildBiomes = new KList<>(); + private KList floatingChildBiomes = new KList<>(); @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") private boolean mergeFloatingChildBiomes = false; @ArrayType(min = 1, type = IrisBiomeGeneratorLink.class) 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 index 6c268f50e..399ed59c2 100644 --- 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 @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.world.dimension; +import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; @@ -38,7 +39,6 @@ import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; -import art.arcane.iris.engine.object.terrain.floating.IrisFloatingChildBiomes; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.world.IrisEnvironment; import art.arcane.iris.engine.object.world.IrisWorldBoundary; @@ -584,14 +584,14 @@ public class IrisDimension extends IrisRegistrant { biomes.put(loadKey, biome); addReachableBiomeKeys(pending, biome.getChildren()); addReachableBiomeKey(pending, biome.getCarvingBiome()); - KList floatingChildren = biome.getFloatingChildBiomes(); + KList floatingChildren = biome.getFloatingChildBiomes(); if (floatingChildren == null) { continue; } - for (IrisFloatingChildBiomes floatingChild : floatingChildren) { + for (FloatingChildBiome floatingChild : floatingChildren) { if (floatingChild != null) { - addReachableBiomeKey(pending, floatingChild.getBiome()); - String carvingReference = floatingChild.getCarving(); + addReachableBiomeKey(pending, floatingChild.biome()); + String carvingReference = floatingChild.carving(); IrisDimensionCarvingEntry carvingEntry = carvingEntryIndex.get(carvingReference); addReachableBiomeKey(pending, carvingEntry == null ? carvingReference : carvingEntry.getBiome()); From 8428da4f50a963076e7d3526f7f35594629a57c5 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:24:20 +0200 Subject: [PATCH 039/139] Loot tables, spawners, entities and markers are resource kinds of iris:loot and iris:spawn LootResources and SpawnResources keep the folders and lookups by key; LootValidator is the loot check that was Iris's PackLootValidator. --- .../arcane/iris/engine/loot/LootGiving.java | 2 +- .../arcane/iris/engine/loot/LootModule.java | 6 +- .../iris/engine/loot/LootResources.java | 78 +++++ .../iris/engine/loot/LootValidator.java | 286 ++++++++++++++++++ .../engine/object/entity/IrisEntitySpawn.java | 3 +- .../entity/spawn/IrisSpawnerCooldowns.java | 3 +- .../engine/object/loot/IrisLootReference.java | 3 +- .../engine/object/placement/BlocksModule.java | 3 +- .../object/placement/IrisObjectPlacement.java | 3 +- .../iris/engine/spawn/EntitySpawning.java | 14 +- .../arcane/iris/engine/spawn/SpawnModule.java | 3 +- .../iris/engine/spawn/SpawnResources.java | 111 +++++++ 12 files changed, 499 insertions(+), 16 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootResources.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/LootValidator.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index f747148a8..3613ff1cb 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -70,7 +70,7 @@ public final class LootGiving implements Loot { @Override public List items(PackWorld world, Site site, String key) { Engine engine = engine(world); - IrisLootTable table = engine.getData().getLootLoader().load(key); + IrisLootTable table = LootResources.table(engine.getData(), key); if (table == null) { return List.of(); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index ff32bc104..939bcccb7 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -26,8 +26,8 @@ import com.volmit.service.Loot; import com.volmit.stage.StageGraph; /** - * Module {@code iris:loot}: the loot tables of the pack and the items they and the block drops of the dimension, regions - * and biomes give. It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through + * Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}) and the items they and the block drops + * of the dimension, regions and biomes give. It checks the tables and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through * {@link BlockDrops} when a player breaks a block. */ public final class LootModule implements IrisModule { @@ -44,6 +44,8 @@ public final class LootModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + LootResources.kinds().forEach(registry::registerResourceKind); + registry.registerValidator(new LootValidator()); registry.registerService(Loot.class, new LootGiving()); registry.registerService(BlockDrops.class, new BlockDropping()); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootResources.java b/src/main/java/art/arcane/iris/engine/loot/LootResources.java new file mode 100644 index 000000000..3c0a8faa1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootResources.java @@ -0,0 +1,78 @@ +/* + * 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.loot; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kind of module {@code iris:loot}, which keeps the folder and files Iris packs have always used, and + * lookups by pack key for code that still names loot tables by key. Every lookup goes through the pack's + * {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot. + *

+ * Lookups answer null where Iris's loader 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 LootResources { + /** Loot tables, in {@code loot/}. */ + public static final ResourceKind TABLES = ResourceKind.of("iris:loot/table", "loot", IrisLootTable.class); + + private LootResources() { + } + + /** Every resource kind of the loot module. */ + public static List> kinds() { + return List.of(TABLES); + } + + public static IrisLootTable table(IrisData data, String key) { + if (key == null || key.isBlank()) { + return null; + } + IrisPackResources resources = data.getPackResources(); + try { + return resources.find(TABLES.key(resources.idOf(key))).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** The tables of the pack named by {@code keys}, in order, without the ones the pack lacks. */ + public static KList tables(IrisData data, List keys) { + KList tables = new KList<>(); + for (String key : keys) { + IrisLootTable table = table(data, key); + if (table != null) { + tables.add(table); + } + } + return tables; + } + + /** The key of every loot table of the pack, in key order. */ + public static List tableKeys(IrisData data) { + return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java new file mode 100644 index 000000000..e5f256fcb --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -0,0 +1,286 @@ +/* + * 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.loot; + +import art.arcane.iris.core.modules.IrisValidationContext; +import art.arcane.iris.core.pack.PackIntegerChecks; +import art.arcane.iris.core.pack.PackValidationIo; +import art.arcane.iris.engine.object.loot.IrisLoot; +import art.arcane.iris.engine.object.loot.IrisLootReference; +import art.arcane.iris.engine.object.loot.IrisLootTable; +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 com.volmit.validation.ValidationContext; +import com.volmit.validation.Validator; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot + * reference of a dimension, region or biome names a table the pack has. The files are read as written, like the pack + * validator's other file checks, so a malformed table is reported rather than failing the load. + */ +public final class LootValidator implements Validator { + private static final List LOOT_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); + private static final String JSON_EXTENSION = ".json"; + + @Override + public void validate(ValidationContext pack) { + check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report); + } + + /** What is wrong with the loot tables and loot references of the pack in {@code packFolder}. */ + public static List check(File packFolder) { + List problems = new ArrayList<>(); + if (packFolder == null || !packFolder.isDirectory()) { + return problems; + } + + File lootFolder = new File(packFolder, LootResources.TABLES.folder()); + Set lootKeys = keysOf(lootFolder); + checkTables(lootFolder, problems); + for (String folderName : LOOT_HOST_FOLDERS) { + checkReferences(new File(packFolder, folderName), folderName, lootKeys, problems); + } + return problems; + } + + private static void checkTables(File lootFolder, List problems) { + if (!lootFolder.isDirectory()) { + return; + } + List lootFiles = PackValidationIo.listJsonRecursive(lootFolder); + lootFiles.sort(Comparator.comparing(File::getPath)); + for (File lootFile : lootFiles) { + String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile); + List errors = new ArrayList<>(); + JSONObject table = readTable(lootFile, lootKey, errors); + if (table != null) { + validateLootTable(lootKey, table, errors); + } + report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors); + } + } + + private static void checkReferences(File resourceFolder, String folderName, Set lootKeys, List problems) { + if (!resourceFolder.isDirectory()) { + return; + } + List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); + resourceFiles.sort(Comparator.comparing(File::getPath)); + for (File resourceFile : resourceFiles) { + JSONObject resource = PackValidationIo.readJson(resourceFile); + if (resource == null || !resource.has("loot")) { + continue; + } + String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); + List errors = new ArrayList<>(); + List warnings = new ArrayList<>(); + validateLootReference(hostType(folderName), resourceKey, resource.opt("loot"), lootKeys, errors, warnings); + Subject subject = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION); + report(problems, Problem::error, subject, errors); + report(problems, Problem::warning, subject, warnings); + } + } + + private static void report(List problems, java.util.function.BiFunction severity, + Subject subject, List messages) { + for (String message : messages) { + problems.add(severity.apply(subject, message)); + } + } + + private static Set keysOf(File folder) { + Set keys = new HashSet<>(); + if (!folder.isDirectory()) { + return keys; + } + for (File file : PackValidationIo.listJsonRecursive(folder)) { + String key = PackValidationIo.deriveKey(folder, file); + if (key != null && !key.isBlank()) { + keys.add(key); + } + } + return keys; + } + + private static JSONObject readTable(File file, String key, List errors) { + try { + return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); + } catch (IOException | RuntimeException e) { + String reason = e.getMessage(); + if (reason == null || reason.isBlank()) { + reason = e.getClass().getSimpleName(); + } + errors.add("Loot table '" + key + "' has invalid JSON: " + reason); + return null; + } + } + + private static String hostType(String folderName) { + return switch (folderName) { + case "dimensions" -> "Dimension"; + case "regions" -> "Region"; + case "biomes" -> "Biome"; + default -> "Resource"; + }; + } + + private static void validateLootTable(String lootKey, JSONObject table, List blockingErrors) { + String path = "Loot table '" + lootKey + "'"; + Integer rarity = PackIntegerChecks.integerField(table, "rarity", 1, path, blockingErrors); + Integer minimumPicked = PackIntegerChecks.integerField(table, "minPicked", 1, path, blockingErrors); + Integer maximumPicked = PackIntegerChecks.integerField(table, "maxPicked", 5, path, blockingErrors); + Integer maximumTries = PackIntegerChecks.integerField(table, "maxTries", 10, path, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".rarity", rarity, 1, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors); + PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors); + PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors); + + JSONArray entries = table.optJSONArray("loot"); + if (entries == null || entries.length() == 0) { + blockingErrors.add(path + ".loot must be a non-empty array."); + return; + } + for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) { + JSONObject entry = entries.optJSONObject(entryIndex); + String entryPath = path + ".loot[" + entryIndex + "]"; + if (entry == null) { + blockingErrors.add(entryPath + " must be an object."); + continue; + } + String type = entry.optString("type", "").trim(); + if (type.isEmpty()) { + blockingErrors.add(entryPath + ".type must not be blank."); + } + Integer entryRarity = PackIntegerChecks.integerField(entry, "rarity", 1, entryPath, blockingErrors); + Integer minimumAmount = PackIntegerChecks.integerField(entry, "minAmount", 1, entryPath, blockingErrors); + Integer maximumAmount = PackIntegerChecks.integerField(entry, "maxAmount", 1, entryPath, blockingErrors); + PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors); + PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors); + PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors); + PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); + PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); + PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount, + entryPath + ".maxAmount", maximumAmount, blockingErrors); + validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors); + } + } + + private static void validateLootEnchantments(String entryPath, Object rawEnchantments, + List blockingErrors) { + if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) { + return; + } + if (!(rawEnchantments instanceof JSONArray enchantments)) { + blockingErrors.add(entryPath + ".enchantments must be an array."); + return; + } + for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) { + JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex); + String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]"; + if (enchantment == null) { + blockingErrors.add(enchantmentPath + " must be an object."); + continue; + } + if (enchantment.optString("enchantment", "").isBlank()) { + blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); + } + Integer minimumLevel = PackIntegerChecks.integerField(enchantment, "minLevel", 1, enchantmentPath, blockingErrors); + Integer maximumLevel = PackIntegerChecks.integerField(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors); + PackIntegerChecks.requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors); + PackIntegerChecks.requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors); + PackIntegerChecks.requireOrdered(enchantmentPath + ".minLevel", minimumLevel, + enchantmentPath + ".maxLevel", maximumLevel, blockingErrors); + if (enchantment.has("chance")) { + Object rawChance = enchantment.opt("chance"); + if (!(rawChance instanceof Number number) + || !Double.isFinite(number.doubleValue()) + || number.doubleValue() < 0D + || number.doubleValue() > 1D) { + blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1."); + } + } + } + } + + private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot, + Set lootKeys, List blockingErrors, List warnings) { + String path = resourceType + " '" + resourceKey + "'.loot"; + if (!(rawLoot instanceof JSONObject reference)) { + blockingErrors.add(path + " must be an object."); + return; + } + boolean clearMode = false; + if (reference.has("mode")) { + Object rawMode = reference.opt("mode"); + if (!(rawMode instanceof String mode) + || !Set.of("ADD", "CLEAR", "REPLACE", "FALLBACK").contains(mode)) { + blockingErrors.add(path + ".mode must be ADD, CLEAR, REPLACE, or FALLBACK."); + } else { + clearMode = "CLEAR".equals(mode); + } + } + if (reference.has("multiplier")) { + Object rawMultiplier = reference.opt("multiplier"); + if (!(rawMultiplier instanceof Number multiplier) + || !Double.isFinite(multiplier.doubleValue()) + || multiplier.doubleValue() < 0D + || multiplier.doubleValue() > IrisLootReference.MAX_MULTIPLIER) { + blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + + (int) IrisLootReference.MAX_MULTIPLIER + "."); + } + } + if (!reference.has("tables")) { + return; + } + JSONArray tables = reference.optJSONArray("tables"); + if (tables == null) { + blockingErrors.add(path + ".tables must be an array."); + return; + } + if (clearMode && tables.length() > 0) { + warnings.add(path + " uses mode CLEAR and lists " + tables.length() + + " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."); + } + for (int tableIndex = 0; tableIndex < tables.length(); tableIndex++) { + Object rawTableKey = tables.opt(tableIndex); + if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) { + blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table."); + } else if (!lootKeys.contains(tableKey)) { + blockingErrors.add(path + ".tables[" + tableIndex + + "] references missing loot table '" + tableKey + "'."); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java index b68abf83c..1332e3bf0 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.entity; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IRare; @@ -60,6 +61,6 @@ public class IrisEntitySpawn implements IRare { private transient IrisMarker referenceMarker; public IrisEntity getRealEntity(Engine g) { - return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); + return ent.aquire(() -> SpawnResources.entity(g.getData(), getEntity())); } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java index b53c9ee57..7fdcb744a 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java @@ -1,5 +1,6 @@ package art.arcane.iris.engine.object.entity.spawn; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; import lombok.EqualsAndHashCode; @@ -23,7 +24,7 @@ public class IrisSpawnerCooldowns { public void cleanup(Engine engine) { cooldowns.values().removeIf(cd -> { - IrisSpawner sp = engine.getData().getSpawnerLoader().load(cd.getSpawner()); + IrisSpawner sp = SpawnResources.spawner(engine.getData(), cd.getSpawner()); return sp == null || cd.canSpawn(sp.getMaximumRate()); }); } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java index c2e7b563f..598555154 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.loot; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; @@ -59,7 +60,7 @@ public class IrisLootReference { KList t = new KList<>(); for (String i : tables) { - t.add(g.getData().getLootLoader().load(i)); + t.add(LootResources.table(g.getData(), i)); } return t; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 95acd4342..925db6a1a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; @@ -196,7 +197,7 @@ public final class BlocksModule implements IrisModule { RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; for (IrisObjectMarker markerConfig : config.getMarkers()) { - IrisMarker marker = placement.object().getLoader().getMarkerLoader().load(markerConfig.getMarker()); + IrisMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker()); int markerSalt = salt++; if (marker == null) { continue; 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 index 23b508538..f63e0fa69 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.core.modules.ModuleSettings; import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.engine.object.loot.IrisLootTable; @@ -301,7 +302,7 @@ public class IrisObjectPlacement { TableCache cache = new TableCache(); cache.merge(getCache(manager, getVanillaLoot(), IrisObjectPlacement::getVanillaTable)); - cache.merge(getCache(manager, getLoot(), manager.getLootLoader()::load)); + cache.merge(getCache(manager, getLoot(), key -> LootResources.table(manager, key))); return cache; }); diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 5c9bec4f1..e4aea6f93 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -76,7 +76,7 @@ public final class EntitySpawning implements EntitySpawns { if (count <= 0) { return; } - IrisSpawner spawner = engine(world).getData().getSpawnerLoader().load(plan.spawner()); + IrisSpawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner()); if (spawner != null) { spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ()); } @@ -84,7 +84,7 @@ public final class EntitySpawning implements EntitySpawns { @Override public Optional entity(PackWorld world, String key) { - IrisEntity entity = engine(world).getData().getEntityLoader().load(key); + IrisEntity entity = SpawnResources.entity(engine(world).getData(), key); if (entity == null) { return Optional.empty(); } @@ -97,14 +97,14 @@ public final class EntitySpawning implements EntitySpawns { return Optional.empty(); } Engine engine = engine(world); - IrisMarker marker = engine.getData().getMarkerLoader().load(tag); + IrisMarker marker = SpawnResources.marker(engine.getData(), tag); if (marker == null) { return Optional.empty(); } List spawners = new ArrayList<>(); for (String key : marker.getSpawners()) { - if (engine.getData().getSpawnerLoader().load(key) == null) { + if (SpawnResources.spawner(engine.getData(), key) == null) { IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag); continue; } @@ -175,8 +175,8 @@ public final class EntitySpawning implements EntitySpawns { } private Optional planMarker(PackWorld world, Engine engine, Marker marker) { - IrisSpawner spawner = engine.getData().getSpawnerLoader().load(marker.spawner()); - IrisMarker irisMarker = engine.getData().getMarkerLoader().load(marker.marker()); + IrisSpawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner()); + IrisMarker irisMarker = SpawnResources.marker(engine.getData(), marker.marker()); if (spawner == null) { return Optional.empty(); } @@ -234,7 +234,7 @@ public final class EntitySpawning implements EntitySpawns { } private static KList shuffled(Engine engine, KList keys) { - return engine.getData().getSpawnerLoader().loadAll(keys).shuffleCopy(RNG.r); + return SpawnResources.spawners(engine.getData(), keys).shuffleCopy(RNG.r); } private static Stream spawnsOf(IrisSpawner spawner, boolean initial) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index d0663b44f..c941d7702 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -25,7 +25,7 @@ import com.volmit.service.EntitySpawns; import com.volmit.stage.StageGraph; /** - * Module {@code iris:spawn}: the spawners, entities and markers of the pack, and the entities that appear in the world + * Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), and the entities that appear in the world * over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for * something to spawn in a chunk or at a marker. */ @@ -43,6 +43,7 @@ public final class SpawnModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java new file mode 100644 index 000000000..b5c25a6b2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java @@ -0,0 +1,111 @@ +/* + * 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.spawn; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.entity.IrisEntity; +import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; +import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kinds of module {@code iris:spawn}, which keep the folders and files Iris packs have always used, and + * lookups by pack key for code that still names spawners, entities and markers by key. Every lookup goes through the + * pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot. + *

+ * 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 SpawnResources { + /** Spawners, in {@code spawners/}. */ + public static final ResourceKind SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", IrisSpawner.class); + /** Entities, in {@code entities/}. */ + public static final ResourceKind ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", IrisEntity.class); + /** Markers, in {@code markers/}. */ + public static final ResourceKind MARKERS = ResourceKind.of("iris:spawn/marker", "markers", IrisMarker.class); + + private SpawnResources() { + } + + /** Every resource kind of the spawn module. */ + public static List> kinds() { + return List.of(SPAWNERS, ENTITIES, MARKERS); + } + + public static IrisSpawner spawner(IrisData data, String key) { + return find(data, SPAWNERS, key); + } + + public static IrisEntity entity(IrisData data, String key) { + return find(data, ENTITIES, key); + } + + public static IrisMarker marker(IrisData data, String key) { + return find(data, MARKERS, key); + } + + /** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */ + public static KList spawners(IrisData data, List keys) { + KList spawners = new KList<>(); + for (String key : keys) { + IrisSpawner spawner = spawner(data, key); + if (spawner != null) { + spawners.add(spawner); + } + } + return spawners; + } + + /** The key of every entity of the pack, in key order. */ + public static List entityKeys(IrisData data) { + return keys(data, ENTITIES); + } + + /** The key of every spawner of the pack, in key order. */ + public static List spawnerKeys(IrisData data) { + return keys(data, SPAWNERS); + } + + /** The key of every marker of the pack, in key order. */ + public static List markerKeys(IrisData data) { + return keys(data, MARKERS); + } + + 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.key(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 data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); + } +} From 4735477918967b304ea130827b65789a71b1e49a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:26:05 +0200 Subject: [PATCH 040/139] README: iris:loot, iris:spawn and the new services of iris:objects; tree species by name --- README.md | 8 ++++++++ .../arcane/iris/engine/mantle/components/TreeGrowing.java | 8 +++----- .../iris/engine/object/placement/IrisObjectPlacement.java | 5 +++++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8de696f27..b51dcd8c5 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,14 @@ provides `ObjectsAt` (the objects a chunk would get, for the object search and s provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a world places, and their nearest start for the find commands). `iris:structure` also has a lifecycle hook that drops a world's structure index when the world stops, which includes every reload of the pack's structure files. +`iris:objects` also provides `SaplingGrowth` (`TreeGrowing`: the tree a sapling grows into, as placed blocks, and which +objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). +`iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to +them (`LootValidator`), and provides `Loot` (`LootGiving`: which tables a container draws from and the `ItemDrop`s a +table gives) and `BlockDrops` (`BlockDropping`). `iris:spawn` owns spawners, entities and markers (`SpawnResources`, +folders `spawners`, `entities`, `markers`) and provides `EntitySpawns` (`EntitySpawning`: what to spawn in a chunk or at +a marker, as `EntitySpec`s; `EntityResolution` makes the entity's random choices). Iris's Bukkit code creates the items +and entities from those values (`BukkitItemStacks`, `BukkitEntitySpawner`). `iris:decorant` keeps its per-world `Decorating` in the world's state store (`context.world().state(...)`); the other built-ins still reach the same store through `IrisChunk.state(...)` / `engine.getGeneration().state(...)`. diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 1bcfe3226..40dee1a6d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -41,7 +41,6 @@ import com.volmit.placement.PlacedBlock; import com.volmit.service.SaplingGrowth; import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; -import org.bukkit.TreeType; import java.util.ArrayList; import java.util.HashSet; @@ -100,19 +99,18 @@ public final class TreeGrowing implements SaplingGrowth { /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { - TreeType species = TreeType.valueOf(sapling.species()); KList placements = new KList<>(); boolean useAll = engine.getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); BlockPosition at = sapling.at(); - placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), species)); + placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), sapling.species())); if (useAll || placements.isEmpty()) { - placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), species)); + placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), sapling.species())); } return placements.isNotEmpty() ? placements.getRandom() : null; } - private static KList matching(KList objects, TreeType species) { + private static KList matching(KList objects, String species) { KList matches = new KList<>(); for (IrisObjectPlacement placement : objects) { if (placement.matches(SAPLING_SIZE, species)) { 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 index f63e0fa69..3b6559a38 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -272,6 +272,11 @@ public class IrisObjectPlacement { 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 size}. */ + public boolean matches(IrisTreeSize size, String species) { + return matches(size, TreeType.valueOf(species)); + } + public boolean matches(IrisTreeSize size, TreeType type) { for (IrisTree i : getTrees()) { if (i.matches(size, type)) { From 1f3e1c9abaffd502d77cfcfdb9ec163dd21a126c Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:31:08 +0200 Subject: [PATCH 041/139] Procedural object settings as module-owned IrisApi types: coral, crystal, formation, fungus, ruin and the tree profile classes; ResolvedProceduralPlacement bakes and places them --- .../objects/coral/Coral.java} | 251 ++++++++++----- .../objects/coral/CoralBranchAzimuth.java} | 6 +- .../objects/coral/CoralForm.java} | 6 +- .../objects/crystal/Crystal.java} | 246 +++++++++----- .../objects/crystal/CrystalDistribution.java} | 6 +- .../objects/crystal/CrystalSurface.java} | 6 +- .../objects/formation/Formation.java} | 303 +++++++++++++----- .../objects/formation/FormationForm.java} | 6 +- .../objects/formation/FormationProfile.java} | 6 +- .../objects/fungi/Fungus.java} | 281 ++++++++++------ .../objects/fungi/FungusCapShape.java} | 6 +- .../objects/ruin/Ruin.java} | 229 ++++++++----- .../objects/ruin/RuinDecorator.java} | 64 ++-- .../objects/ruin/RuinDecoratorTarget.java} | 6 +- .../objects/ruin/RuinForm.java} | 6 +- .../objects/tree/TreeAzimuthMode.java} | 6 +- .../objects/tree/TreeBranchProbability.java} | 6 +- .../objects/tree/TreeBranches.java} | 148 +++++++-- .../objects/tree/TreeCanopy.java} | 75 +++-- .../objects/tree/TreeDecorator.java} | 67 ++-- .../objects/tree/TreeDecoratorTarget.java} | 6 +- .../objects/tree/TreeFunction.java} | 6 +- .../objects/tree/TreeLayer.java} | 33 +- .../objects/tree/TreeLeafMode.java} | 6 +- .../objects/tree/TreeProfile.java} | 6 +- .../objects/tree/TreeRootStyle.java} | 6 +- .../objects/tree/TreeSecondaryLeaf.java} | 40 +-- .../objects/tree/TreeSubBranches.java} | 61 +++- .../iris/builtin/prepare/ObjectRotation.java | 60 ++++ .../iris/builtin/prepare/ObjectTranslate.java | 70 ++++ .../mantle/components/ObjectModule.java | 16 + .../procedural/IrisProceduralBlocks.java | 29 +- .../procedural/IrisProceduralObjects.java | 79 +++-- .../ResolvedProceduralPlacement.java | 158 +++++++++ .../procedural/coral/CoralGenerator.java | 88 ++--- .../procedural/coral/ResolvedCoral.java | 42 +++ .../crystal/CrystalBaseBuilder.java | 8 +- .../procedural/crystal/CrystalGenerator.java | 39 +-- .../procedural/crystal/CrystalGeometry.java | 5 +- .../crystal/CrystalShardBuilder.java | 34 +- .../procedural/crystal/ResolvedCrystal.java | 42 +++ .../formation/FormationBlockResolver.java | 26 +- .../formation/FormationGenerator.java | 14 +- .../formation/FormationProfiles.java | 13 +- .../formation/FormationShapeBuilder.java | 106 +++--- .../formation/ResolvedFormation.java | 48 +++ .../procedural/fungi/FungusCapBuilder.java | 34 +- .../procedural/fungi/FungusGenerator.java | 30 +- .../procedural/fungi/FungusShelfBuilder.java | 16 +- .../procedural/fungi/FungusStemBuilder.java | 16 +- .../procedural/fungi/ResolvedFungus.java | 74 +++++ .../object/procedural/ruin/ResolvedRuin.java | 42 +++ .../procedural/ruin/RuinDecoratorApplier.java | 12 +- .../object/procedural/ruin/RuinGenerator.java | 51 +-- .../procedural/tree/IrisProceduralTree.java | 27 +- .../procedural/tree/TreeBlockResolver.java | 24 +- .../procedural/tree/TreeCanopyBuilder.java | 88 ++--- .../procedural/tree/TreeDecoratorApplier.java | 58 ++-- .../object/procedural/tree/TreeFunctions.java | 52 +-- .../object/procedural/tree/TreeProfiles.java | 9 +- .../procedural/tree/TreeRootBuilder.java | 4 +- .../procedural/tree/TreeTrunkBuilder.java | 4 +- 62 files changed, 2309 insertions(+), 1003 deletions(-) rename src/main/java/art/arcane/iris/{engine/object/procedural/coral/IrisCoral.java => builtin/objects/coral/Coral.java} (64%) rename src/main/java/art/arcane/iris/{engine/object/procedural/coral/IrisCoralBranchAzimuth.java => builtin/objects/coral/CoralBranchAzimuth.java} (89%) rename src/main/java/art/arcane/iris/{engine/object/procedural/coral/IrisCoralForm.java => builtin/objects/coral/CoralForm.java} (93%) rename src/main/java/art/arcane/iris/{engine/object/procedural/crystal/IrisCrystal.java => builtin/objects/crystal/Crystal.java} (64%) rename src/main/java/art/arcane/iris/{engine/object/procedural/crystal/IrisCrystalDistribution.java => builtin/objects/crystal/CrystalDistribution.java} (89%) rename src/main/java/art/arcane/iris/{engine/object/procedural/crystal/IrisCrystalSurface.java => builtin/objects/crystal/CrystalSurface.java} (92%) rename src/main/java/art/arcane/iris/{engine/object/procedural/formation/IrisFormation.java => builtin/objects/formation/Formation.java} (64%) rename src/main/java/art/arcane/iris/{engine/object/procedural/formation/IrisFormationForm.java => builtin/objects/formation/FormationForm.java} (93%) rename src/main/java/art/arcane/iris/{engine/object/procedural/formation/IrisFormationProfile.java => builtin/objects/formation/FormationProfile.java} (91%) rename src/main/java/art/arcane/iris/{engine/object/procedural/fungi/IrisFungus.java => builtin/objects/fungi/Fungus.java} (62%) rename src/main/java/art/arcane/iris/{engine/object/procedural/fungi/IrisFungusCapShape.java => builtin/objects/fungi/FungusCapShape.java} (91%) rename src/main/java/art/arcane/iris/{engine/object/procedural/ruin/IrisRuin.java => builtin/objects/ruin/Ruin.java} (67%) rename src/main/java/art/arcane/iris/{engine/object/procedural/ruin/IrisRuinDecorator.java => builtin/objects/ruin/RuinDecorator.java} (63%) rename src/main/java/art/arcane/iris/{engine/object/procedural/ruin/IrisRuinDecoratorTarget.java => builtin/objects/ruin/RuinDecoratorTarget.java} (89%) rename src/main/java/art/arcane/iris/{engine/object/procedural/ruin/IrisRuinForm.java => builtin/objects/ruin/RuinForm.java} (93%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeAzimuthMode.java => builtin/objects/tree/TreeAzimuthMode.java} (92%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeBranchProbability.java => builtin/objects/tree/TreeBranchProbability.java} (92%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeBranches.java => builtin/objects/tree/TreeBranches.java} (57%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeCanopy.java => builtin/objects/tree/TreeCanopy.java} (60%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeDecorator.java => builtin/objects/tree/TreeDecorator.java} (57%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeDecoratorTarget.java => builtin/objects/tree/TreeDecoratorTarget.java} (92%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeFunction.java => builtin/objects/tree/TreeFunction.java} (92%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeLayer.java => builtin/objects/tree/TreeLayer.java} (65%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeLeafMode.java => builtin/objects/tree/TreeLeafMode.java} (91%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeProfile.java => builtin/objects/tree/TreeProfile.java} (93%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeRootStyle.java => builtin/objects/tree/TreeRootStyle.java} (89%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeSecondaryLeaf.java => builtin/objects/tree/TreeSecondaryLeaf.java} (58%) rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeSubBranches.java => builtin/objects/tree/TreeSubBranches.java} (64%) create mode 100644 src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java create mode 100644 src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java b/src/main/java/art/arcane/iris/builtin/objects/coral/Coral.java similarity index 64% rename from src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java rename to src/main/java/art/arcane/iris/builtin/objects/coral/Coral.java index dde80bf4b..832cd8b68 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoral.java +++ b/src/main/java/art/arcane/iris/builtin/objects/coral/Coral.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,44 +16,29 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.coral; +package art.arcane.iris.builtin.objects.coral; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.procedural.coral.CoralGenerator; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Optional; @Snippet("coral") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A single procedurally generated coral reef structure. Iris bakes a pool of deterministic variants from these settings and scatters them across the seafloor at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Mirrors the procedural tree system but tuned for underwater reefs: structural blocks are waterlogged so the coral stays alive, and placement defaults to anchoring on the terrain beneath the water surface.") -@Data -public class IrisCoral implements IrisProceduralPlacement { - private final transient AtomicCache> variantCache = new AtomicCache<>(); - +public final class Coral { @Desc("A human readable name used in logs and as the variant load key.") private String name = "coral"; @@ -78,7 +63,7 @@ public class IrisCoral implements IrisProceduralPlacement { private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; @Desc("Rotate this coral's placement.") - private IrisObjectRotation rotation = new IrisObjectRotation(); + private ObjectRotation rotation = new ObjectRotation(); @Desc("Limit the max or min height of placement.") private ObjectLimit clamp = new ObjectLimit(); @@ -90,7 +75,7 @@ public class IrisCoral implements IrisProceduralPlacement { private boolean underwater = true; @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the seafloor.") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + private ObjectTranslate translate = new ObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") private StiltSettings stiltSettings; @@ -102,22 +87,22 @@ public class IrisCoral implements IrisProceduralPlacement { private boolean waterlogged = true; @Desc("The overall silhouette this coral grows into (branching, fan, brain, pillar, tendril). Each form runs a different generation routine.") - private IrisCoralForm form = IrisCoralForm.BRANCHING; + private CoralForm form = CoralForm.BRANCHING; @Required @Desc("The structural coral block (the living wood of the reef), e.g. minecraft:tube_coral_block. Ignored when blockPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = "minecraft:tube_coral_block"; @Desc("A noise-driven palette for the structural coral block. When set this overrides the single block, letting the reef mix tube/brain/bubble/fire/horn coral_block tones across its body.") - private IrisMaterialPalette blockPalette = null; + private PaletteSpec blockPalette; @Desc("Optional tip block placed at branch tips and at the very top of the structure, e.g. coral fans or minecraft:sea_pickle. Ignored when tipPalette is set. Null disables tips.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String tipBlock = null; @Desc("A noise-driven palette for the tip block. When set this overrides the single tipBlock, letting tips mix fan / pickle decorations.") - private IrisMaterialPalette tipPalette = null; + private PaletteSpec tipPalette; @MinNumber(0) @MaxNumber(1) @@ -156,7 +141,7 @@ public class IrisCoral implements IrisProceduralPlacement { private double branchElevation = 55; @Desc("BRANCHING only: how the arms are distributed around the stalk by azimuth.") - private IrisCoralBranchAzimuth branchAzimuth = IrisCoralBranchAzimuth.GOLDEN_ANGLE; + private CoralBranchAzimuth branchAzimuth = CoralBranchAzimuth.GOLDEN_ANGLE; @Desc("BRANCHING only: if true, each arm splits once into a small fan of sub-arms for a bushier reef.") private boolean subBranches = true; @@ -201,49 +186,159 @@ public class IrisCoral implements IrisProceduralPlacement { @Desc("TENDRIL only: how many thin wavy stalks rise from the base.") private int tendrilCount = 4; - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> { - KList baked = new KList<>(); - int count = Math.max(1, variants); - - for (int i = 0; i < count; i++) { - IrisObject object = CoralGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); - if (object == null || object.getBlocks().isEmpty()) { - continue; - } - object.setLoadKey("procedural/" + name + "#" + i); - object.setLoader(data); - baked.add(object); - } - - return baked; - }); + public Coral() { } - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); + public String name() { + return name; } - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(mode); - placement.setRotation(rotation); - placement.setClamp(clamp); - placement.setCarvingSupport(carvingSupport); - placement.setUnderwater(underwater); - placement.setTranslate(translate); - placement.setStiltSettings(stiltSettings); - placement.setVacuumSettings(vacuumSettings); - placement.setChance(chance); - placement.setDensity(density); - return placement; + public double chance() { + return chance; } - public boolean isPlausible() { - return false; + public int density() { + return density; + } + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public ObjectPlaceMode mode() { + return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public CarvingMode carvingSupport() { + return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; + } + + public boolean underwater() { + return underwater; + } + + public ObjectTranslate translate() { + return translate; + } + + /** Empty where the pack sets none. */ + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + /** Empty where the pack sets none. */ + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public boolean waterlogged() { + return waterlogged; + } + + public CoralForm form() { + return form == null ? CoralForm.BRANCHING : form; + } + + public String block() { + return block; + } + + /** Empty where the pack sets none. */ + public Optional blockPalette() { + return Optional.ofNullable(blockPalette); + } + + /** Empty where the pack sets none. */ + public Optional tipBlock() { + return Optional.ofNullable(tipBlock); + } + + /** Empty where the pack sets none. */ + public Optional tipPalette() { + return Optional.ofNullable(tipPalette); + } + + public double tipChance() { + return tipChance; + } + + public int heightMin() { + return heightMin; + } + + public int heightMax() { + return heightMax; + } + + public double spread() { + return spread; + } + + public double sway() { + return sway; + } + + public int branchCount() { + return branchCount; + } + + public double branchLength() { + return branchLength; + } + + public double branchElevation() { + return branchElevation; + } + + public CoralBranchAzimuth branchAzimuth() { + return branchAzimuth == null ? CoralBranchAzimuth.GOLDEN_ANGLE : branchAzimuth; + } + + public boolean subBranches() { + return subBranches; + } + + public int subBranchCount() { + return subBranchCount; + } + + public double subBranchScale() { + return subBranchScale; + } + + public int tipClusterRadius() { + return tipClusterRadius; + } + + public int brainRadius() { + return brainRadius; + } + + public double brainRoughness() { + return brainRoughness; + } + + public int pillarRadius() { + return pillarRadius; + } + + public int fanWidth() { + return fanWidth; + } + + public int tendrilCount() { + return tendrilCount; } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java b/src/main/java/art/arcane/iris/builtin/objects/coral/CoralBranchAzimuth.java similarity index 89% rename from src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java rename to src/main/java/art/arcane/iris/builtin/objects/coral/CoralBranchAzimuth.java index 657457102..bd3712ab1 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralBranchAzimuth.java +++ b/src/main/java/art/arcane/iris/builtin/objects/coral/CoralBranchAzimuth.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.coral; +package art.arcane.iris.builtin.objects.coral; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("How the arms of a BRANCHING coral are distributed around the central stalk by compass azimuth.") -public enum IrisCoralBranchAzimuth { +public enum CoralBranchAzimuth { @Desc("Distribute arms by the golden angle (about 137.5 degrees per arm) for a natural phyllotactic spiral where no two arms overlap.") GOLDEN_ANGLE, diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java b/src/main/java/art/arcane/iris/builtin/objects/coral/CoralForm.java similarity index 93% rename from src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java rename to src/main/java/art/arcane/iris/builtin/objects/coral/CoralForm.java index 2d4f00038..236b3c1e0 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/IrisCoralForm.java +++ b/src/main/java/art/arcane/iris/builtin/objects/coral/CoralForm.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.coral; +package art.arcane.iris.builtin.objects.coral; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The overall silhouette a procedural coral grows into. Each form drives a completely different generation routine in the coral generator, from tree-like branching arms to rounded brain blobs and thin wavy tendrils.") -public enum IrisCoralForm { +public enum CoralForm { @Desc("A tree-like coral built from a stout central stalk that sprouts several upward-leaning arms (distributed by golden angle or randomly), each optionally splitting once into sub-arms, with small coral tip clusters (fans / sea pickles) at the ends. The most structurally complex form and the closest analogue to a procedural tree.") BRANCHING, diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java b/src/main/java/art/arcane/iris/builtin/objects/crystal/Crystal.java similarity index 64% rename from src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java rename to src/main/java/art/arcane/iris/builtin/objects/crystal/Crystal.java index 6de4cedff..a68427901 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystal.java +++ b/src/main/java/art/arcane/iris/builtin/objects/crystal/Crystal.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,44 +16,29 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.crystal; +package art.arcane.iris.builtin.objects.crystal; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.procedural.crystal.CrystalGenerator; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Optional; @Snippet("crystal") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A single procedurally generated crystal cluster: a budding base blob with faceted, tapered shards radiating from it (geode / amethyst-style). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Built for caves.") -@Data -public class IrisCrystal implements IrisProceduralPlacement { - private final transient AtomicCache> variantCache = new AtomicCache<>(); - +public final class Crystal { @Desc("A human readable name used in logs and as the variant load key.") private String name = "crystal"; @@ -78,7 +63,7 @@ public class IrisCrystal implements IrisProceduralPlacement { private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; @Desc("Rotate this crystal cluster's placement.") - private IrisObjectRotation rotation = new IrisObjectRotation(); + private ObjectRotation rotation = new ObjectRotation(); @Desc("Limit the max or min height of placement.") private ObjectLimit clamp = new ObjectLimit(); @@ -90,7 +75,7 @@ public class IrisCrystal implements IrisProceduralPlacement { private boolean underwater = false; @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + private ObjectTranslate translate = new ObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") private StiltSettings stiltSettings; @@ -99,22 +84,22 @@ public class IrisCrystal implements IrisProceduralPlacement { private VacuumSettings vacuumSettings; @Desc("The surface this crystal grows from (FLOOR shards up, CEILING shards down, WALL shards outward). This orients the baked geometry only.") - private IrisCrystalSurface growthSurface = IrisCrystalSurface.FLOOR; + private CrystalSurface growthSurface = CrystalSurface.FLOOR; @Required @Desc("The primary crystal shard block, e.g. minecraft:amethyst_block. Ignored when blockPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = "minecraft:amethyst_block"; @Desc("A noise-driven palette for the crystal shards (a prismatic mix, e.g. amethyst_block, calcite, tinted_glass). When set this overrides the single block, letting the shards mix blocks by noise. Palette wins.") - private IrisMaterialPalette blockPalette = null; + private PaletteSpec blockPalette; @Desc("Optional block placed at the very tip of each shard for a different colored or sparkling point (e.g. minecraft:amethyst_cluster or glowstone). Ignored when tipPalette is set. If unset and glow is true, a light-emitting block is sprinkled among the tips instead.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String tipBlock = null; @Desc("A noise-driven palette for the shard tips. When set this overrides the single tipBlock. Palette wins.") - private IrisMaterialPalette tipPalette = null; + private PaletteSpec tipPalette; @MinNumber(0) @MaxNumber(1) @@ -125,15 +110,15 @@ public class IrisCrystal implements IrisProceduralPlacement { private boolean glow = false; @Desc("The light-emitting block sprinkled among the tips when glow is true and no tip block is configured.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String glowBlock = "minecraft:glowstone"; @Desc("Optional block for the budding base blob the shards grow from, e.g. minecraft:budding_amethyst or calcite. Ignored when basePalette is set. If unset, the base is built from the primary shard block.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String baseBlock = "minecraft:budding_amethyst"; @Desc("A noise-driven palette for the budding base blob. When set this overrides the single baseBlock. Palette wins.") - private IrisMaterialPalette basePalette = null; + private PaletteSpec basePalette; @MinNumber(0) @Desc("Radius in blocks of the budding base blob the shards radiate from. 0 places no base blob (shards spring from a single point).") @@ -175,56 +160,155 @@ public class IrisCrystal implements IrisProceduralPlacement { private double spreadAngle = 45; @Desc("How the shard azimuths are distributed around the normal (RANDOM for a chaotic clump, GOLDEN_ANGLE for an evenly spaced rosette).") - private IrisCrystalDistribution distribution = IrisCrystalDistribution.GOLDEN_ANGLE; + private CrystalDistribution distribution = CrystalDistribution.GOLDEN_ANGLE; @MinNumber(0) @MaxNumber(1) @Desc("Per-shard angular randomness (0-1) added on top of the chosen distribution so the cluster never looks mechanically regular. 0 is perfectly distributed; 1 is heavily jittered.") private double jitter = 0.25; - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> { - KList baked = new KList<>(); - int count = Math.max(1, variants); - - for (int i = 0; i < count; i++) { - IrisObject object = CrystalGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); - if (object == null || object.getBlocks().isEmpty()) { - continue; - } - object.setLoadKey("procedural/" + name + "#" + i); - object.setLoader(data); - baked.add(object); - } - - return baked; - }); + public Crystal() { } - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); + public String name() { + return name; } - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(mode); - placement.setRotation(rotation); - placement.setClamp(clamp); - placement.setCarvingSupport(carvingSupport); - placement.setUnderwater(underwater); - placement.setTranslate(translate); - placement.setStiltSettings(stiltSettings); - placement.setVacuumSettings(vacuumSettings); - placement.setChance(chance); - placement.setDensity(density); - return placement; + public double chance() { + return chance; } - public boolean isPlausible() { - return false; + public int density() { + return density; + } + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public ObjectPlaceMode mode() { + return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public CarvingMode carvingSupport() { + return carvingSupport == null ? CarvingMode.CARVING_ONLY : carvingSupport; + } + + public boolean underwater() { + return underwater; + } + + public ObjectTranslate translate() { + return translate; + } + + /** Empty where the pack sets none. */ + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + /** Empty where the pack sets none. */ + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public CrystalSurface growthSurface() { + return growthSurface == null ? CrystalSurface.FLOOR : growthSurface; + } + + public String block() { + return block; + } + + /** Empty where the pack sets none. */ + public Optional blockPalette() { + return Optional.ofNullable(blockPalette); + } + + /** Empty where the pack sets none. */ + public Optional tipBlock() { + return Optional.ofNullable(tipBlock); + } + + /** Empty where the pack sets none. */ + public Optional tipPalette() { + return Optional.ofNullable(tipPalette); + } + + public double tipChance() { + return tipChance; + } + + public boolean glow() { + return glow; + } + + public String glowBlock() { + return glowBlock; + } + + public String baseBlock() { + return baseBlock; + } + + /** Empty where the pack sets none. */ + public Optional basePalette() { + return Optional.ofNullable(basePalette); + } + + public double baseRadius() { + return baseRadius; + } + + public double baseNoise() { + return baseNoise; + } + + public int shardCountMin() { + return shardCountMin; + } + + public int shardCountMax() { + return shardCountMax; + } + + public int shardLengthMin() { + return shardLengthMin; + } + + public int shardLengthMax() { + return shardLengthMax; + } + + public double shardBaseRadius() { + return shardBaseRadius; + } + + public double shardTaper() { + return shardTaper; + } + + public double spreadAngle() { + return spreadAngle; + } + + public CrystalDistribution distribution() { + return distribution == null ? CrystalDistribution.GOLDEN_ANGLE : distribution; + } + + public double jitter() { + return jitter; } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java b/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalDistribution.java similarity index 89% rename from src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java rename to src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalDistribution.java index 52eadb53e..d6882038a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalDistribution.java +++ b/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalDistribution.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.crystal; +package art.arcane.iris.builtin.objects.crystal; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("How the shards of a crystal cluster are angularly distributed around the surface normal.") -public enum IrisCrystalDistribution { +public enum CrystalDistribution { @Desc("Each shard gets a uniformly random azimuth around the normal. Produces a chaotic, naturally clumped cluster.") RANDOM, diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java b/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalSurface.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java rename to src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalSurface.java index ddabd7879..19aa568ac 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/IrisCrystalSurface.java +++ b/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalSurface.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.crystal; +package art.arcane.iris.builtin.objects.crystal; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The surface a crystal cluster grows from. This only orients the baked geometry (which way the shards point); placement of the object into a cave is handled by the placement system, not here.") -public enum IrisCrystalSurface { +public enum CrystalSurface { @Desc("Grows from a cave floor. The budding base sits at the bottom and the shards point upward, fanning within the spread cone around the up axis. Built with positive py so the cluster grows up from the base layer.") FLOOR, diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java b/src/main/java/art/arcane/iris/builtin/objects/formation/Formation.java similarity index 64% rename from src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java rename to src/main/java/art/arcane/iris/builtin/objects/formation/Formation.java index eaf4a1478..2fac99587 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormation.java +++ b/src/main/java/art/arcane/iris/builtin/objects/formation/Formation.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,44 +16,29 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.formation; +package art.arcane.iris.builtin.objects.formation; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.procedural.formation.FormationGenerator; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Optional; @Snippet("formation") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A single procedurally generated natural formation, including rock landmarks and magical glacial silhouettes. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") -@Data -public class IrisFormation implements IrisProceduralPlacement { - private final transient AtomicCache> variantCache = new AtomicCache<>(); - +public final class Formation { @Desc("A human readable name used in logs and as the variant load key.") private String name = "formation"; @@ -78,7 +63,7 @@ public class IrisFormation implements IrisProceduralPlacement { private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; @Desc("Rotate this formation's placement.") - private IrisObjectRotation rotation = new IrisObjectRotation(); + private ObjectRotation rotation = new ObjectRotation(); @Desc("Limit the max or min height of placement.") private ObjectLimit clamp = new ObjectLimit(); @@ -95,7 +80,7 @@ public class IrisFormation implements IrisProceduralPlacement { private boolean underwater = false; @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + private ObjectTranslate translate = new ObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") private StiltSettings stiltSettings; @@ -104,25 +89,25 @@ public class IrisFormation implements IrisProceduralPlacement { private VacuumSettings vacuumSettings; @Desc("The overall silhouette of the formation. Drives which sculpting routine the generator uses.") - private IrisFormationForm form = IrisFormationForm.SPIRE; + private FormationForm form = FormationForm.SPIRE; @Required @Desc("The main rock block, e.g. minecraft:stone. Ignored when blockPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = "minecraft:stone"; @Desc("A noise-driven palette for the main rock body. When set this overrides the single block, letting the body mix blocks by noise.") - private IrisMaterialPalette blockPalette = null; + private PaletteSpec blockPalette; @Desc("Optional caprock block placed on the top crown of the formation (and the wide overhanging cap for HOODOO). Ignored when capPalette is set. When null and capPalette is unset, the formation uses its main rock everywhere.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String capBlock = null; @Desc("A noise-driven palette for the caprock. When set this overrides the single capBlock.") - private IrisMaterialPalette capPalette = null; + private PaletteSpec capPalette; @Desc("Optional palette of strata (horizontal colored bands) blended into the rock body by y level. When set, every strataThickness blocks of height switches to the next strata block, producing the signature banded look. Falls back to the main block where unset.") - private IrisMaterialPalette strataPalette = null; + private PaletteSpec strataPalette; @MinNumber(1) @MaxNumber(32) @@ -150,7 +135,7 @@ public class IrisFormation implements IrisProceduralPlacement { private int topWidth = 0; @Desc("The function used to shape the formation radius over its height.") - private IrisFormationProfile profile = IrisFormationProfile.TAPER; + private FormationProfile profile = FormationProfile.TAPER; @MinNumber(0) @MaxNumber(1) @@ -255,50 +240,208 @@ public class IrisFormation implements IrisProceduralPlacement { @Desc("How many blocks the tip of an OVERHANG curls downward.") private int overhangDrop = 3; - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> { - KList baked = new KList<>(); - int count = Math.max(1, variants); - - for (int i = 0; i < count; i++) { - IrisObject object = FormationGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); - if (object == null || object.getBlocks().isEmpty()) { - continue; - } - object.setLoadKey("procedural/" + name + "#" + i); - object.setLoader(data); - baked.add(object); - } - - return baked; - }); + public Formation() { } - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); + public String name() { + return name; } - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(mode); - placement.setRotation(rotation); - placement.setClamp(clamp); - placement.setCarvingSupport(carvingSupport); - placement.setSurfaceSupportBuffer(surfaceSupportBuffer); - placement.setUnderwater(underwater); - placement.setTranslate(translate); - placement.setStiltSettings(stiltSettings); - placement.setVacuumSettings(vacuumSettings); - placement.setChance(chance); - placement.setDensity(density); - return placement; + public double chance() { + return chance; } - public boolean isPlausible() { - return false; + public int density() { + return density; + } + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public ObjectPlaceMode mode() { + return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public CarvingMode carvingSupport() { + return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; + } + + public int surfaceSupportBuffer() { + return surfaceSupportBuffer; + } + + public boolean underwater() { + return underwater; + } + + public ObjectTranslate translate() { + return translate; + } + + /** Empty where the pack sets none. */ + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + /** Empty where the pack sets none. */ + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public FormationForm form() { + return form == null ? FormationForm.SPIRE : form; + } + + public String block() { + return block; + } + + /** Empty where the pack sets none. */ + public Optional blockPalette() { + return Optional.ofNullable(blockPalette); + } + + /** Empty where the pack sets none. */ + public Optional capBlock() { + return Optional.ofNullable(capBlock); + } + + /** Empty where the pack sets none. */ + public Optional capPalette() { + return Optional.ofNullable(capPalette); + } + + /** Empty where the pack sets none. */ + public Optional strataPalette() { + return Optional.ofNullable(strataPalette); + } + + public int strataThickness() { + return strataThickness; + } + + public int heightMin() { + return heightMin; + } + + public int heightMax() { + return heightMax; + } + + public int baseWidthMin() { + return baseWidthMin; + } + + public int baseWidthMax() { + return baseWidthMax; + } + + public int topWidth() { + return topWidth; + } + + public FormationProfile profile() { + return profile == null ? FormationProfile.TAPER : profile; + } + + public double profileWaist() { + return profileWaist; + } + + public double profileWaistFloor() { + return profileWaistFloor; + } + + public double lean() { + return lean; + } + + public double leanAzimuth() { + return leanAzimuth; + } + + public double roughness() { + return roughness; + } + + public double jitter() { + return jitter; + } + + public int hoodooCapRadius() { + return hoodooCapRadius; + } + + public int hoodooCapHeight() { + return hoodooCapHeight; + } + + public int archSpan() { + return archSpan; + } + + public int archThickness() { + return archThickness; + } + + public double archAsymmetry() { + return archAsymmetry; + } + + public int basaltColumns() { + return basaltColumns; + } + + public int basaltColumnRadius() { + return basaltColumnRadius; + } + + public double basaltHeightVariance() { + return basaltHeightVariance; + } + + public int icebergPeaks() { + return icebergPeaks; + } + + public int fractureCount() { + return fractureCount; + } + + public int fractureSeparation() { + return fractureSeparation; + } + + public double spiralTurns() { + return spiralTurns; + } + + public int spiralRadius() { + return spiralRadius; + } + + public int spiralThickness() { + return spiralThickness; + } + + public int overhangReach() { + return overhangReach; + } + + public int overhangDrop() { + return overhangDrop; } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java b/src/main/java/art/arcane/iris/builtin/objects/formation/FormationForm.java similarity index 93% rename from src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java rename to src/main/java/art/arcane/iris/builtin/objects/formation/FormationForm.java index 635066991..d6a830643 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationForm.java +++ b/src/main/java/art/arcane/iris/builtin/objects/formation/FormationForm.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.formation; +package art.arcane.iris.builtin.objects.formation; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The overall silhouette of a procedural natural formation. Each form drives a distinct sculpting routine in the formation generator.") -public enum IrisFormationForm { +public enum FormationForm { @Desc("A tall, slender needle of rock that tapers smoothly to a point at the top (a sharp pinnacle or stone spire).") SPIRE, @Desc("A column with a pinched, eroded waist and a wide overhanging caprock balanced on top (the classic desert hoodoo / mushroom rock).") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java b/src/main/java/art/arcane/iris/builtin/objects/formation/FormationProfile.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java rename to src/main/java/art/arcane/iris/builtin/objects/formation/FormationProfile.java index de0d1ae40..11d7b2f6b 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/IrisFormationProfile.java +++ b/src/main/java/art/arcane/iris/builtin/objects/formation/FormationProfile.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.formation; +package art.arcane.iris.builtin.objects.formation; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("A width-shaping function evaluated over normalized height (0 at the base, 1 at the top). Controls how the formation radius scales between baseWidth at the bottom and topWidth at the top.") -public enum IrisFormationProfile { +public enum FormationProfile { @Desc("Same radius at every height (a straight cylinder of constant baseWidth).") CONSTANT, @Desc("Radius ramps straight from baseWidth at the bottom to topWidth at the top.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java b/src/main/java/art/arcane/iris/builtin/objects/fungi/Fungus.java similarity index 62% rename from src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java rename to src/main/java/art/arcane/iris/builtin/objects/fungi/Fungus.java index f22fad06e..69f19fcaa 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungus.java +++ b/src/main/java/art/arcane/iris/builtin/objects/fungi/Fungus.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,44 +16,29 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.fungi; +package art.arcane.iris.builtin.objects.fungi; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.procedural.fungi.FungusGenerator; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Optional; @Snippet("fungus") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A single procedurally generated fungus (giant mushroom or shelf fungus). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. The fungus is built as a stem column with a cap dome grown on top, mirroring the trunk-and-canopy model used by procedural trees.") -@Data -public class IrisFungus implements IrisProceduralPlacement { - private final transient AtomicCache> variantCache = new AtomicCache<>(); - +public final class Fungus { @Desc("A human readable name used in logs and as the variant load key.") private String name = "fungus"; @@ -78,7 +63,7 @@ public class IrisFungus implements IrisProceduralPlacement { private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; @Desc("Rotate this fungus's placement.") - private IrisObjectRotation rotation = new IrisObjectRotation(); + private ObjectRotation rotation = new ObjectRotation(); @Desc("Limit the max or min height of placement.") private ObjectLimit clamp = new ObjectLimit(); @@ -90,7 +75,7 @@ public class IrisFungus implements IrisProceduralPlacement { private boolean underwater = false; @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + private ObjectTranslate translate = new ObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") private StiltSettings stiltSettings; @@ -100,19 +85,19 @@ public class IrisFungus implements IrisProceduralPlacement { @Required @Desc("The stem block, e.g. minecraft:mushroom_stem. Ignored when stemPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String stem = "minecraft:mushroom_stem"; @Desc("A noise-driven palette for the stem. When set this overrides the single stem block, letting the stem mix blocks by noise.") - private IrisMaterialPalette stemPalette = null; + private PaletteSpec stemPalette; @Required @Desc("The cap block, e.g. minecraft:red_mushroom_block. Ignored when capPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String cap = "minecraft:red_mushroom_block"; @Desc("A noise-driven palette for the cap. When set this overrides the single cap block, letting the cap mix blocks by noise.") - private IrisMaterialPalette capPalette = null; + private PaletteSpec capPalette; @MinNumber(1) @Desc("Minimum total stem height in blocks. Variants spread between this and stemHeightMax.") @@ -142,7 +127,7 @@ public class IrisFungus implements IrisProceduralPlacement { private double stemWavePeriods = 1; @Desc("The silhouette of the cap (dome, flat umbrella, funnel, cone, or wide shallow slab).") - private IrisFungusCapShape capShape = IrisFungusCapShape.DOME; + private FungusCapShape capShape = FungusCapShape.DOME; @MinNumber(1) @Desc("Minimum cap radius in blocks (measured from the cap center to its rim).") @@ -171,11 +156,11 @@ public class IrisFungus implements IrisProceduralPlacement { private double capOverhang = 2; @Desc("Optional block forming the gill layer on the underside of the cap (gills or a glow layer), e.g. minecraft:brown_mushroom_block or minecraft:shroomlight. Ignored when gillPalette is set or left null.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String gillBlock = null; @Desc("A noise-driven palette for the underside gill layer. When set this overrides the single gillBlock.") - private IrisMaterialPalette gillPalette = null; + private PaletteSpec gillPalette; @MinNumber(0) @MaxNumber(1) @@ -183,11 +168,11 @@ public class IrisFungus implements IrisProceduralPlacement { private double gillChance = 0.85; @Desc("Optional block speckled across the top of the cap by noise (white toadstool dots, warts, glowing spots), e.g. minecraft:bone_block or minecraft:white_concrete. Ignored when spotPalette is set or left null.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String spotBlock = null; @Desc("A noise-driven palette for the cap top spots. When set this overrides the single spotBlock.") - private IrisMaterialPalette spotPalette = null; + private PaletteSpec spotPalette; @MinNumber(0) @MaxNumber(1) @@ -201,62 +186,170 @@ public class IrisFungus implements IrisProceduralPlacement { @Desc("The radius in blocks of the sideways fan when shelf is true.") private int shelfRadius = 3; - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> { - KList baked = new KList<>(); - int count = Math.max(1, variants); - int lo = Math.min(stemHeightMin, stemHeightMax); - int hi = Math.max(stemHeightMin, stemHeightMax); - RNG heightRng = new RNG(seed); - - for (int i = 0; i < count; i++) { - int height; - if (count == 1 || lo == hi) { - height = heightRng.i(lo, hi + 1); - } else { - double step = (hi - lo) / (double) (count - 1); - double base = lo + step * i; - double jitter = heightRng.d(-step * 0.3, step * 0.3); - height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); - } - - IrisObject object = FungusGenerator.generate(this, Math.max(1, height), new RNG(seed + (i * 7919L)), data); - if (object == null || object.getBlocks().isEmpty()) { - continue; - } - object.setLoadKey("procedural/" + name + "#" + i); - object.setLoader(data); - baked.add(object); - } - - return baked; - }); + public Fungus() { } - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); + public String name() { + return name; } - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(mode); - placement.setRotation(rotation); - placement.setClamp(clamp); - placement.setCarvingSupport(carvingSupport); - placement.setUnderwater(underwater); - placement.setTranslate(translate); - placement.setStiltSettings(stiltSettings); - placement.setVacuumSettings(vacuumSettings); - placement.setChance(chance); - placement.setDensity(density); - return placement; + public double chance() { + return chance; } - public boolean isPlausible() { - return false; + public int density() { + return density; + } + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public ObjectPlaceMode mode() { + return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public CarvingMode carvingSupport() { + return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; + } + + public boolean underwater() { + return underwater; + } + + public ObjectTranslate translate() { + return translate; + } + + /** Empty where the pack sets none. */ + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + /** Empty where the pack sets none. */ + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public String stem() { + return stem; + } + + /** Empty where the pack sets none. */ + public Optional stemPalette() { + return Optional.ofNullable(stemPalette); + } + + public String cap() { + return cap; + } + + /** Empty where the pack sets none. */ + public Optional capPalette() { + return Optional.ofNullable(capPalette); + } + + public int stemHeightMin() { + return stemHeightMin; + } + + public int stemHeightMax() { + return stemHeightMax; + } + + public int stemWidth() { + return stemWidth; + } + + public double stemCurve() { + return stemCurve; + } + + public double stemLeanAzimuth() { + return stemLeanAzimuth; + } + + public double stemWaveAmplitude() { + return stemWaveAmplitude; + } + + public double stemWavePeriods() { + return stemWavePeriods; + } + + public FungusCapShape capShape() { + return capShape == null ? FungusCapShape.DOME : capShape; + } + + public int capRadiusMin() { + return capRadiusMin; + } + + public int capRadiusMax() { + return capRadiusMax; + } + + public int capThickness() { + return capThickness; + } + + public double capSquish() { + return capSquish; + } + + public double capDroop() { + return capDroop; + } + + public double capOverhang() { + return capOverhang; + } + + /** Empty where the pack sets none. */ + public Optional gillBlock() { + return Optional.ofNullable(gillBlock); + } + + /** Empty where the pack sets none. */ + public Optional gillPalette() { + return Optional.ofNullable(gillPalette); + } + + public double gillChance() { + return gillChance; + } + + /** Empty where the pack sets none. */ + public Optional spotBlock() { + return Optional.ofNullable(spotBlock); + } + + /** Empty where the pack sets none. */ + public Optional spotPalette() { + return Optional.ofNullable(spotPalette); + } + + public double spotChance() { + return spotChance; + } + + public boolean shelf() { + return shelf; + } + + public int shelfRadius() { + return shelfRadius; } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java b/src/main/java/art/arcane/iris/builtin/objects/fungi/FungusCapShape.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java rename to src/main/java/art/arcane/iris/builtin/objects/fungi/FungusCapShape.java index 449532565..6184c4afc 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/IrisFungusCapShape.java +++ b/src/main/java/art/arcane/iris/builtin/objects/fungi/FungusCapShape.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.fungi; +package art.arcane.iris.builtin.objects.fungi; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The silhouette of the mushroom cap. Each shape drives how the cap radius and thickness vary from its apex down to the rim, giving the fungus a distinct profile.") -public enum IrisFungusCapShape { +public enum FungusCapShape { @Desc("A rounded hemisphere cap that bulges up and curls slightly under at the rim, the classic red toadstool dome.") DOME, @Desc("A wide, nearly flat umbrella that holds its full radius almost to the edge before dropping, the brown-mushroom plate look.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java b/src/main/java/art/arcane/iris/builtin/objects/ruin/Ruin.java similarity index 67% rename from src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java rename to src/main/java/art/arcane/iris/builtin/objects/ruin/Ruin.java index c092881a5..2774af004 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuin.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ruin/Ruin.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,46 +16,32 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.ruin; +package art.arcane.iris.builtin.objects.ruin; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.RegistryListBlockType; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.procedural.ruin.RuinGenerator; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; @Snippet("ruin") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A single procedurally generated ruin: a crumbling man-made structure (pillar, wall, arch, foundation slab, or rubble pile). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Weathering swaps blocks for mossy or cracked variants by noise, erosion deletes blocks so the shape reads as collapsed, and a buried fraction sinks the ruin into the terrain.") -@Data -public class IrisRuin implements IrisProceduralPlacement { - private final transient AtomicCache> variantCache = new AtomicCache<>(); - +public final class Ruin { @Desc("A human readable name used in logs and as the variant load key (procedural/#).") private String name = "ruin"; @@ -80,7 +66,7 @@ public class IrisRuin implements IrisProceduralPlacement { private ObjectPlaceMode mode = ObjectPlaceMode.MIN_HEIGHT; @Desc("Rotate this ruin's placement so variants do not all face the same way.") - private IrisObjectRotation rotation = new IrisObjectRotation(); + private ObjectRotation rotation = new ObjectRotation(); @Desc("Limit the max or min terrain height at which this ruin may place.") private ObjectLimit clamp = new ObjectLimit(); @@ -92,7 +78,7 @@ public class IrisRuin implements IrisProceduralPlacement { private boolean underwater = false; @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + private ObjectTranslate translate = new ObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") private StiltSettings stiltSettings; @@ -102,14 +88,14 @@ public class IrisRuin implements IrisProceduralPlacement { @Required @Desc("The primary structural block, e.g. minecraft:cobblestone or minecraft:stone_bricks. Ignored when blockPalette is set. This is the bulk material of the ruin before weathering swaps some of it out.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = "minecraft:cobblestone"; @Desc("A noise-driven palette for the primary block. When set this overrides the single block, letting the structure mix materials by noise. Palette wins over the block string via IrisProceduralBlocks.resolve.") - private IrisMaterialPalette blockPalette = null; + private PaletteSpec blockPalette; @Desc("The overall silhouette of the ruin: PILLAR (broken column), WALL (gapped segment), ARCH (two legs plus a curved span), FLOOR_SLAB (foundation patch), or RUBBLE (low scattered pile).") - private IrisRuinForm form = IrisRuinForm.PILLAR; + private RuinForm form = RuinForm.PILLAR; @MinNumber(1) @Desc("Minimum structure height in blocks (PILLAR/WALL/ARCH height, slab thickness for FLOOR_SLAB, mound height for RUBBLE). Variants interpolate between this and heightMax.") @@ -136,10 +122,10 @@ public class IrisRuin implements IrisProceduralPlacement { private int lengthMax = 7; @Desc("A palette of weathered variants (mossy/cracked block ids) blended over the structure by noise. When set this drives weathering; otherwise weatheredBlock is used.") - private IrisMaterialPalette weatheringPalette = null; + private PaletteSpec weatheringPalette; @Desc("A single weathered block id used when weatheringPalette is not set, e.g. minecraft:mossy_cobblestone. Applied to a noise-selected fraction of the structure, biased toward the lower rows.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String weatheredBlock = "minecraft:mossy_cobblestone"; @MinNumber(0) @@ -167,53 +153,134 @@ public class IrisRuin implements IrisProceduralPlacement { @Desc("How far the structure extends below the surface as a fraction of its height (0 sits fully on top, 1 sinks it a full height into the ground). The buried rows live at negative y so the ruin reads as settled and partly swallowed by the terrain.") private double buriedFraction = 0.2; - @ArrayType(min = 1, type = IrisRuinDecorator.class) + @MinItems(1) @Desc("Accent decorators applied after the ruin is built and eroded (moss carpets and lanterns on broken tops, vines and lichen on the faces, rubble and growth scattered around the base).") - private KList accents = new KList<>(); + private List accents = List.of(); - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> { - KList baked = new KList<>(); - int count = Math.max(1, variants); - - for (int i = 0; i < count; i++) { - IrisObject object = RuinGenerator.generate(this, i, new RNG(seed + (i * 7919L)), data); - if (object == null || object.getBlocks().isEmpty()) { - continue; - } - object.setLoadKey("procedural/" + name + "#" + i); - object.setLoader(data); - baked.add(object); - } - - return baked; - }); + public Ruin() { } - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); + public String name() { + return name; } - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(mode); - placement.setRotation(rotation); - placement.setClamp(clamp); - placement.setCarvingSupport(carvingSupport); - placement.setUnderwater(underwater); - placement.setTranslate(translate); - placement.setStiltSettings(stiltSettings); - placement.setVacuumSettings(vacuumSettings); - placement.setChance(chance); - placement.setDensity(density); - return placement; + public double chance() { + return chance; } - public boolean isPlausible() { - return false; + public int density() { + return density; + } + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public ObjectPlaceMode mode() { + return mode == null ? ObjectPlaceMode.MIN_HEIGHT : mode; + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public CarvingMode carvingSupport() { + return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; + } + + public boolean underwater() { + return underwater; + } + + public ObjectTranslate translate() { + return translate; + } + + /** Empty where the pack sets none. */ + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + /** Empty where the pack sets none. */ + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public String block() { + return block; + } + + /** Empty where the pack sets none. */ + public Optional blockPalette() { + return Optional.ofNullable(blockPalette); + } + + public RuinForm form() { + return form == null ? RuinForm.PILLAR : form; + } + + public int heightMin() { + return heightMin; + } + + public int heightMax() { + return heightMax; + } + + public int widthMin() { + return widthMin; + } + + public int widthMax() { + return widthMax; + } + + public int lengthMin() { + return lengthMin; + } + + public int lengthMax() { + return lengthMax; + } + + /** Empty where the pack sets none. */ + public Optional weatheringPalette() { + return Optional.ofNullable(weatheringPalette); + } + + public String weatheredBlock() { + return weatheredBlock; + } + + public double mossiness() { + return mossiness; + } + + public double weatheringScale() { + return weatheringScale; + } + + public double erosion() { + return erosion; + } + + public double erosionScale() { + return erosionScale; + } + + public double buriedFraction() { + return buriedFraction; + } + + public List accents() { + return accents == null ? List.of() : Collections.unmodifiableList(accents); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java b/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecorator.java similarity index 63% rename from src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java rename to src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecorator.java index 35f2a74b4..c09789ea2 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecorator.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,38 +16,32 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.ruin; +package art.arcane.iris.builtin.objects.ruin; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -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.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Optional; @Snippet("ruin-decorator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("An accent block applied to a generated ruin after it is built and eroded, such as moss carpets on broken tops, vines on the faces, or rubble scattered around the base.") -@Data -public class IrisRuinDecorator { +public final class RuinDecorator { @Desc("Where on the ruin this accent is placed. TOP sits on the highest block of each column, SURFACE clings to air-facing vertical faces, BASE_SCATTER rings the ground footprint around the base.") - private IrisRuinDecoratorTarget target = IrisRuinDecoratorTarget.TOP; + private RuinDecoratorTarget target = RuinDecoratorTarget.TOP; @Required @Desc("The block id to place, e.g. minecraft:moss_carpet or minecraft:vine. Ignored when palette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = ""; @Desc("A noise-driven palette for this decorator. When set this overrides the single block, letting the accent mix blocks by noise. Resolved through IrisProceduralBlocks.resolve so the palette wins over the string.") - private IrisMaterialPalette palette = null; + private PaletteSpec palette; @MinNumber(0) @MaxNumber(1) @@ -57,4 +51,28 @@ public class IrisRuinDecorator { @MinNumber(1) @Desc("For the BASE_SCATTER target, how many blocks beyond the ruin footprint the scatter ring extends outward in each direction. Higher values fling rubble and growth further from the structure.") private int scatterRadius = 2; + + public RuinDecorator() { + } + + public RuinDecoratorTarget target() { + return target == null ? RuinDecoratorTarget.TOP : target; + } + + public String block() { + return block; + } + + /** Empty where the pack sets none. */ + public Optional palette() { + return Optional.ofNullable(palette); + } + + public double chance() { + return chance; + } + + public int scatterRadius() { + return scatterRadius; + } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java b/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecoratorTarget.java similarity index 89% rename from src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java rename to src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecoratorTarget.java index f3e13b96a..2b0b7e21e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinDecoratorTarget.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecoratorTarget.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.ruin; +package art.arcane.iris.builtin.objects.ruin; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Where a ruin accent block is placed after the ruin has been built and eroded.") -public enum IrisRuinDecoratorTarget { +public enum RuinDecoratorTarget { @Desc("On top of the highest surviving block in each column (moss carpets, snow, sculk, lanterns on broken tops).") TOP, @Desc("On air-facing vertical sides of any surviving block (vines, glow lichen, climbing growth on the ruin faces).") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java b/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinForm.java similarity index 93% rename from src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java rename to src/main/java/art/arcane/iris/builtin/objects/ruin/RuinForm.java index 507eac57d..02c8a8b60 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/IrisRuinForm.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinForm.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.ruin; +package art.arcane.iris.builtin.objects.ruin; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The overall silhouette of a procedural ruin. Each form rasterizes a different crumbling man-made shape from the same size, weathering, and erosion settings.") -public enum IrisRuinForm { +public enum RuinForm { @Desc("A broken vertical column. A square trunk (widthMin..widthMax footprint) rises to a randomized height then snaps off with a jagged crown, leaving a toppled stub. Use for ancient pillars and obelisk stumps.") PILLAR, @Desc("A standing wall segment. A flat slab spanning lengthMin..lengthMax long and heightMin..heightMax tall, thickness widthMin..widthMax, punched through with noise-driven gaps and a ragged top edge. Use for collapsed building sides and fortifications.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeAzimuthMode.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeAzimuthMode.java index 88dccbd99..f9373f666 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeAzimuthMode.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeAzimuthMode.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls the compass direction (azimuth) of trunk lean as it rises, or the direction each branch is thrown.") -public enum IrisTreeAzimuthMode { +public enum TreeAzimuthMode { @Desc("A single fixed azimuth.") CONSTANT, @Desc("Azimuth ramps straight from start to end with height.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranchProbability.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranchProbability.java index 6b07b0a10..c44d3fa34 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranchProbability.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranchProbability.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls how the chance of spawning a branch varies with trunk height (0 at the base, 1 at the top).") -public enum IrisTreeBranchProbability { +public enum TreeBranchProbability { @Desc("Same branch chance at every height.") CONSTANT, @Desc("Ramps straight from base chance to crown chance.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranches.java similarity index 57% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranches.java index e78f06868..2aea203d8 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeBranches.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranches.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,26 +16,20 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.Optional; @Snippet("tree-branches") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A branch system that throws limbs out of the trunk and places a leaf ball at each tip. When present, branches drive the canopy and only the topmost crown disc of the profile is still placed.") -@Data -public class IrisTreeBranches { +public final class TreeBranches { @Desc("How branch spawn chance varies over trunk height.") - private IrisTreeBranchProbability probabilityFunction = IrisTreeBranchProbability.TOP_HEAVY; + private TreeBranchProbability probabilityFunction = TreeBranchProbability.TOP_HEAVY; @MinNumber(0) @Desc("Branch chance for the CONSTANT probability function.") @@ -72,7 +66,7 @@ public class IrisTreeBranches { private double probabilityPeriods = 5; @Desc("How branch length varies over trunk height.") - private IrisTreeFunction lengthFunction = IrisTreeFunction.LINEAR; + private TreeFunction lengthFunction = TreeFunction.LINEAR; @MinNumber(0) @Desc("Branch length at the base for the LINEAR length function.") @@ -94,7 +88,7 @@ public class IrisTreeBranches { private double lengthSteepness = 5; @Desc("How the compass direction of each branch is chosen.") - private IrisTreeAzimuthMode azimuthMode = IrisTreeAzimuthMode.RANDOM; + private TreeAzimuthMode azimuthMode = TreeAzimuthMode.RANDOM; @Desc("Fixed azimuth in degrees when azimuthMode is CONSTANT.") private double azimuth = 0; @@ -120,12 +114,124 @@ public class IrisTreeBranches { private int clusterRadius = 2; @Desc("How the branch tip leaf cluster fills.") - private IrisTreeLeafMode clusterMode = IrisTreeLeafMode.TRIMMED; + private TreeLeafMode clusterMode = TreeLeafMode.TRIMMED; @MinNumber(0) @Desc("Fill density for the branch tip leaf cluster when clusterMode is density or noise.") private double clusterDensity = 0.85; @Desc("Optional one level of recursive sub-branches sprouting from each branch tip.") - private IrisTreeSubBranches subBranches = null; + private TreeSubBranches subBranches = null; + + public TreeBranches() { + } + + public TreeBranchProbability probabilityFunction() { + return probabilityFunction == null ? TreeBranchProbability.TOP_HEAVY : probabilityFunction; + } + + public double probabilityConstant() { + return probabilityConstant; + } + + public double probabilityBase() { + return probabilityBase; + } + + public double probabilityCrown() { + return probabilityCrown; + } + + public double probabilitySteepness() { + return probabilitySteepness; + } + + public double probabilityMidpoint() { + return probabilityMidpoint; + } + + public double probabilityExponent() { + return probabilityExponent; + } + + public double probabilityMean() { + return probabilityMean; + } + + public double probabilityStd() { + return probabilityStd; + } + + public double probabilityScale() { + return probabilityScale; + } + + public double probabilityPeriods() { + return probabilityPeriods; + } + + public TreeFunction lengthFunction() { + return lengthFunction == null ? TreeFunction.LINEAR : lengthFunction; + } + + public double lengthBase() { + return lengthBase; + } + + public double lengthCrown() { + return lengthCrown; + } + + public double lengthConstant() { + return lengthConstant; + } + + public double lengthMax() { + return lengthMax; + } + + public double lengthSteepness() { + return lengthSteepness; + } + + public TreeAzimuthMode azimuthMode() { + return azimuthMode == null ? TreeAzimuthMode.RANDOM : azimuthMode; + } + + public double azimuth() { + return azimuth; + } + + public double elevation() { + return elevation; + } + + public double sag() { + return sag; + } + + public int branchDepth() { + return branchDepth; + } + + public boolean leafStartUp() { + return leafStartUp; + } + + public int clusterRadius() { + return clusterRadius; + } + + public TreeLeafMode clusterMode() { + return clusterMode == null ? TreeLeafMode.TRIMMED : clusterMode; + } + + public double clusterDensity() { + return clusterDensity; + } + + /** Empty where the pack sets none. */ + public Optional subBranches() { + return Optional.ofNullable(subBranches); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeCanopy.java similarity index 60% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeCanopy.java index fb14d2c57..ca748c351 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeCanopy.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeCanopy.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,26 +16,21 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -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.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; @Snippet("tree-canopy") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("The leaf crown of a procedural tree. Built from stacked dome-shaped discs (driven by the profile or by explicit layers) and optionally a branch system.") -@Data -public class IrisTreeCanopy { +public final class TreeCanopy { @MinNumber(0) @MaxNumber(180) @Desc("Elevation angle in degrees from vertical for each leaf dome. 90 is a flat disc, below 90 domes downward into a sphere, above 90 flares outward into an umbrella.") @@ -47,7 +42,7 @@ public class IrisTreeCanopy { private double squish = 1; @Desc("How leaves fill each canopy disc.") - private IrisTreeLeafMode mode = IrisTreeLeafMode.TRIMMED; + private TreeLeafMode mode = TreeLeafMode.TRIMMED; @MinNumber(0) @MaxNumber(1) @@ -62,10 +57,46 @@ public class IrisTreeCanopy { @Desc("Horizontal Z stretch of the crown for elliptical or wind-blown shapes. 1 is circular.") private double crownStretchZ = 1; - @ArrayType(min = 1, type = IrisTreeLayer.class) + @MinItems(1) @Desc("Optional explicit crown discs. When provided these replace the profile-driven layers and let you sculpt the silhouette by hand.") - private KList layers = new KList<>(); + private List layers = List.of(); @Desc("Optional branch system. When present, branches build most of the canopy and only the topmost profile disc is still placed as a crown.") - private IrisTreeBranches branches = null; + private TreeBranches branches = null; + + public TreeCanopy() { + } + + public double startAngle() { + return startAngle; + } + + public double squish() { + return squish; + } + + public TreeLeafMode mode() { + return mode == null ? TreeLeafMode.TRIMMED : mode; + } + + public double leafDensity() { + return leafDensity; + } + + public double crownStretchX() { + return crownStretchX; + } + + public double crownStretchZ() { + return crownStretchZ; + } + + public List layers() { + return layers == null ? List.of() : Collections.unmodifiableList(layers); + } + + /** Empty where the pack sets none. */ + public Optional branches() { + return Optional.ofNullable(branches); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecorator.java similarity index 57% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecorator.java index 78fbe258e..78700bb5a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecorator.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,37 +16,32 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -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.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Optional; @Snippet("tree-decorator") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("An accent block applied to a generated tree such as fruit on branch tips, vines on the trunk, snow on the crown, or a glowing underside.") -@Data -public class IrisTreeDecorator { +public final class TreeDecorator { @Desc("Where this decorator is placed on the tree.") - private IrisTreeDecoratorTarget target = IrisTreeDecoratorTarget.BRANCH_TIP; + private TreeDecoratorTarget target = TreeDecoratorTarget.BRANCH_TIP; @Required @Desc("The block id to place, e.g. minecraft:magma_block. Ignored when palette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = ""; @Desc("A noise-driven palette for this decorator. When set this overrides the single block.") - private IrisMaterialPalette palette = null; + private PaletteSpec palette; @MinNumber(0) @MaxNumber(1) @@ -59,4 +54,32 @@ public class IrisTreeDecorator { @Desc("If true the block's facing is oriented away from the trunk (for trunk-mounted fences/gates/banners).") private boolean axisAware = false; + + public TreeDecorator() { + } + + public TreeDecoratorTarget target() { + return target == null ? TreeDecoratorTarget.BRANCH_TIP : target; + } + + public String block() { + return block; + } + + /** Empty where the pack sets none. */ + public Optional palette() { + return Optional.ofNullable(palette); + } + + public double chance() { + return chance; + } + + public int length() { + return length; + } + + public boolean axisAware() { + return axisAware; + } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecoratorTarget.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecoratorTarget.java index 734d89150..598ce05c2 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeDecoratorTarget.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecoratorTarget.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Where a tree decorator block is placed.") -public enum IrisTreeDecoratorTarget { +public enum TreeDecoratorTarget { @Desc("At the tip of each generated branch (vines, fruit, lanterns).") BRANCH_TIP, @Desc("On air-facing sides of trunk and branch blocks (vines, moss).") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeFunction.java similarity index 92% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeFunction.java index 5bbf1efed..3f4cc7c9c 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeFunction.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeFunction.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("A shaping function evaluated over normalized height (0 at the base, 1 at the top). Used for trunk width, trunk curve and branch length.") -public enum IrisTreeFunction { +public enum TreeFunction { @Desc("Same value at every height.") CONSTANT, @Desc("Ramps straight from start to end.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLayer.java similarity index 65% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeLayer.java index 526d437e3..1f5181cae 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLayer.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLayer.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,27 +16,30 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Snippet; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MinNumber; @Snippet("tree-layer") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("An explicit canopy disc at a given vertical offset and radius. Define a list of these to bypass the profile and sculpt the crown by hand.") -@Data -public class IrisTreeLayer { +public final class TreeLayer { @Desc("The vertical offset of this disc, measured in blocks above the trunk base.") private int yOffset = 0; @MinNumber(0.5) @Desc("The radius of this leaf disc in blocks.") private double radius = 2; + + public TreeLayer() { + } + + public int yOffset() { + return yOffset; + } + + public double radius() { + return radius; + } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLeafMode.java similarity index 91% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeLeafMode.java index 3801e148f..7ac85244f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeLeafMode.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLeafMode.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("How leaves fill a disc or cluster.") -public enum IrisTreeLeafMode { +public enum TreeLeafMode { @Desc("Corner-trimmed disc/sphere for a rounded silhouette.") TRIMMED, @Desc("Completely filled disc/sphere.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeProfile.java similarity index 93% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeProfile.java index e5fca1397..14f9b2af5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeProfile.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeProfile.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Named canopy presets that drive default layer radii and shape, scaled to the tree height.") -public enum IrisTreeProfile { +public enum TreeProfile { @Desc("Rounded broadleaf crown.") OAK, @Desc("Slim upright broadleaf crown.") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeRootStyle.java similarity index 89% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeRootStyle.java index d8b80e7b9..4ef5457fe 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeRootStyle.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeRootStyle.java @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("How a procedural tree's root system is built below (and around) the trunk base.") -public enum IrisTreeRootStyle { +public enum TreeRootStyle { @Desc("A single tapering taproot straight down from the base.") TAPROOT, @Desc("A taproot plus a ring of flared buttress legs that splay outward as they descend (default).") diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSecondaryLeaf.java similarity index 58% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeSecondaryLeaf.java index 160b9d48f..54f96c881 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSecondaryLeaf.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSecondaryLeaf.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,31 +16,35 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListBlockType; -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; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; @Snippet("tree-secondary-leaf") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A weighted accent leaf or foliage block scattered through the canopy (blossoms, shroomlight, berries).") -@Data -public class IrisTreeSecondaryLeaf { +public final class TreeSecondaryLeaf { @Required @Desc("The block id to scatter, e.g. minecraft:shroomlight") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String block = ""; @MinNumber(0) @Desc("The relative weight of this block among the secondary leaves.") private int weight = 1; + + public TreeSecondaryLeaf() { + } + + public String block() { + return block; + } + + public int weight() { + return weight; + } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSubBranches.java similarity index 64% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/TreeSubBranches.java index a6a591dd2..efd42f501 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSubBranches.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSubBranches.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,24 +16,16 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -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 lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; @Snippet("tree-sub-branches") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("One recursive level of sub-branches sprouting from each primary branch tip.") -@Data -public class IrisTreeSubBranches { +public final class TreeSubBranches { @MinNumber(1) @Desc("How many sub-branches sprout from each primary branch tip.") private int count = 1; @@ -58,9 +50,44 @@ public class IrisTreeSubBranches { private int clusterRadius = 1; @Desc("How the sub-branch tip leaf cluster fills.") - private IrisTreeLeafMode clusterMode = IrisTreeLeafMode.TRIMMED; + private TreeLeafMode clusterMode = TreeLeafMode.TRIMMED; @MinNumber(0) @Desc("Fill density for the sub-branch leaf cluster when clusterMode is density or noise.") private double clusterDensity = 0.85; + + public TreeSubBranches() { + } + + public int count() { + return count; + } + + public double pitchDelta() { + return pitchDelta; + } + + public double yawDelta() { + return yawDelta; + } + + public double lengthScale() { + return lengthScale; + } + + public double sag() { + return sag; + } + + public int clusterRadius() { + return clusterRadius; + } + + public TreeLeafMode clusterMode() { + return clusterMode == null ? TreeLeafMode.TRIMMED : clusterMode; + } + + public double clusterDensity() { + return clusterDensity; + } } diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java new file mode 100644 index 000000000..71f972ab0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java @@ -0,0 +1,60 @@ +/* + * 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.builtin.prepare; + +import com.volmit.config.Desc; +import com.volmit.config.Snippet; + +/** How an object is turned around each axis, written as a placement's {@code rotation}. */ +@Snippet("object-rotator") +@Desc("Configures rotation for iris") +public final class ObjectRotation { + private static final double QUARTER_TURN_DEGREES = 90; + + @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, QUARTER_TURN_DEGREES); + + @Desc("The z axis rotation") + private AxisRotationClamp zAxis = new AxisRotationClamp(); + + public ObjectRotation() { + } + + public boolean enabled() { + return enabled; + } + + public AxisRotationClamp xAxis() { + return xAxis; + } + + public AxisRotationClamp yAxis() { + return yAxis; + } + + public AxisRotationClamp zAxis() { + return zAxis; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java new file mode 100644 index 000000000..45afcef6d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java @@ -0,0 +1,70 @@ +/* + * 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.builtin.prepare; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** How far an object is shifted from where it would be placed, written as a placement's {@code translate}. */ +@Snippet("object-translator") +@Desc("Translate objects") +public final class ObjectTranslate { + @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 ObjectTranslate() { + } + + public int x() { + return x; + } + + public int y() { + return y; + } + + public int yRandom() { + return yRandom; + } + + public int z() { + return z; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 6e7b4fd5e..534dbef02 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -19,6 +19,14 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.objects.coral.Coral; +import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.builtin.objects.ruin.Ruin; +import art.arcane.iris.builtin.objects.tree.TreeCanopy; +import art.arcane.iris.builtin.objects.tree.TreeDecorator; +import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.core.modules.IrisPackWorld; @@ -56,6 +64,14 @@ public final class ObjectModule implements IrisModule { @Override public void register(FeatureRegistry registry) { registry.registerService(ObjectsAt.class, ObjectModule::objectsAt); + registry.registerHeldType(TreeCanopy.class); + registry.registerHeldType(TreeDecorator.class); + registry.registerHeldType(TreeSecondaryLeaf.class); + registry.registerHeldType(Coral.class); + registry.registerHeldType(Crystal.class); + registry.registerHeldType(Formation.class); + registry.registerHeldType(Fungus.class); + registry.registerHeldType(Ruin.class); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java index de4ab0c45..f18a45811 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.object.procedural; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.spi.PlatformBlockState; @@ -26,8 +25,10 @@ import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.math.IrisBlockVector; import art.arcane.iris.util.common.math.Vector3i; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.PaletteSpec; import java.util.Map; +import java.util.Optional; /** * Shared low-level helpers for building procedural objects in memory: resolving a @@ -52,13 +53,26 @@ public final class IrisProceduralBlocks { }; } - public static boolean paletteSet(IrisMaterialPalette palette) { - return palette != null && palette.getPalette() != null && !palette.getPalette().isEmpty(); + public static boolean paletteSet(PaletteSpec palette) { + return palette != null && !palette.palette().isEmpty(); } - public static PlatformBlockState resolve(String block, IrisMaterialPalette palette, IrisData data, int x, int y, int z, RNG paletteRng) { + public static boolean paletteSet(Optional palette) { + return palette.filter(IrisProceduralBlocks::paletteSet).isPresent(); + } + + public static PlatformBlockState resolve(String block, Optional palette, IrisData data, int x, int y, int z, RNG paletteRng) { + return resolve(block, palette.orElse(null), data, x, y, z, paletteRng); + } + + public static PlatformBlockState resolve(Optional block, Optional palette, IrisData data, int x, int y, int z, RNG paletteRng) { + return resolve(block.orElse(null), palette.orElse(null), data, x, y, z, paletteRng); + } + + /** The block of {@code palette} at the position, picked with the seed of {@code paletteRng} as the palette's old class did; else {@code block}. */ + public static PlatformBlockState resolve(String block, PaletteSpec palette, IrisData data, int x, int y, int z, RNG paletteRng) { if (paletteSet(palette)) { - return palette.get(paletteRng, x, y, z, data); + return pick(palette, data, paletteRng.getSeed(), x, y, z); } if (block != null && !block.isEmpty()) { return B.getStateOrNull(block, false); @@ -66,6 +80,11 @@ public final class IrisProceduralBlocks { return null; } + /** The block {@code palette} gives at the position when its noise is seeded with {@code seed}. */ + public static PlatformBlockState pick(PaletteSpec palette, IrisData data, long seed, int x, int y, int z) { + return B.getState(data.getPackResources().blocks().palette(palette, seed).at(x, y, z).key()); + } + public static boolean hasProperty(PlatformBlockState state, String property) { String key = state.key(); int start = propertyStart(key, property); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java index 1f4201ce8..eb594c1d0 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java @@ -18,18 +18,31 @@ package art.arcane.iris.engine.object.procedural; -import art.arcane.iris.engine.object.procedural.coral.IrisCoral; -import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; -import art.arcane.iris.engine.object.procedural.formation.IrisFormation; -import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; -import art.arcane.iris.engine.object.procedural.ruin.IrisRuin; +import art.arcane.iris.builtin.objects.ruin.Ruin; +import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; +import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; +import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; +import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; +import art.arcane.iris.builtin.objects.coral.Coral; +import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.Snippet; import art.arcane.volmlib.util.collection.KList; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; import lombok.AllArgsConstructor; +import lombok.AccessLevel; import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @@ -40,53 +53,59 @@ import lombok.experimental.Accessors; @Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") @Data public class IrisProceduralObjects { + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + @EqualsAndHashCode.Exclude + private final transient Map placeables = new ConcurrentHashMap<>(); + @ArrayType(min = 1, type = IrisProceduralTree.class) @Desc("Procedurally generated trees.") private KList trees = new KList<>(); - @ArrayType(min = 1, type = IrisRuin.class) + @ArrayType(min = 1, type = Ruin.class) @Desc("Procedurally generated ruins (crumbling pillars, walls, arches, rubble).") - private KList ruins = new KList<>(); + private KList ruins = new KList<>(); - @ArrayType(min = 1, type = IrisFormation.class) + @ArrayType(min = 1, type = Formation.class) @Desc("Procedurally generated natural rock formations (spires, hoodoos, arches, sea stacks, boulders, basalt columns).") - private KList formations = new KList<>(); + private KList formations = new KList<>(); - @ArrayType(min = 1, type = IrisCoral.class) + @ArrayType(min = 1, type = Coral.class) @Desc("Procedurally generated underwater coral structures.") - private KList coral = new KList<>(); + private KList coral = new KList<>(); - @ArrayType(min = 1, type = IrisFungus.class) + @ArrayType(min = 1, type = Fungus.class) @Desc("Procedurally generated mushrooms and shelf fungi.") - private KList fungi = new KList<>(); + private KList fungi = new KList<>(); - @ArrayType(min = 1, type = IrisCrystal.class) + @ArrayType(min = 1, type = Crystal.class) @Desc("Procedurally generated crystal clusters (usually placed in caves).") - private KList crystals = new KList<>(); + private KList crystals = new KList<>(); public KList getAllPlacements() { KList all = new KList<>(); if (trees != null) { all.addAll(trees); } - if (ruins != null) { - all.addAll(ruins); - } - if (formations != null) { - all.addAll(formations); - } - if (coral != null) { - all.addAll(coral); - } - if (fungi != null) { - all.addAll(fungi); - } - if (crystals != null) { - all.addAll(crystals); - } + addPlaceable(all, ruins, ResolvedRuin::new); + addPlaceable(all, formations, ResolvedFormation::new); + addPlaceable(all, coral, ResolvedCoral::new); + addPlaceable(all, fungi, ResolvedFungus::new); + addPlaceable(all, crystals, ResolvedCrystal::new); return all; } + /** The settings in {@code settings}, each made placeable once, in order. */ + @SuppressWarnings("unchecked") + private void addPlaceable(KList all, KList settings, Function resolve) { + if (settings == null) { + return; + } + for (S entry : settings) { + all.add(placeables.computeIfAbsent(entry, key -> resolve.apply((S) key))); + } + } + public boolean isEmpty() { return getAllPlacements().isEmpty(); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java new file mode 100644 index 000000000..695d1b211 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java @@ -0,0 +1,158 @@ +/* + * 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.procedural; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.prefab.IrisObjectRotation; +import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +/** + * A procedural object's settings made placeable: bakes a deterministic pool of variants from them, once, and turns + * the placement options into the object placement the engine scatters. The settings classes held the same cache + * and methods before they became module settings. + */ +public abstract class ResolvedProceduralPlacement implements IrisProceduralPlacement { + private static final long VARIANT_SEED_STRIDE = 7919L; + + /** The options every procedural placement shares with an object placement. */ + public record Shape(String name, double chance, int density, long seed, int variants, ObjectPlaceMode mode, + ObjectRotation rotation, ObjectLimit clamp, CarvingMode carvingSupport, boolean underwater, + ObjectTranslate translate, StiltSettings stiltSettings, VacuumSettings vacuumSettings) { + } + + private final Shape shape; + private final AtomicCache> variantCache = new AtomicCache<>(); + + protected ResolvedProceduralPlacement(Shape shape) { + this.shape = shape; + } + + /** The object variant {@code index} is baked as, from its own seeded stream. */ + protected abstract IrisObject generate(int index, RNG rng, IrisData data); + + /** The number of variants to bake; the settings' count, at least one. */ + protected int variantCount() { + return Math.max(1, shape.variants()); + } + + @Override + public String getName() { + return shape.name(); + } + + @Override + public double getChance() { + return shape.chance(); + } + + @Override + public int getDensity() { + return shape.density(); + } + + @Override + public boolean isPlausible() { + return false; + } + + @Override + public KList getVariantObjects(IrisData data) { + return variantCache.aquire(() -> bake(data)); + } + + /** Bakes every variant; the default draws variant {@code i} from {@code seed + i * stride}. */ + protected KList bake(IrisData data) { + KList baked = new KList<>(); + int count = variantCount(); + + for (int i = 0; i < count; i++) { + IrisObject object = generate(i, variantRng(i), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + shape.name() + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + } + + protected final RNG variantRng(int index) { + return new RNG(shape.seed() + (index * VARIANT_SEED_STRIDE)); + } + + protected final long seed() { + return shape.seed(); + } + + @Override + public IrisObject getVariantObject(IrisData data, RNG rng) { + KList baked = getVariantObjects(data); + if (baked == null || baked.isEmpty()) { + return null; + } + return baked.get(rng.i(baked.size())); + } + + @Override + public IrisObjectPlacement asPlacement() { + IrisObjectPlacement placement = new IrisObjectPlacement(); + placement.setMode(shape.mode()); + placement.setRotation(irisRotation(shape.rotation())); + placement.setClamp(shape.clamp()); + placement.setCarvingSupport(shape.carvingSupport()); + placement.setUnderwater(shape.underwater()); + placement.setTranslate(irisTranslate(shape.translate())); + placement.setStiltSettings(shape.stiltSettings()); + placement.setVacuumSettings(shape.vacuumSettings()); + placement.setChance(shape.chance()); + placement.setDensity(shape.density()); + customize(placement); + return placement; + } + + /** Sets what this kind of placement adds to the common options. */ + protected void customize(IrisObjectPlacement placement) { + } + + private static IrisObjectRotation irisRotation(ObjectRotation rotation) { + return new IrisObjectRotation() + .setEnabled(rotation.enabled()) + .setXAxis(rotation.xAxis()) + .setYAxis(rotation.yAxis()) + .setZAxis(rotation.zAxis()); + } + + private static IrisObjectTranslate irisTranslate(ObjectTranslate translate) { + return new IrisObjectTranslate(translate.x(), translate.y(), translate.yRandom(), translate.z()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java index 17c4a4980..ee6c1c48d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.coral; +import art.arcane.iris.builtin.objects.coral.Coral; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.procedural.coral.IrisCoral; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; @@ -36,14 +36,14 @@ public final class CoralGenerator { private CoralGenerator() { } - public static IrisObject generate(IrisCoral coral, int variantIndex, RNG rng, IrisData data) { - int lo = Math.min(coral.getHeightMin(), coral.getHeightMax()); - int hi = Math.max(coral.getHeightMin(), coral.getHeightMax()); + public static IrisObject generate(Coral coral, int variantIndex, RNG rng, IrisData data) { + int lo = Math.min(coral.heightMin(), coral.heightMax()); + int hi = Math.max(coral.heightMin(), coral.heightMax()); int height = Math.max(2, rng.i(lo, hi + 1)); long shapeSeed = rng.getSeed() + variantIndex * 31L; CoralCanvas canvas = new CoralCanvas(); - switch (coral.getForm()) { + switch (coral.form()) { case BRANCHING -> buildBranching(canvas, coral, height, shapeSeed, rng); case FAN -> buildFan(canvas, coral, height, shapeSeed); case BRAIN -> buildBrain(canvas, coral, height, shapeSeed); @@ -55,39 +55,39 @@ public final class CoralGenerator { return IrisProceduralBlocks.assemble(resolved); } - private static void buildBranching(CoralCanvas canvas, IrisCoral coral, int height, long seed, RNG rng) { + private static void buildBranching(CoralCanvas canvas, Coral coral, int height, long seed, RNG rng) { int stalkTop = Math.max(1, (int) Math.round(height * 0.5)); for (int y = 0; y < stalkTop; y++) { placeWavy(canvas, coral, 0, y, 0, y, seed, CoralCanvas.Role.STRUCTURE); } - int count = Math.max(1, coral.getBranchCount()); + int count = Math.max(1, coral.branchCount()); for (int b = 0; b < count; b++) { double az = branchAzimuth(coral, b, count, rng); int startY = stalkTop - 1 + (int) Math.round((b % 2) * 1.0); double[] tip = rasterizeArm(canvas, coral, 0, startY, 0, az, - coral.getBranchElevation(), coral.getBranchLength(), seed + b * 131L); + coral.branchElevation(), coral.branchLength(), seed + b * 131L); placeTipCluster(canvas, coral, (int) Math.round(tip[0]), (int) Math.round(tip[1]), (int) Math.round(tip[2]), - coral.getTipClusterRadius(), seed + b * 977L); + coral.tipClusterRadius(), seed + b * 977L); - if (coral.isSubBranches()) { - int subCount = Math.max(1, coral.getSubBranchCount()); + if (coral.subBranches()) { + int subCount = Math.max(1, coral.subBranchCount()); for (int s = 0; s < subCount; s++) { double subAz = az + (s - (subCount - 1) / 2.0) * 35.0; - double subLen = coral.getBranchLength() * coral.getSubBranchScale(); + double subLen = coral.branchLength() * coral.subBranchScale(); double[] subTip = rasterizeArm(canvas, coral, (int) Math.round(tip[0]), (int) Math.round(tip[1]), (int) Math.round(tip[2]), - subAz, coral.getBranchElevation() + 10.0, subLen, seed + b * 131L + s * 17L + 5000L); + subAz, coral.branchElevation() + 10.0, subLen, seed + b * 131L + s * 17L + 5000L); placeTipCluster(canvas, coral, (int) Math.round(subTip[0]), (int) Math.round(subTip[1]), (int) Math.round(subTip[2]), - Math.max(0, coral.getTipClusterRadius() - 1), seed + b * 977L + s * 53L); + Math.max(0, coral.tipClusterRadius() - 1), seed + b * 977L + s * 53L); } } } } - private static void buildFan(CoralCanvas canvas, IrisCoral coral, int height, long seed) { - int half = Math.max(1, coral.getFanWidth()); + private static void buildFan(CoralCanvas canvas, Coral coral, int height, long seed) { + int half = Math.max(1, coral.fanWidth()); for (int y = 0; y < height; y++) { double t = y / (double) Math.max(1, height - 1); double profile = Math.sin(Math.PI * t); @@ -101,10 +101,10 @@ public final class CoralGenerator { } } - private static void buildBrain(CoralCanvas canvas, IrisCoral coral, int height, long seed) { - int r = Math.max(1, coral.getBrainRadius()); + private static void buildBrain(CoralCanvas canvas, Coral coral, int height, long seed) { + int r = Math.max(1, coral.brainRadius()); int ry = Math.max(1, Math.min(r, (int) Math.round(height * 0.6))); - double rough = coral.getBrainRoughness(); + double rough = coral.brainRoughness(); for (int dx = -r; dx <= r; dx++) { for (int dz = -r; dz <= r; dz++) { for (int dy = 0; dy <= ry * 2; dy++) { @@ -121,8 +121,8 @@ public final class CoralGenerator { } } - private static void buildPillar(CoralCanvas canvas, IrisCoral coral, int height, long seed) { - int r = Math.max(1, coral.getPillarRadius()); + private static void buildPillar(CoralCanvas canvas, Coral coral, int height, long seed) { + int r = Math.max(1, coral.pillarRadius()); for (int y = 0; y < height; y++) { for (int dx = -r; dx <= r; dx++) { for (int dz = -r; dz <= r; dz++) { @@ -132,12 +132,12 @@ public final class CoralGenerator { } } } - placeTipCluster(canvas, coral, 0, height - 1, 0, coral.getTipClusterRadius(), seed); + placeTipCluster(canvas, coral, 0, height - 1, 0, coral.tipClusterRadius(), seed); } - private static void buildTendril(CoralCanvas canvas, IrisCoral coral, int height, long seed, RNG rng) { - int count = Math.max(1, coral.getTendrilCount()); - double radius = Math.max(0.0, coral.getSpread()); + private static void buildTendril(CoralCanvas canvas, Coral coral, int height, long seed, RNG rng) { + int count = Math.max(1, coral.tendrilCount()); + double radius = Math.max(0.0, coral.spread()); for (int c = 0; c < count; c++) { double az = Math.toRadians(c * (360.0 / count)); double bx = Math.cos(az) * radius * 0.5; @@ -153,7 +153,7 @@ public final class CoralGenerator { } } - private static double[] rasterizeArm(CoralCanvas canvas, IrisCoral coral, int ox, int oy, int oz, + private static double[] rasterizeArm(CoralCanvas canvas, Coral coral, int ox, int oy, int oz, double azimuthDeg, double elevationDeg, double length, long seed) { double azRad = Math.toRadians(azimuthDeg); double elRad = Math.toRadians(elevationDeg); @@ -175,23 +175,23 @@ public final class CoralGenerator { return tip; } - private static void placeWavy(CoralCanvas canvas, IrisCoral coral, int x, int y, int z, double phase, long seed, CoralCanvas.Role role) { + private static void placeWavy(CoralCanvas canvas, Coral coral, int x, int y, int z, double phase, long seed, CoralCanvas.Role role) { double sway = swayOffset(coral, phase, seed); int sx = (int) Math.round(sway); int sz = (int) Math.round(swayOffset(coral, phase + 53.0, seed + 7L)); canvas.set(x + sx, y, z + sz, role); } - private static double swayOffset(IrisCoral coral, double phase, long seed) { - double amount = Math.max(0.0, Math.min(1.0, coral.getSway())); + private static double swayOffset(Coral coral, double phase, long seed) { + double amount = Math.max(0.0, Math.min(1.0, coral.sway())); if (amount <= 0.0) { return 0.0; } double n = TreeFunctions.valueNoise1D(phase * 0.35, seed) - 0.5; - return n * 2.0 * amount * (1.0 + coral.getSpread() * 0.25); + return n * 2.0 * amount * (1.0 + coral.spread() * 0.25); } - private static void placeTipCluster(CoralCanvas canvas, IrisCoral coral, int cx, int cy, int cz, int radius, long seed) { + private static void placeTipCluster(CoralCanvas canvas, Coral coral, int cx, int cy, int cz, int radius, long seed) { if (radius <= 0) { placeTip(canvas, coral, cx, cy, cz, seed); return; @@ -208,31 +208,31 @@ public final class CoralGenerator { placeTip(canvas, coral, cx, cy + radius + 1, cz, seed); } - private static void placeTip(CoralCanvas canvas, IrisCoral coral, int x, int y, int z, long seed) { + private static void placeTip(CoralCanvas canvas, Coral coral, int x, int y, int z, long seed) { if (!hasTip(coral)) { return; } - if (TreeFunctions.valueNoise1D(x * 31.0 + y * 17.0 + z * 13.0, seed) <= coral.getTipChance()) { + if (TreeFunctions.valueNoise1D(x * 31.0 + y * 17.0 + z * 13.0, seed) <= coral.tipChance()) { canvas.set(x, y, z, CoralCanvas.Role.TIP); } } - private static boolean hasTip(IrisCoral coral) { - return IrisProceduralBlocks.paletteSet(coral.getTipPalette()) - || (coral.getTipBlock() != null && !coral.getTipBlock().isEmpty()); + private static boolean hasTip(Coral coral) { + return IrisProceduralBlocks.paletteSet(coral.tipPalette()) + || (coral.tipBlock() != null && !coral.tipBlock().isEmpty()); } - private static double branchAzimuth(IrisCoral coral, int index, int count, RNG rng) { - return switch (coral.getBranchAzimuth()) { + private static double branchAzimuth(Coral coral, int index, int count, RNG rng) { + return switch (coral.branchAzimuth()) { case GOLDEN_ANGLE -> index * GOLDEN_ANGLE; case EVEN -> index * (360.0 / count); case RANDOM -> rng.d(0.0, 360.0); }; } - private static Map resolve(CoralCanvas canvas, IrisCoral coral, IrisData data) { + private static Map resolve(CoralCanvas canvas, Coral coral, IrisData data) { Map out = new HashMap<>(); - RNG paletteRng = new RNG(coral.getSeed()); + RNG paletteRng = new RNG(coral.seed()); for (Map.Entry entry : canvas.getCells().entrySet()) { int[] xyz = CoralCanvas.decode(entry.getKey()); int x = xyz[0]; @@ -240,17 +240,17 @@ public final class CoralGenerator { int z = xyz[2]; PlatformBlockState state; if (entry.getValue() == CoralCanvas.Role.TIP) { - state = IrisProceduralBlocks.resolve(coral.getTipBlock(), coral.getTipPalette(), data, x, y, z, paletteRng); + state = IrisProceduralBlocks.resolve(coral.tipBlock(), coral.tipPalette(), data, x, y, z, paletteRng); if (state == null) { - state = IrisProceduralBlocks.resolve(coral.getBlock(), coral.getBlockPalette(), data, x, y, z, paletteRng); + state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), data, x, y, z, paletteRng); } } else { - state = IrisProceduralBlocks.resolve(coral.getBlock(), coral.getBlockPalette(), data, x, y, z, paletteRng); + state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), data, x, y, z, paletteRng); } if (state == null) { continue; } - if (coral.isWaterlogged() && IrisProceduralBlocks.hasProperty(state, "waterlogged")) { + if (coral.waterlogged() && IrisProceduralBlocks.hasProperty(state, "waterlogged")) { try { state = state.withProperty("waterlogged", "true"); } catch (IllegalArgumentException ignored) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java new file mode 100644 index 000000000..db3ef9dea --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java @@ -0,0 +1,42 @@ +/* + * 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.procedural.coral; + +import art.arcane.iris.builtin.objects.coral.Coral; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.volmlib.util.math.RNG; + +/** A coral reef made placeable: its variants are baked by {@link CoralGenerator}. */ +public final class ResolvedCoral extends ResolvedProceduralPlacement { + private final Coral settings; + + public ResolvedCoral(Coral settings) { + super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), + settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + this.settings = settings; + } + + @Override + protected IrisObject generate(int index, RNG rng, IrisData data) { + return CoralGenerator.generate(settings, index, rng, data); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java index 18a2b80a6..65e8924c8 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java @@ -18,21 +18,21 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; +import art.arcane.iris.builtin.objects.crystal.Crystal; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; public final class CrystalBaseBuilder { private CrystalBaseBuilder() { } - public static void build(CrystalCanvas canvas, IrisCrystal crystal, long seed) { - double radius = crystal.getBaseRadius(); + public static void build(CrystalCanvas canvas, Crystal crystal, long seed) { + double radius = crystal.baseRadius(); if (radius <= 0.0) { canvas.set(0, 0, 0, CrystalRole.BASE); return; } - double noiseStrength = crystal.getBaseNoise(); + double noiseStrength = crystal.baseNoise(); int reach = (int) Math.ceil(radius + 1.0); for (int x = -reach; x <= reach; x++) { for (int y = -reach; y <= reach; y++) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java index e6ed58df2..03087c84c 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java @@ -18,8 +18,9 @@ package art.arcane.iris.engine.object.procedural.crystal; +import art.arcane.iris.builtin.objects.crystal.Crystal; +import com.volmit.block.PaletteSpec; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; @@ -33,7 +34,7 @@ public final class CrystalGenerator { private CrystalGenerator() { } - public static IrisObject generate(IrisCrystal crystal, int variantIndex, RNG rng, IrisData data) { + public static IrisObject generate(Crystal crystal, int variantIndex, RNG rng, IrisData data) { CrystalCanvas canvas = new CrystalCanvas(); long structureSeed = rng.getSeed(); @@ -41,8 +42,8 @@ public final class CrystalGenerator { CrystalShardBuilder.build(canvas, crystal, rng); Map resolved = new HashMap<>(); - RNG paletteRng = new RNG(crystal.getSeed()); - RNG tipRng = new RNG(crystal.getSeed() + (variantIndex * 31337L) + 4099L); + RNG paletteRng = new RNG(crystal.seed()); + RNG tipRng = new RNG(crystal.seed() + (variantIndex * 31337L) + 4099L); for (Map.Entry entry : canvas.getCells().entrySet()) { Vector3i position = entry.getKey(); @@ -59,7 +60,7 @@ public final class CrystalGenerator { return IrisProceduralBlocks.assemble(resolved); } - private static PlatformBlockState resolveRole(IrisCrystal crystal, CrystalRole role, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { + private static PlatformBlockState resolveRole(Crystal crystal, CrystalRole role, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { return switch (role) { case BASE -> resolveBase(crystal, data, x, y, z, paletteRng); case SHARD -> resolveShard(crystal, data, x, y, z, paletteRng); @@ -67,11 +68,11 @@ public final class CrystalGenerator { }; } - private static PlatformBlockState resolveBase(IrisCrystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { - boolean hasBase = IrisProceduralBlocks.paletteSet(crystal.getBasePalette()) - || (crystal.getBaseBlock() != null && !crystal.getBaseBlock().isEmpty()); + private static PlatformBlockState resolveBase(Crystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { + boolean hasBase = IrisProceduralBlocks.paletteSet(crystal.basePalette()) + || (crystal.baseBlock() != null && !crystal.baseBlock().isEmpty()); if (hasBase) { - PlatformBlockState base = IrisProceduralBlocks.resolve(crystal.getBaseBlock(), crystal.getBasePalette(), data, x, y, z, paletteRng); + PlatformBlockState base = IrisProceduralBlocks.resolve(crystal.baseBlock(), crystal.basePalette(), data, x, y, z, paletteRng); if (base != null) { return base; } @@ -79,17 +80,17 @@ public final class CrystalGenerator { return resolveShard(crystal, data, x, y, z, paletteRng); } - private static PlatformBlockState resolveShard(IrisCrystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { - return IrisProceduralBlocks.resolve(crystal.getBlock(), crystal.getBlockPalette(), data, x, y, z, paletteRng); + private static PlatformBlockState resolveShard(Crystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { + return IrisProceduralBlocks.resolve(crystal.block(), crystal.blockPalette(), data, x, y, z, paletteRng); } - private static PlatformBlockState resolveTip(IrisCrystal crystal, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { - boolean hasTip = IrisProceduralBlocks.paletteSet(crystal.getTipPalette()) - || (crystal.getTipBlock() != null && !crystal.getTipBlock().isEmpty()); + private static PlatformBlockState resolveTip(Crystal crystal, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { + boolean hasTip = IrisProceduralBlocks.paletteSet(crystal.tipPalette()) + || (crystal.tipBlock() != null && !crystal.tipBlock().isEmpty()); if (hasTip) { - if (tipRng.chance(crystal.getTipChance())) { - PlatformBlockState tip = IrisProceduralBlocks.resolve(crystal.getTipBlock(), crystal.getTipPalette(), data, x, y, z, paletteRng); + if (tipRng.chance(crystal.tipChance())) { + PlatformBlockState tip = IrisProceduralBlocks.resolve(crystal.tipBlock(), crystal.tipPalette(), data, x, y, z, paletteRng); if (tip != null) { return tip; } @@ -97,9 +98,9 @@ public final class CrystalGenerator { return resolveShard(crystal, data, x, y, z, paletteRng); } - if (crystal.isGlow() && crystal.getGlowBlock() != null && !crystal.getGlowBlock().isEmpty()) { - if (tipRng.chance(crystal.getTipChance())) { - PlatformBlockState glow = IrisProceduralBlocks.resolve(crystal.getGlowBlock(), null, data, x, y, z, paletteRng); + if (crystal.glow() && crystal.glowBlock() != null && !crystal.glowBlock().isEmpty()) { + if (tipRng.chance(crystal.tipChance())) { + PlatformBlockState glow = IrisProceduralBlocks.resolve(crystal.glowBlock(), (PaletteSpec) null, data, x, y, z, paletteRng); if (glow != null) { return glow; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java index aa63d4619..00043d8ad 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java @@ -18,13 +18,14 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.engine.object.procedural.crystal.IrisCrystalSurface; +import art.arcane.iris.builtin.objects.crystal.CrystalSurface; + public final class CrystalGeometry { private CrystalGeometry() { } - public static double[] surfaceNormal(IrisCrystalSurface surface) { + public static double[] surfaceNormal(CrystalSurface surface) { return switch (surface) { case FLOOR -> new double[]{0.0, 1.0, 0.0}; case CEILING -> new double[]{0.0, -1.0, 0.0}; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java index c65872317..1515e981f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.engine.object.procedural.crystal.IrisCrystal; -import art.arcane.iris.engine.object.procedural.crystal.IrisCrystalDistribution; +import art.arcane.iris.builtin.objects.crystal.CrystalDistribution; +import art.arcane.iris.builtin.objects.crystal.Crystal; import art.arcane.volmlib.util.math.RNG; public final class CrystalShardBuilder { @@ -28,24 +28,24 @@ public final class CrystalShardBuilder { private CrystalShardBuilder() { } - public static void build(CrystalCanvas canvas, IrisCrystal crystal, RNG rng) { - double[] normal = CrystalGeometry.surfaceNormal(crystal.getGrowthSurface()); + public static void build(CrystalCanvas canvas, Crystal crystal, RNG rng) { + double[] normal = CrystalGeometry.surfaceNormal(crystal.growthSurface()); double[] u = CrystalGeometry.orthonormalBasisU(normal); double[] v = CrystalGeometry.orthonormalBasisV(normal, u); - int countLo = Math.min(crystal.getShardCountMin(), crystal.getShardCountMax()); - int countHi = Math.max(crystal.getShardCountMin(), crystal.getShardCountMax()); + int countLo = Math.min(crystal.shardCountMin(), crystal.shardCountMax()); + int countHi = Math.max(crystal.shardCountMin(), crystal.shardCountMax()); int shardCount = Math.max(1, rng.i(countLo, countHi + 1)); - int lengthLo = Math.min(crystal.getShardLengthMin(), crystal.getShardLengthMax()); - int lengthHi = Math.max(crystal.getShardLengthMin(), crystal.getShardLengthMax()); + int lengthLo = Math.min(crystal.shardLengthMin(), crystal.shardLengthMax()); + int lengthHi = Math.max(crystal.shardLengthMin(), crystal.shardLengthMax()); - double spreadRadians = Math.toRadians(Math.max(0.0, Math.min(90.0, crystal.getSpreadAngle()))); - double jitterAmount = Math.max(0.0, Math.min(1.0, crystal.getJitter())); - double emitRadius = Math.max(0.0, crystal.getBaseRadius() * 0.6); + double spreadRadians = Math.toRadians(Math.max(0.0, Math.min(90.0, crystal.spreadAngle()))); + double jitterAmount = Math.max(0.0, Math.min(1.0, crystal.jitter())); + double emitRadius = Math.max(0.0, crystal.baseRadius() * 0.6); for (int i = 0; i < shardCount; i++) { - double azimuth = azimuth(crystal.getDistribution(), i, rng); + double azimuth = azimuth(crystal.distribution(), i, rng); azimuth += rng.d(-Math.PI, Math.PI) * jitterAmount * 0.5; double cone = spreadRadians * fanFraction(shardCount, i, rng); @@ -63,9 +63,9 @@ public final class CrystalShardBuilder { } } - private static void rasterizeShard(CrystalCanvas canvas, IrisCrystal crystal, double ox, double oy, double oz, double[] direction, int length) { - double baseRadius = Math.max(0.5, crystal.getShardBaseRadius()); - double taper = Math.max(0.0, Math.min(1.0, crystal.getShardTaper())); + private static void rasterizeShard(CrystalCanvas canvas, Crystal crystal, double ox, double oy, double oz, double[] direction, int length) { + double baseRadius = Math.max(0.5, crystal.shardBaseRadius()); + double taper = Math.max(0.0, Math.min(1.0, crystal.shardTaper())); int samples = Math.max(1, length * 3); @@ -108,8 +108,8 @@ public final class CrystalShardBuilder { canvas.set(tipX, tipY, tipZ, CrystalRole.TIP); } - private static double azimuth(IrisCrystalDistribution distribution, int index, RNG rng) { - if (distribution == IrisCrystalDistribution.GOLDEN_ANGLE) { + private static double azimuth(CrystalDistribution distribution, int index, RNG rng) { + if (distribution == CrystalDistribution.GOLDEN_ANGLE) { return Math.toRadians(index * GOLDEN_ANGLE); } return rng.d(0.0, Math.PI * 2.0); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java new file mode 100644 index 000000000..17a62af06 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java @@ -0,0 +1,42 @@ +/* + * 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.procedural.crystal; + +import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.volmlib.util.math.RNG; + +/** A crystal cluster made placeable: its variants are baked by {@link CrystalGenerator}. */ +public final class ResolvedCrystal extends ResolvedProceduralPlacement { + private final Crystal settings; + + public ResolvedCrystal(Crystal settings) { + super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), + settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + this.settings = settings; + } + + @Override + protected IrisObject generate(int index, RNG rng, IrisData data) { + return CrystalGenerator.generate(settings, index, rng, data); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java index 5c97110f3..7ee88de5a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java @@ -18,8 +18,10 @@ package art.arcane.iris.engine.object.procedural.formation; +import com.volmit.block.PaletteSpec; +import java.util.Optional; +import art.arcane.iris.builtin.objects.formation.Formation; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.procedural.formation.IrisFormation; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; @@ -30,37 +32,37 @@ public final class FormationBlockResolver { private FormationBlockResolver() { } - public static PlatformBlockState resolve(IrisFormation f, IrisData data, FormationCanvas.Role role, Vector3i raw) { + public static PlatformBlockState resolve(Formation f, IrisData data, FormationCanvas.Role role, Vector3i raw) { int x = raw.getBlockX(); int y = raw.getBlockY(); int z = raw.getBlockZ(); - RNG paletteRng = new RNG(f.getSeed()); + RNG paletteRng = new RNG(f.seed()); if (role == FormationCanvas.Role.CAP && capDefined(f)) { - PlatformBlockState cap = IrisProceduralBlocks.resolve(f.getCapBlock(), f.getCapPalette(), data, x, y, z, paletteRng); + PlatformBlockState cap = IrisProceduralBlocks.resolve(f.capBlock(), f.capPalette(), data, x, y, z, paletteRng); if (cap != null) { return cap; } } if (strataDefined(f)) { - IrisMaterialPalette strata = f.getStrataPalette(); - int thickness = Math.max(1, f.getStrataThickness()); + PaletteSpec strata = f.strataPalette().orElseThrow(); + int thickness = Math.max(1, f.strataThickness()); int band = Math.floorDiv(y, thickness); - PlatformBlockState strataState = strata.get(new RNG(f.getSeed() + (band * 31L)), x, band, z, data); + PlatformBlockState strataState = IrisProceduralBlocks.pick(strata, data, f.seed() + (band * 31L), x, band, z); if (strataState != null) { return strataState; } } - return IrisProceduralBlocks.resolve(f.getBlock(), f.getBlockPalette(), data, x, y, z, paletteRng); + return IrisProceduralBlocks.resolve(f.block(), f.blockPalette(), data, x, y, z, paletteRng); } - private static boolean capDefined(IrisFormation f) { - return IrisProceduralBlocks.paletteSet(f.getCapPalette()) || (f.getCapBlock() != null && !f.getCapBlock().isEmpty()); + private static boolean capDefined(Formation f) { + return IrisProceduralBlocks.paletteSet(f.capPalette()) || f.capBlock().filter(block -> !block.isEmpty()).isPresent(); } - private static boolean strataDefined(IrisFormation f) { - return IrisProceduralBlocks.paletteSet(f.getStrataPalette()); + private static boolean strataDefined(Formation f) { + return IrisProceduralBlocks.paletteSet(f.strataPalette()); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java index bebb43360..8d2d5c79e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.formation; +import art.arcane.iris.builtin.objects.formation.Formation; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.procedural.formation.IrisFormation; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; @@ -33,18 +33,18 @@ public final class FormationGenerator { private FormationGenerator() { } - public static IrisObject generate(IrisFormation f, int variantIndex, RNG rng, IrisData data) { - int lo = Math.min(f.getHeightMin(), f.getHeightMax()); - int hi = Math.max(f.getHeightMin(), f.getHeightMax()); + public static IrisObject generate(Formation f, int variantIndex, RNG rng, IrisData data) { + int lo = Math.min(f.heightMin(), f.heightMax()); + int hi = Math.max(f.heightMin(), f.heightMax()); int height = Math.max(3, rng.i(lo, hi + 1)); - int wLo = Math.min(f.getBaseWidthMin(), f.getBaseWidthMax()); - int wHi = Math.max(f.getBaseWidthMin(), f.getBaseWidthMax()); + int wLo = Math.min(f.baseWidthMin(), f.baseWidthMax()); + int wHi = Math.max(f.baseWidthMin(), f.baseWidthMax()); double baseRadius = Math.max(1, rng.i(wLo, wHi + 1)); FormationCanvas canvas = new FormationCanvas(); - switch (f.getForm()) { + switch (f.form()) { case SPIRE -> FormationShapeBuilder.spire(canvas, f, height, baseRadius, rng); case HOODOO -> FormationShapeBuilder.hoodoo(canvas, f, height, baseRadius, rng); case ARCH -> FormationShapeBuilder.arch(canvas, f, height, baseRadius, rng); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java index d6edb576c..bc857176d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java @@ -18,15 +18,16 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.engine.object.procedural.formation.IrisFormation; +import art.arcane.iris.builtin.objects.formation.Formation; + public final class FormationProfiles { private FormationProfiles() { } - public static double radiusAt(IrisFormation f, double baseRadius, double topRadius, double t) { + public static double radiusAt(Formation f, double baseRadius, double topRadius, double t) { double clamped = Math.max(0.0, Math.min(1.0, t)); - return switch (f.getProfile()) { + return switch (f.profile()) { case CONSTANT -> baseRadius; case LINEAR -> baseRadius + (topRadius - baseRadius) * clamped; case TAPER -> baseRadius + (topRadius - baseRadius) * smoothstep(clamped); @@ -35,9 +36,9 @@ public final class FormationProfiles { }; } - private static double parabolic(IrisFormation f, double baseRadius, double topRadius, double t) { - double waist = Math.max(0.0, Math.min(1.0, f.getProfileWaist())); - double floor = Math.max(0.0, Math.min(1.0, f.getProfileWaistFloor())); + private static double parabolic(Formation f, double baseRadius, double topRadius, double t) { + double waist = Math.max(0.0, Math.min(1.0, f.profileWaist())); + double floor = Math.max(0.0, Math.min(1.0, f.profileWaistFloor())); double denom = Math.pow(Math.max(waist, 1.0 - waist), 2); if (denom == 0) { denom = 1; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java index edae9a400..bc2f78893 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.engine.object.procedural.formation.IrisFormation; +import art.arcane.iris.builtin.objects.formation.Formation; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.iris.util.common.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -30,11 +30,11 @@ public final class FormationShapeBuilder { private FormationShapeBuilder() { } - public static void spire(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { - double topRadius = f.getTopWidth(); + public static void spire(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { + double topRadius = f.topWidth(); column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, true); - double lean = Math.toRadians(f.getLean()); - double azimuth = Math.toRadians(f.getLeanAzimuth()); + double lean = Math.toRadians(f.lean()); + double azimuth = Math.toRadians(f.leanAzimuth()); int previousX = 0; int previousZ = 0; for (int y = 0; y < height; y++) { @@ -53,25 +53,25 @@ public final class FormationShapeBuilder { } } - public static void seaStack(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + public static void seaStack(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { double topRadius = Math.max(1.0, baseRadius * 0.55); - if (f.getTopWidth() > 0) { - topRadius = f.getTopWidth(); + if (f.topWidth() > 0) { + topRadius = f.topWidth(); } column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, true); } - public static void hoodoo(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { - double topRadius = f.getTopWidth() > 0 ? f.getTopWidth() : Math.max(1.0, baseRadius * 0.7); + public static void hoodoo(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { + double topRadius = f.topWidth() > 0 ? f.topWidth() : Math.max(1.0, baseRadius * 0.7); column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, false); - int capRadius = f.getHoodooCapRadius(); + int capRadius = f.hoodooCapRadius(); if (capRadius <= 0) { return; } - int capHeight = Math.max(1, f.getHoodooCapHeight()); - double lean = Math.toRadians(f.getLean()); - double azimuth = Math.toRadians(f.getLeanAzimuth()); + int capHeight = Math.max(1, f.hoodooCapHeight()); + double lean = Math.toRadians(f.lean()); + double azimuth = Math.toRadians(f.leanAzimuth()); double shear = Math.tan(lean) * height; double topOffX = Math.cos(azimuth) * shear; double topOffZ = Math.sin(azimuth) * shear; @@ -85,12 +85,12 @@ public final class FormationShapeBuilder { } } - public static void boulder(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + public static void boulder(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { double rx = baseRadius; double ry = Math.max(2.0, height * 0.5); double rz = baseRadius * (0.8 + rng.d(0.0, 0.3)); - double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); - long noiseSeed = f.getSeed() + 4201L; + double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); + long noiseSeed = f.seed() + 4201L; int maxR = (int) Math.ceil(Math.max(rx, Math.max(ry, rz))) + 2; for (int x = -maxR; x <= maxR; x++) { @@ -109,10 +109,10 @@ public final class FormationShapeBuilder { } } - public static void arch(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { - double span = Math.max(2.0, f.getArchSpan()); - double tubeRadius = Math.max(0.75, f.getArchThickness() * 0.5); - double asymmetry = Math.max(0.0, Math.min(1.0, f.getArchAsymmetry())); + public static void arch(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { + double span = Math.max(2.0, f.archSpan()); + double tubeRadius = Math.max(0.75, f.archThickness() * 0.5); + double asymmetry = Math.max(0.0, Math.min(1.0, f.archAsymmetry())); double leftFootX = -span * 0.5 - tubeRadius - rng.d(0.0, span * 0.16) * asymmetry; double rightFootX = span * 0.5 + tubeRadius + rng.d(0.0, span * 0.16) * asymmetry; double leftFootZ = rng.d(-tubeRadius * 0.45, tubeRadius * 0.45) * asymmetry; @@ -164,10 +164,10 @@ public final class FormationShapeBuilder { } } - public static void basaltColumns(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { - int count = Math.max(2, f.getBasaltColumns()); - int colRadius = Math.max(1, f.getBasaltColumnRadius()); - double variance = Math.max(0.0, Math.min(1.0, f.getBasaltHeightVariance())); + public static void basaltColumns(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { + int count = Math.max(2, f.basaltColumns()); + int colRadius = Math.max(1, f.basaltColumnRadius()); + double variance = Math.max(0.0, Math.min(1.0, f.basaltHeightVariance())); int spread = (int) Math.ceil(baseRadius); for (int c = 0; c < count; c++) { @@ -194,14 +194,14 @@ public final class FormationShapeBuilder { } } - public static void iceberg(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + public static void iceberg(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { long noiseSeed = rng.nextLong(); double bodyHeight = Math.max(2.0, height * 0.42); double radiusX = baseRadius * rng.d(1.15, 1.5); double radiusZ = baseRadius * rng.d(1.0, 1.35); - ellipsoid(canvas, radiusX, bodyHeight, radiusZ, bodyHeight * 0.36, noiseSeed, f.getRoughness()); + ellipsoid(canvas, radiusX, bodyHeight, radiusZ, bodyHeight * 0.36, noiseSeed, f.roughness()); - int peaks = Math.max(1, f.getIcebergPeaks()); + int peaks = Math.max(1, f.icebergPeaks()); double phase = rng.d(0.0, Math.PI * 2.0); for (int i = 0; i < peaks; i++) { double angle = phase + (Math.PI * 2.0 * i / peaks) + rng.d(-0.35, 0.35); @@ -215,9 +215,9 @@ public final class FormationShapeBuilder { } } - public static void fissure(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { - int count = Math.max(2, f.getFractureCount()); - double separation = Math.max(1.0, f.getFractureSeparation()); + public static void fissure(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { + int count = Math.max(2, f.fractureCount()); + double separation = Math.max(1.0, f.fractureSeparation()); double shardRadius = Math.max(1.0, baseRadius / Math.max(1.6, count * 0.72)); double phase = rng.d(0.0, Math.PI * 2.0); @@ -233,11 +233,11 @@ public final class FormationShapeBuilder { } } - public static void spiral(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + public static void spiral(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { int steps = Math.max(12, height * 4); - double turns = Math.max(0.25, f.getSpiralTurns()); - double startRadius = Math.max(1.0, f.getSpiralRadius()); - double startThickness = Math.max(1.0, f.getSpiralThickness()); + double turns = Math.max(0.25, f.spiralTurns()); + double startRadius = Math.max(1.0, f.spiralRadius()); + double startThickness = Math.max(1.0, f.spiralThickness()); double phase = rng.d(0.0, Math.PI * 2.0); long noiseSeed = rng.nextLong(); @@ -257,11 +257,11 @@ public final class FormationShapeBuilder { (int) Math.round(Math.sin(phase) * startRadius), footRadius, false, rng); } - public static void overhang(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, RNG rng) { + public static void overhang(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { int steps = Math.max(12, height * 4); - double reach = Math.max(1.0, f.getOverhangReach()); - double drop = Math.max(0.0, f.getOverhangDrop()); - double phase = Math.toRadians(f.getLeanAzimuth()) + rng.d(-0.18, 0.18); + double reach = Math.max(1.0, f.overhangReach()); + double drop = Math.max(0.0, f.overhangDrop()); + double phase = Math.toRadians(f.leanAzimuth()) + rng.d(-0.18, 0.18); double trunkHeight = Math.max(3.0, height * 0.62); long noiseSeed = rng.nextLong(); @@ -285,12 +285,12 @@ public final class FormationShapeBuilder { } } - private static void column(FormationCanvas canvas, IrisFormation f, int height, double baseRadius, double topRadius, int extraBaseX, int extraBaseZ, RNG rng, boolean capTop) { - double lean = Math.toRadians(f.getLean()); - double azimuth = Math.toRadians(f.getLeanAzimuth()); - double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); - double jitter = Math.max(0.0, Math.min(1.0, f.getJitter())); - long noiseSeed = f.getSeed() + 9001L; + private static void column(FormationCanvas canvas, Formation f, int height, double baseRadius, double topRadius, int extraBaseX, int extraBaseZ, RNG rng, boolean capTop) { + double lean = Math.toRadians(f.lean()); + double azimuth = Math.toRadians(f.leanAzimuth()); + double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); + double jitter = Math.max(0.0, Math.min(1.0, f.jitter())); + long noiseSeed = f.seed() + 9001L; for (int y = 0; y < height; y++) { double t = height <= 1 ? 1.0 : (y / (double) (height - 1)); @@ -311,7 +311,7 @@ public final class FormationShapeBuilder { } } - private static void ringDisc(FormationCanvas canvas, IrisFormation f, int cx, int y, int cz, double radius, double roughness, double jitter, long noiseSeed, boolean cap, RNG rng) { + private static void ringDisc(FormationCanvas canvas, Formation f, int cx, int y, int cz, double radius, double roughness, double jitter, long noiseSeed, boolean cap, RNG rng) { int r = (int) Math.ceil(radius) + 1; for (int x = -r; x <= r; x++) { for (int z = -r; z <= r; z++) { @@ -332,7 +332,7 @@ public final class FormationShapeBuilder { } } - private static void disc(FormationCanvas canvas, IrisFormation f, int cx, int y, int cz, double radius, boolean cap, RNG rng) { + private static void disc(FormationCanvas canvas, Formation f, int cx, int y, int cz, double radius, boolean cap, RNG rng) { int r = (int) Math.ceil(radius) + 1; for (int x = -r; x <= r; x++) { for (int z = -r; z <= r; z++) { @@ -347,11 +347,11 @@ public final class FormationShapeBuilder { } } - private static void taperedPeak(FormationCanvas canvas, IrisFormation f, int height, double radius, + private static void taperedPeak(FormationCanvas canvas, Formation f, int height, double radius, int offsetX, int offsetZ, double leanAngle, double leanDistance, RNG rng) { long noiseSeed = rng.nextLong(); - double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); - double jitter = Math.max(0.0, Math.min(1.0, f.getJitter())); + double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); + double jitter = Math.max(0.0, Math.min(1.0, f.jitter())); for (int y = 0; y < height; y++) { double t = height <= 1 ? 1.0 : y / (double) (height - 1); int x = offsetX + (int) Math.round(Math.cos(leanAngle) * leanDistance * t * t); @@ -383,11 +383,11 @@ public final class FormationShapeBuilder { } } - private static void ball(FormationCanvas canvas, IrisFormation f, int centerX, int centerY, int centerZ, + private static void ball(FormationCanvas canvas, Formation f, int centerX, int centerY, int centerZ, double radius, boolean cap, long noiseSeed, RNG rng) { int extent = (int) Math.ceil(radius); - double roughness = Math.max(0.0, Math.min(1.0, f.getRoughness())); - double jitter = Math.max(0.0, Math.min(1.0, f.getJitter())); + double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); + double jitter = Math.max(0.0, Math.min(1.0, f.jitter())); for (int x = -extent; x <= extent; x++) { for (int y = -extent; y <= extent; y++) { for (int z = -extent; z <= extent; z++) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java new file mode 100644 index 000000000..6c4b0dcd3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java @@ -0,0 +1,48 @@ +/* + * 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.procedural.formation; + +import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.volmlib.util.math.RNG; + +/** A rock formation made placeable: its variants are baked by {@link FormationGenerator}. */ +public final class ResolvedFormation extends ResolvedProceduralPlacement { + private final Formation settings; + + public ResolvedFormation(Formation settings) { + super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), + settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + this.settings = settings; + } + + @Override + protected void customize(IrisObjectPlacement placement) { + placement.setSurfaceSupportBuffer(settings.surfaceSupportBuffer()); + } + + @Override + protected IrisObject generate(int index, RNG rng, IrisData data) { + return FormationGenerator.generate(settings, index, rng, data); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java index 2c0f95362..460e0cc7a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java @@ -18,8 +18,10 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; -import art.arcane.iris.engine.object.procedural.fungi.IrisFungusCapShape; +import com.volmit.block.PaletteSpec; +import java.util.Optional; +import art.arcane.iris.builtin.objects.fungi.FungusCapShape; +import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; @@ -31,17 +33,17 @@ public final class FungusCapBuilder { private FungusCapBuilder() { } - public static void build(Map roles, IrisFungus fungus, int baseRadius, double cx, int baseY, double cz, long seed) { - int radius = (int) Math.round(baseRadius + Math.max(0.0, fungus.getCapOverhang())); - int thickness = Math.max(1, Math.min(3, fungus.getCapThickness())); - double squish = Math.max(0.0, Math.min(1.0, fungus.getCapSquish())); - double droop = Math.max(0.0, fungus.getCapDroop()); - IrisFungusCapShape shape = fungus.getCapShape() == null ? IrisFungusCapShape.DOME : fungus.getCapShape(); + public static void build(Map roles, Fungus fungus, int baseRadius, double cx, int baseY, double cz, long seed) { + int radius = (int) Math.round(baseRadius + Math.max(0.0, fungus.capOverhang())); + int thickness = Math.max(1, Math.min(3, fungus.capThickness())); + double squish = Math.max(0.0, Math.min(1.0, fungus.capSquish())); + double droop = Math.max(0.0, fungus.capDroop()); + FungusCapShape shape = fungus.capShape() == null ? FungusCapShape.DOME : fungus.capShape(); int icx = (int) Math.round(cx); int icz = (int) Math.round(cz); - boolean hasGill = blockOrPaletteSet(fungus.getGillBlock(), fungus.getGillPalette()); - boolean hasSpot = blockOrPaletteSet(fungus.getSpotBlock(), fungus.getSpotPalette()); + boolean hasGill = blockOrPaletteSet(fungus.gillBlock(), fungus.gillPalette()); + boolean hasSpot = blockOrPaletteSet(fungus.spotBlock(), fungus.spotPalette()); double apexRise = apexRise(shape, radius) * (1.0 - 0.6 * squish); double droopReach = Math.tan(Math.toRadians(droop)) * radius; @@ -68,9 +70,9 @@ public final class FungusCapBuilder { boolean underside = layer == thickness - 1; boolean topFace = layer == 0; - if (underside && hasGill && rollNoise(icx + dx, y, icz + dz, seed + 4111L) <= fungus.getGillChance()) { + if (underside && hasGill && rollNoise(icx + dx, y, icz + dz, seed + 4111L) <= fungus.gillChance()) { role = FungusCellRole.GILL; - } else if (topFace && hasSpot && spotNoise(icx + dx, y, icz + dz, seed + 9311L) <= fungus.getSpotChance()) { + } else if (topFace && hasSpot && spotNoise(icx + dx, y, icz + dz, seed + 9311L) <= fungus.spotChance()) { role = FungusCellRole.SPOT; } @@ -80,7 +82,7 @@ public final class FungusCapBuilder { } } - private static double apexRise(IrisFungusCapShape shape, int radius) { + private static double apexRise(FungusCapShape shape, int radius) { return switch (shape) { case DOME -> radius * 0.85; case CONICAL -> radius * 1.4; @@ -90,7 +92,7 @@ public final class FungusCapBuilder { }; } - private static double capSurface(IrisFungusCapShape shape, double normalized, double apexRise) { + private static double capSurface(FungusCapShape shape, double normalized, double apexRise) { double n = Math.max(0.0, Math.min(1.0, normalized)); return switch (shape) { case DOME -> apexRise * Math.sqrt(Math.max(0.0, 1.0 - n * n)); @@ -109,10 +111,10 @@ public final class FungusCapBuilder { return TreeFunctions.valueNoise3D(Math.floorDiv(x, 2), y, Math.floorDiv(z, 2), seed); } - static boolean blockOrPaletteSet(String block, IrisMaterialPalette palette) { + static boolean blockOrPaletteSet(Optional block, Optional palette) { if (IrisProceduralBlocks.paletteSet(palette)) { return true; } - return block != null && !block.isEmpty(); + return block.filter(name -> !name.isEmpty()).isPresent(); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java index 25f9d673c..293c116f0 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.fungi; +import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; @@ -33,11 +33,11 @@ public final class FungusGenerator { private FungusGenerator() { } - public static IrisObject generate(IrisFungus fungus, int height, RNG rng, IrisData data) { + public static IrisObject generate(Fungus fungus, int height, RNG rng, IrisData data) { Map roles = new HashMap<>(); long baseSeed = rng.getSeed(); - if (fungus.isShelf()) { + if (fungus.shelf()) { FungusShelfBuilder.build(roles, fungus, rng, baseSeed); } else { buildUpright(roles, fungus, height, rng, baseSeed); @@ -47,7 +47,7 @@ public final class FungusGenerator { return null; } - RNG paletteRng = new RNG(fungus.getSeed()); + RNG paletteRng = new RNG(fungus.seed()); Map resolved = new HashMap<>(); for (Map.Entry entry : roles.entrySet()) { Vector3i pos = entry.getKey(); @@ -61,7 +61,7 @@ public final class FungusGenerator { return IrisProceduralBlocks.assemble(resolved); } - private static void buildUpright(Map roles, IrisFungus fungus, int height, RNG rng, long baseSeed) { + private static void buildUpright(Map roles, Fungus fungus, int height, RNG rng, long baseSeed) { int stemHeight = Math.max(1, height); Map stemCells = new HashMap<>(); double[] top = FungusStemBuilder.build(stemCells, fungus, stemHeight, baseSeed); @@ -76,28 +76,28 @@ public final class FungusGenerator { FungusCapBuilder.build(roles, fungus, radius, cx, capBaseY, cz, baseSeed + 5557L); } - private static int pickRadius(IrisFungus fungus, RNG rng) { - int lo = Math.min(fungus.getCapRadiusMin(), fungus.getCapRadiusMax()); - int hi = Math.max(fungus.getCapRadiusMin(), fungus.getCapRadiusMax()); + private static int pickRadius(Fungus fungus, RNG rng) { + int lo = Math.min(fungus.capRadiusMin(), fungus.capRadiusMax()); + int hi = Math.max(fungus.capRadiusMin(), fungus.capRadiusMax()); lo = Math.max(1, lo); hi = Math.max(lo, hi); return rng.i(lo, hi + 1); } - private static PlatformBlockState resolveRole(IrisFungus fungus, FungusCellRole role, IrisData data, Vector3i pos, RNG paletteRng) { + private static PlatformBlockState resolveRole(Fungus fungus, FungusCellRole role, IrisData data, Vector3i pos, RNG paletteRng) { int x = pos.getBlockX(); int y = pos.getBlockY(); int z = pos.getBlockZ(); return switch (role) { - case STEM -> IrisProceduralBlocks.resolve(fungus.getStem(), fungus.getStemPalette(), data, x, y, z, paletteRng); - case CAP -> IrisProceduralBlocks.resolve(fungus.getCap(), fungus.getCapPalette(), data, x, y, z, paletteRng); + case STEM -> IrisProceduralBlocks.resolve(fungus.stem(), fungus.stemPalette(), data, x, y, z, paletteRng); + case CAP -> IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), data, x, y, z, paletteRng); case GILL -> { - PlatformBlockState gill = IrisProceduralBlocks.resolve(fungus.getGillBlock(), fungus.getGillPalette(), data, x, y, z, paletteRng); - yield gill != null ? gill : IrisProceduralBlocks.resolve(fungus.getCap(), fungus.getCapPalette(), data, x, y, z, paletteRng); + PlatformBlockState gill = IrisProceduralBlocks.resolve(fungus.gillBlock(), fungus.gillPalette(), data, x, y, z, paletteRng); + yield gill != null ? gill : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), data, x, y, z, paletteRng); } case SPOT -> { - PlatformBlockState spot = IrisProceduralBlocks.resolve(fungus.getSpotBlock(), fungus.getSpotPalette(), data, x, y, z, paletteRng); - yield spot != null ? spot : IrisProceduralBlocks.resolve(fungus.getCap(), fungus.getCapPalette(), data, x, y, z, paletteRng); + PlatformBlockState spot = IrisProceduralBlocks.resolve(fungus.spotBlock(), fungus.spotPalette(), data, x, y, z, paletteRng); + yield spot != null ? spot : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), data, x, y, z, paletteRng); } }; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java index 9b10d7aa5..2e34768d5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.iris.util.common.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -29,20 +29,20 @@ public final class FungusShelfBuilder { private FungusShelfBuilder() { } - public static void build(Map roles, IrisFungus fungus, RNG rng, long seed) { - int radius = Math.max(1, fungus.getShelfRadius()); + public static void build(Map roles, Fungus fungus, RNG rng, long seed) { + int radius = Math.max(1, fungus.shelfRadius()); double azimuth = rng.d(0.0, Math.PI * 2.0); double fanX = Math.sin(azimuth); double fanZ = Math.cos(azimuth); - int stubHeight = Math.max(0, Math.min(2, fungus.getStemWidth())); + int stubHeight = Math.max(0, Math.min(2, fungus.stemWidth())); for (int y = 0; y < stubHeight; y++) { roles.put(new Vector3i(0, y, 0), FungusCellRole.STEM); } int fanY = stubHeight; - boolean hasGill = FungusCapBuilder.blockOrPaletteSet(fungus.getGillBlock(), fungus.getGillPalette()); - boolean hasSpot = FungusCapBuilder.blockOrPaletteSet(fungus.getSpotBlock(), fungus.getSpotPalette()); + boolean hasGill = FungusCapBuilder.blockOrPaletteSet(fungus.gillBlock(), fungus.gillPalette()); + boolean hasSpot = FungusCapBuilder.blockOrPaletteSet(fungus.spotBlock(), fungus.spotPalette()); for (int dx = -radius; dx <= radius; dx++) { for (int dz = -radius; dz <= radius; dz++) { @@ -59,12 +59,12 @@ public final class FungusShelfBuilder { int y = fanY + lift; FungusCellRole role = FungusCellRole.CAP; - if (hasSpot && spotNoise(dx, y, dz, seed + 9311L) <= fungus.getSpotChance()) { + if (hasSpot && spotNoise(dx, y, dz, seed + 9311L) <= fungus.spotChance()) { role = FungusCellRole.SPOT; } roles.putIfAbsent(new Vector3i(dx, y, dz), role); - if (hasGill && rollNoise(dx, y - 1, dz, seed + 4111L) <= fungus.getGillChance()) { + if (hasGill && rollNoise(dx, y - 1, dz, seed + 4111L) <= fungus.gillChance()) { roles.putIfAbsent(new Vector3i(dx, y - 1, dz), FungusCellRole.GILL); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java index 397abfb52..4f82f80a7 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.engine.object.procedural.fungi.IrisFungus; +import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.math.Vector3i; @@ -29,15 +29,15 @@ public final class FungusStemBuilder { private FungusStemBuilder() { } - public static double[] build(Map stemCells, IrisFungus fungus, int stemHeight, long seed) { - int width = Math.max(1, Math.min(3, fungus.getStemWidth())); - double maxLean = stemHeight * Math.tan(Math.toRadians(Math.max(0.0, fungus.getStemCurve()))); - double leanRad = Math.toRadians(fungus.getStemLeanAzimuth()); + public static double[] build(Map stemCells, Fungus fungus, int stemHeight, long seed) { + int width = Math.max(1, Math.min(3, fungus.stemWidth())); + double maxLean = stemHeight * Math.tan(Math.toRadians(Math.max(0.0, fungus.stemCurve()))); + double leanRad = Math.toRadians(fungus.stemLeanAzimuth()); double leanX = Math.sin(leanRad); double leanZ = Math.cos(leanRad); - double waveAmp = Math.max(0.0, fungus.getStemWaveAmplitude()); - double wavePeriods = fungus.getStemWavePeriods() == 0 ? 1.0 : fungus.getStemWavePeriods(); - double waveAzimuth = Math.toRadians(fungus.getStemLeanAzimuth() + 90.0); + double waveAmp = Math.max(0.0, fungus.stemWaveAmplitude()); + double wavePeriods = fungus.stemWavePeriods() == 0 ? 1.0 : fungus.stemWavePeriods(); + double waveAzimuth = Math.toRadians(fungus.stemLeanAzimuth() + 90.0); double waveX = Math.sin(waveAzimuth); double waveZ = Math.cos(waveAzimuth); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java new file mode 100644 index 000000000..fd8ca1209 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java @@ -0,0 +1,74 @@ +/* + * 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.procedural.fungi; + +import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +/** A fungus made placeable: its variants are baked by {@link FungusGenerator}. */ +public final class ResolvedFungus extends ResolvedProceduralPlacement { + private final Fungus settings; + + public ResolvedFungus(Fungus settings) { + super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), + settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + this.settings = settings; + } + + @Override + protected IrisObject generate(int index, RNG rng, IrisData data) { + throw new UnsupportedOperationException("A fungus bakes its variants itself, from the stem heights"); + } + + @Override + protected KList bake(IrisData data) { + KList baked = new KList<>(); + int count = variantCount(); + int lo = Math.min(settings.stemHeightMin(), settings.stemHeightMax()); + int hi = Math.max(settings.stemHeightMin(), settings.stemHeightMax()); + RNG heightRng = new RNG(seed()); + + for (int i = 0; i < count; i++) { + int height; + if (count == 1 || lo == hi) { + height = heightRng.i(lo, hi + 1); + } else { + double step = (hi - lo) / (double) (count - 1); + double base = lo + step * i; + double jitter = heightRng.d(-step * 0.3, step * 0.3); + height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); + } + + IrisObject object = FungusGenerator.generate(settings, Math.max(1, height), variantRng(i), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey("procedural/" + getName() + "#" + i); + object.setLoader(data); + baked.add(object); + } + + return baked; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java new file mode 100644 index 000000000..48b464512 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java @@ -0,0 +1,42 @@ +/* + * 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.procedural.ruin; + +import art.arcane.iris.builtin.objects.ruin.Ruin; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.volmlib.util.math.RNG; + +/** A ruin made placeable: its variants are baked by {@link RuinGenerator}. */ +public final class ResolvedRuin extends ResolvedProceduralPlacement { + private final Ruin settings; + + public ResolvedRuin(Ruin settings) { + super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), + settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + this.settings = settings; + } + + @Override + protected IrisObject generate(int index, RNG rng, IrisData data) { + return RuinGenerator.generate(settings, index, rng, data); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java index 430d04683..a42d2a437 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.procedural.ruin; +import art.arcane.iris.builtin.objects.ruin.RuinDecorator; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.engine.object.procedural.ruin.IrisRuinDecorator; import art.arcane.iris.util.common.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -36,19 +36,19 @@ final class RuinDecoratorApplier { private RuinDecoratorApplier() { } - static void apply(RuinBlockCanvas canvas, IrisRuinDecorator decorator, IrisData data, long seed, RNG rng) { - List candidates = switch (decorator.getTarget()) { + static void apply(RuinBlockCanvas canvas, RuinDecorator decorator, IrisData data, long seed, RNG rng) { + List candidates = switch (decorator.target()) { case TOP -> topCandidates(canvas); case SURFACE -> surfaceCandidates(canvas); - case BASE_SCATTER -> baseScatterCandidates(canvas, Math.max(1, decorator.getScatterRadius())); + case BASE_SCATTER -> baseScatterCandidates(canvas, Math.max(1, decorator.scatterRadius())); }; RNG paletteRng = new RNG(seed); for (Vector3i v : candidates) { - if (!rng.chance(decorator.getChance())) { + if (!rng.chance(decorator.chance())) { continue; } - PlatformBlockState bd = IrisProceduralBlocks.resolve(decorator.getBlock(), decorator.getPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + PlatformBlockState bd = IrisProceduralBlocks.resolve(decorator.block(), decorator.palette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); if (bd != null) { canvas.accent(v.getBlockX(), v.getBlockY(), v.getBlockZ(), bd); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java index ea65ecd9f..b523bb2b8 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java @@ -18,11 +18,12 @@ package art.arcane.iris.engine.object.procedural.ruin; +import art.arcane.iris.builtin.objects.ruin.RuinDecorator; +import art.arcane.iris.builtin.objects.ruin.Ruin; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.engine.object.procedural.ruin.IrisRuin; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.iris.util.common.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -36,14 +37,14 @@ public final class RuinGenerator { private RuinGenerator() { } - public static IrisObject generate(IrisRuin ruin, int variantIndex, RNG rng, IrisData data) { - int count = Math.max(1, ruin.getVariants()); - int height = pick(ruin.getHeightMin(), ruin.getHeightMax(), variantIndex, count, rng); - int width = pick(ruin.getWidthMin(), ruin.getWidthMax(), variantIndex, count, rng); - int length = pick(ruin.getLengthMin(), ruin.getLengthMax(), variantIndex, count, rng); + public static IrisObject generate(Ruin ruin, int variantIndex, RNG rng, IrisData data) { + int count = Math.max(1, ruin.variants()); + int height = pick(ruin.heightMin(), ruin.heightMax(), variantIndex, count, rng); + int width = pick(ruin.widthMin(), ruin.widthMax(), variantIndex, count, rng); + int length = pick(ruin.lengthMin(), ruin.lengthMax(), variantIndex, count, rng); RuinBlockCanvas canvas = new RuinBlockCanvas(); - switch (ruin.getForm()) { + switch (ruin.form()) { case PILLAR -> RuinShapes.pillar(canvas, Math.max(1, width), Math.max(2, height), rng); case WALL -> RuinShapes.wall(canvas, Math.max(1, width), Math.max(2, length), Math.max(2, height), rng); case ARCH -> RuinShapes.arch(canvas, Math.max(1, width), Math.max(3, length), Math.max(3, height), rng); @@ -70,8 +71,8 @@ public final class RuinGenerator { return (int) Math.round(Math.max(min, Math.min(max, base + jitter))); } - private static void applyBurial(IrisRuin ruin, RuinBlockCanvas canvas, int height) { - double fraction = clamp01(ruin.getBuriedFraction()); + private static void applyBurial(Ruin ruin, RuinBlockCanvas canvas, int height) { + double fraction = clamp01(ruin.buriedFraction()); if (fraction <= 0.0) { return; } @@ -88,13 +89,13 @@ public final class RuinGenerator { canvas.cells().putAll(moved); } - private static void applyErosion(IrisRuin ruin, RuinBlockCanvas canvas) { - double erosion = clamp01(ruin.getErosion()); + private static void applyErosion(Ruin ruin, RuinBlockCanvas canvas) { + double erosion = clamp01(ruin.erosion()); if (erosion <= 0.0) { return; } - double scale = Math.max(0.0001, ruin.getErosionScale()); - long erosionSeed = ruin.getSeed() * 0x2545F4914F6CDD1DL + 17L; + double scale = Math.max(0.0001, ruin.erosionScale()); + long erosionSeed = ruin.seed() * 0x2545F4914F6CDD1DL + 17L; int minY = Integer.MAX_VALUE; for (Vector3i v : canvas.cells().keySet()) { minY = Math.min(minY, v.getBlockY()); @@ -120,25 +121,25 @@ public final class RuinGenerator { } } - private static void applyAccents(IrisRuin ruin, RuinBlockCanvas canvas, RNG rng, IrisData data) { - if (ruin.getAccents() == null || ruin.getAccents().isEmpty()) { + private static void applyAccents(Ruin ruin, RuinBlockCanvas canvas, RNG rng, IrisData data) { + if (ruin.accents() == null || ruin.accents().isEmpty()) { return; } int decoratorIndex = 0; - for (art.arcane.iris.engine.object.procedural.ruin.IrisRuinDecorator decorator : ruin.getAccents()) { - RuinDecoratorApplier.apply(canvas, decorator, data, ruin.getSeed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); + for (art.arcane.iris.builtin.objects.ruin.RuinDecorator decorator : ruin.accents()) { + RuinDecoratorApplier.apply(canvas, decorator, data, ruin.seed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); decoratorIndex++; } } - private static IrisObject resolve(IrisRuin ruin, RuinBlockCanvas canvas, IrisData data) { + private static IrisObject resolve(Ruin ruin, RuinBlockCanvas canvas, IrisData data) { if (canvas.cells().isEmpty()) { return null; } - double scale = Math.max(0.0001, ruin.getWeatheringScale()); - double mossiness = clamp01(ruin.getMossiness()); - long weatherSeed = ruin.getSeed() * 0x9E3779B97F4A7C15L + 101L; - RNG paletteRng = new RNG(ruin.getSeed()); + double scale = Math.max(0.0001, ruin.weatheringScale()); + double mossiness = clamp01(ruin.mossiness()); + long weatherSeed = ruin.seed() * 0x9E3779B97F4A7C15L + 101L; + RNG paletteRng = new RNG(ruin.seed()); int minY = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; @@ -166,7 +167,7 @@ public final class RuinGenerator { return IrisProceduralBlocks.assemble(blocks); } - private static PlatformBlockState structuralBlock(IrisRuin ruin, RuinBlockCanvas.Cell cell, Vector3i v, IrisData data, RNG paletteRng, double scale, double mossiness, long weatherSeed, int minY, int span) { + private static PlatformBlockState structuralBlock(Ruin ruin, RuinBlockCanvas.Cell cell, Vector3i v, IrisData data, RNG paletteRng, double scale, double mossiness, long weatherSeed, int minY, int span) { boolean weathered = false; if (mossiness > 0.0) { int sx = (int) Math.round(v.getBlockX() * scale); @@ -179,12 +180,12 @@ public final class RuinGenerator { } if (weathered) { - PlatformBlockState wd = IrisProceduralBlocks.resolve(ruin.getWeatheredBlock(), ruin.getWeatheringPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + PlatformBlockState wd = IrisProceduralBlocks.resolve(ruin.weatheredBlock(), ruin.weatheringPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); if (wd != null) { return wd; } } - return IrisProceduralBlocks.resolve(ruin.getBlock(), ruin.getBlockPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + return IrisProceduralBlocks.resolve(ruin.block(), ruin.blockPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); } private static double clamp01(double value) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java index fcb71f56a..5f8868801 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java @@ -18,6 +18,13 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; +import art.arcane.iris.builtin.objects.tree.TreeDecorator; +import art.arcane.iris.builtin.objects.tree.TreeCanopy; +import art.arcane.iris.builtin.objects.tree.TreeRootStyle; +import art.arcane.iris.builtin.objects.tree.TreeProfile; +import art.arcane.iris.builtin.objects.tree.TreeFunction; +import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.stilt.StiltSettings; @@ -120,7 +127,7 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private IrisMaterialPalette leavesPalette = null; @Desc("The named canopy profile that drives default crown radii and shape.") - private IrisTreeProfile profile = IrisTreeProfile.OAK; + private TreeProfile profile = TreeProfile.OAK; @MinNumber(1) @Desc("Minimum trunk height in blocks.") @@ -135,7 +142,7 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private int trunkWidth = 1; @Desc("The function used to shape trunk width over height.") - private IrisTreeFunction trunkShape = IrisTreeFunction.CONSTANT; + private TreeFunction trunkShape = TreeFunction.CONSTANT; @Desc("Width multiplier at the base for the LINEAR trunk shape.") private double shapeStart = 1; @@ -168,13 +175,13 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private double leanAngle = 0; @Desc("How the lean accumulates over height.") - private IrisTreeFunction trunkCurve = IrisTreeFunction.LINEAR; + private TreeFunction trunkCurve = TreeFunction.LINEAR; @Desc("Steepness for the SIGMOID trunk curve.") private double curveSteepness = 8; @Desc("How the lean azimuth itself changes over height (for spiraling or wandering trunks).") - private IrisTreeAzimuthMode leanAzimuthMode = IrisTreeAzimuthMode.CONSTANT; + private TreeAzimuthMode leanAzimuthMode = TreeAzimuthMode.CONSTANT; @Desc("Azimuth at the base for the LINEAR azimuth mode.") private double azimuthStart = 0; @@ -210,9 +217,9 @@ public class IrisProceduralTree implements IrisProceduralPlacement { @Desc("The fraction of leaves replaced by the secondary leaf block(s).") private double secondaryLeafFraction = 0.35; - @ArrayType(min = 1, type = IrisTreeSecondaryLeaf.class) + @ArrayType(min = 1, type = TreeSecondaryLeaf.class) @Desc("Optional weighted set of accent leaf blocks. When set this overrides the single secondaryLeaves block.") - private KList weightedSecondaryLeaves = new KList<>(); + private KList weightedSecondaryLeaves = new KList<>(); @Desc("A noise-driven palette for the secondary (accent) leaves. When set this overrides both secondaryLeaves and weightedSecondaryLeaves.") private IrisMaterialPalette secondaryLeavesPalette = null; @@ -238,7 +245,7 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private boolean roots = true; @Desc("How the root system is built when roots is true.") - private IrisTreeRootStyle rootStyle = IrisTreeRootStyle.BUTTRESS; + private TreeRootStyle rootStyle = TreeRootStyle.BUTTRESS; @MinNumber(0) @Desc("Override the root depth/reach in blocks. 0 means auto (scales with tree height).") @@ -262,11 +269,11 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private double forkAngle = 25; @Desc("The leaf crown configuration.") - private IrisTreeCanopy canopy = new IrisTreeCanopy(); + private TreeCanopy canopy = new TreeCanopy(); - @ArrayType(min = 1, type = IrisTreeDecorator.class) + @ArrayType(min = 1, type = TreeDecorator.class) @Desc("Accent decorators applied after the tree is built (fruit, vines, snow, glow).") - private KList decorators = new KList<>(); + private KList decorators = new KList<>(); public KList getVariantObjects(IrisData data) { return variantCache.aquire(() -> { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java index feb18b5a1..037695c7a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java @@ -18,11 +18,13 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; +import art.arcane.iris.builtin.objects.tree.TreeDecorator; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import com.volmit.block.PaletteSpec; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeDecorator; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.math.RNG; @@ -62,8 +64,8 @@ public final class TreeBlockResolver { if (index < 0 || tree.getDecorators() == null || index >= tree.getDecorators().size()) { return null; } - IrisTreeDecorator dec = tree.getDecorators().get(index); - PlatformBlockState state = resolveBlock(dec.getBlock(), dec.getPalette(), data, pos, paletteRng); + TreeDecorator dec = tree.getDecorators().get(index); + PlatformBlockState state = resolveBlock(dec.block(), dec.palette().orElse(null), data, pos, paletteRng); if (state != null && cell.facing() != null && IrisProceduralBlocks.hasProperty(state, "facing")) { try { state = state.withProperty("facing", cell.facing().toLowerCase()); @@ -110,21 +112,25 @@ public final class TreeBlockResolver { private static String pickWeighted(IrisProceduralTree tree, RNG rng) { int total = 0; - for (art.arcane.iris.engine.object.procedural.tree.IrisTreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { - total += Math.max(0, s.getWeight()); + for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { + total += Math.max(0, s.weight()); } if (total <= 0) { return null; } double r = rng.nextDouble() * total; double cumulative = 0; - for (art.arcane.iris.engine.object.procedural.tree.IrisTreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { - cumulative += Math.max(0, s.getWeight()); + for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { + cumulative += Math.max(0, s.weight()); if (r < cumulative) { - return s.getBlock(); + return s.block(); } } - return tree.getWeightedSecondaryLeaves().get(tree.getWeightedSecondaryLeaves().size() - 1).getBlock(); + return tree.getWeightedSecondaryLeaves().get(tree.getWeightedSecondaryLeaves().size() - 1).block(); + } + + private static PlatformBlockState resolveBlock(String block, PaletteSpec palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { + return IrisProceduralBlocks.resolve(block, palette, data, pos.x(), pos.y(), pos.z(), paletteRng); } private static PlatformBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java index 7721e22d0..6c3bd3e7b 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeSubBranches; +import art.arcane.iris.builtin.objects.tree.TreeLayer; +import art.arcane.iris.builtin.objects.tree.TreeCanopy; +import art.arcane.iris.builtin.objects.tree.TreeBranches; +import art.arcane.iris.builtin.objects.tree.TreeProfile; +import art.arcane.iris.builtin.objects.tree.TreeLeafMode; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeBranches; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeCanopy; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeLayer; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeLeafMode; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeProfile; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeSubBranches; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -36,11 +36,11 @@ public final class TreeCanopyBuilder { public static void build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, double[][] offsets, int branchStartY, long baseSeed, List branchEndpoints) { - IrisTreeCanopy canopy = tree.getCanopy(); + TreeCanopy canopy = tree.getCanopy(); if (canopy == null) { - canopy = new IrisTreeCanopy(); + canopy = new TreeCanopy(); } - IrisTreeBranches branches = canopy.getBranches(); + TreeBranches branches = canopy.branches().orElse(null); double[][] layers = resolveLayers(canopy, tree.getProfile(), height, branches != null); @@ -69,19 +69,19 @@ public final class TreeCanopyBuilder { maxR = Math.max(maxR, layer[1]); } int capRadius = Math.max(2, Math.min(3, (int) Math.round(maxR * 0.35))); - IrisTreeCanopy canopy = tree.getCanopy(); - IrisTreeLeafMode mode = canopy != null ? canopy.getMode() : IrisTreeLeafMode.TRIMMED; - double density = canopy != null ? canopy.getLeafDensity() : 1.0; + TreeCanopy canopy = tree.getCanopy(); + TreeLeafMode mode = canopy != null ? canopy.mode() : TreeLeafMode.TRIMMED; + double density = canopy != null ? canopy.leafDensity() : 1.0; placeLeafCluster(canvas, tree, ocx, height - 1, ocz, capRadius, mode, density, baseSeed + 5555L); } - private static double[][] resolveLayers(IrisTreeCanopy canopy, IrisTreeProfile profile, int height, boolean branchDriven) { - KList explicit = canopy.getLayers(); + private static double[][] resolveLayers(TreeCanopy canopy, TreeProfile profile, int height, boolean branchDriven) { + KList explicit = new KList<>(canopy.layers()); if (explicit != null && !explicit.isEmpty()) { double[][] out = new double[explicit.size()][2]; for (int i = 0; i < explicit.size(); i++) { - out[i][0] = explicit.get(i).getYOffset(); - out[i][1] = explicit.get(i).getRadius(); + out[i][0] = explicit.get(i).yOffset(); + out[i][1] = explicit.get(i).radius(); } return out; } @@ -89,7 +89,7 @@ public final class TreeCanopyBuilder { } private static void volumeCanopy(TreeBlockCanvas canvas, IrisProceduralTree tree, double[][] layers, - IrisTreeCanopy canopy, long baseSeed, double[][] offsets) { + TreeCanopy canopy, long baseSeed, double[][] offsets) { int ocx = 0; int ocz = 0; if (offsets != null && offsets.length > 0) { @@ -97,10 +97,10 @@ public final class TreeCanopyBuilder { ocz = (int) Math.round(offsets[offsets.length - 1][1]); } - double startAngle = canopy.getStartAngle(); - double squish = canopy.getSquish(); - IrisTreeLeafMode mode = canopy.getMode(); - double leafDensity = canopy.getLeafDensity(); + double startAngle = canopy.startAngle(); + double squish = canopy.squish(); + TreeLeafMode mode = canopy.mode(); + double leafDensity = canopy.leafDensity(); for (double[] layer : layers) { int yCenter = (int) Math.round(layer[0]); @@ -137,7 +137,7 @@ public final class TreeCanopyBuilder { } private static void placeLeafDisc(TreeBlockCanvas canvas, IrisProceduralTree tree, int cx, int cy, int cz, - double radius, IrisTreeLeafMode mode, double density, long seed) { + double radius, TreeLeafMode mode, double density, long seed) { double sx = stretchX(tree); double sz = stretchZ(tree); RNG rng = new RNG(seed); @@ -158,7 +158,7 @@ public final class TreeCanopyBuilder { } private static void placeLeafCluster(TreeBlockCanvas canvas, IrisProceduralTree tree, int cx, int cy, int cz, - int radius, IrisTreeLeafMode mode, double density, long seed) { + int radius, TreeLeafMode mode, double density, long seed) { double sx = stretchX(tree); double sz = stretchZ(tree); RNG rng = new RNG(seed); @@ -181,16 +181,16 @@ public final class TreeCanopyBuilder { } private static double stretchX(IrisProceduralTree tree) { - IrisTreeCanopy c = tree.getCanopy(); - return c == null ? 1.0 : Math.max(0.1, c.getCrownStretchX()); + TreeCanopy c = tree.getCanopy(); + return c == null ? 1.0 : Math.max(0.1, c.crownStretchX()); } private static double stretchZ(IrisProceduralTree tree) { - IrisTreeCanopy c = tree.getCanopy(); - return c == null ? 1.0 : Math.max(0.1, c.getCrownStretchZ()); + TreeCanopy c = tree.getCanopy(); + return c == null ? 1.0 : Math.max(0.1, c.crownStretchZ()); } - private static boolean passesLeafTest(IrisTreeLeafMode mode, double dist, double radius, double density, + private static boolean passesLeafTest(TreeLeafMode mode, double dist, double radius, double density, RNG rng, int wx, int wy, int wz, long seed, boolean corner) { switch (mode) { case TRIMMED -> { @@ -258,12 +258,12 @@ public final class TreeCanopyBuilder { } private static void branchCanopy(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, - IrisTreeBranches branches, int branchStartY, long baseSeed, double[][] offsets, + TreeBranches branches, int branchStartY, long baseSeed, double[][] offsets, List branchEndpoints) { long branchSeed = baseSeed + 9999; RNG branchRng = new RNG(branchSeed); - IrisTreeSubBranches sub = branches.getSubBranches(); - int depth = branches.getBranchDepth(); + TreeSubBranches sub = branches.subBranches().orElse(null); + int depth = branches.branchDepth(); int branchIndex = 0; for (int y = Math.max(0, branchStartY); y < height; y++) { @@ -280,38 +280,38 @@ public final class TreeCanopyBuilder { oz = (int) Math.round(offsets[y][1]); } - double az = TreeFunctions.azimuthDegrees(branches.getAzimuthMode(), t, branchIndex, tree, branches.getAzimuth(), branchRng); + double az = TreeFunctions.azimuthDegrees(branches.azimuthMode(), t, branchIndex, tree, branches.azimuth(), branchRng); branchIndex++; double branchLen = TreeFunctions.branchLength(branches, t); - double effElevation = branches.isLeafStartUp() ? Math.max(0.0, branches.getElevation()) : branches.getElevation(); + double effElevation = branches.leafStartUp() ? Math.max(0.0, branches.elevation()) : branches.elevation(); int[] end = branchEndpoint(ox, y, oz, az, effElevation, branchLen); - int[] tip = rasterizeBranch(canvas, ox, y, oz, end[0], end[1], end[2], branches.getSag()); + int[] tip = rasterizeBranch(canvas, ox, y, oz, end[0], end[1], end[2], branches.sag()); if (branchEndpoints != null) { branchEndpoints.add(new int[]{tip[0], tip[1], tip[2], ox, oz}); } - placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], branches.getClusterRadius(), - branches.getClusterMode(), branches.getClusterDensity(), branchSeed + y); + placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], branches.clusterRadius(), + branches.clusterMode(), branches.clusterDensity(), branchSeed + y); growSubBranches(canvas, tree, tip[0], tip[1], tip[2], az, effElevation, branchLen, sub, depth, branchSeed + y + 1000L); } } private static void growSubBranches(TreeBlockCanvas canvas, IrisProceduralTree tree, int ox, int oy, int oz, - double az, double el, double len, IrisTreeSubBranches sub, int depth, long seed) { + double az, double el, double len, TreeSubBranches sub, int depth, long seed) { if (sub == null || depth <= 0) { return; } - int count = Math.max(1, sub.getCount()); + int count = Math.max(1, sub.count()); for (int si = 0; si < count; si++) { - double yawOffset = sub.getYawDelta() * (si - (count - 1) / 2.0); + double yawOffset = sub.yawDelta() * (si - (count - 1) / 2.0); double subAz = az + yawOffset; - double subEl = el + sub.getPitchDelta(); - double subLen = len * sub.getLengthScale(); + double subEl = el + sub.pitchDelta(); + double subLen = len * sub.lengthScale(); int[] end = branchEndpoint(ox, oy, oz, subAz, subEl, subLen); - int[] tip = rasterizeBranch(canvas, ox, oy, oz, end[0], end[1], end[2], sub.getSag()); - placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], sub.getClusterRadius(), - sub.getClusterMode(), sub.getClusterDensity(), seed + si * 131L); + int[] tip = rasterizeBranch(canvas, ox, oy, oz, end[0], end[1], end[2], sub.sag()); + placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], sub.clusterRadius(), + sub.clusterMode(), sub.clusterDensity(), seed + si * 131L); growSubBranches(canvas, tree, tip[0], tip[1], tip[2], subAz, subEl, subLen, sub, depth - 1, seed + si * 131L + 17L); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java index 15da8c5a9..4784e81ac 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeDecorator; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeDecorator; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.math.RNG; @@ -32,19 +32,19 @@ public final class TreeDecoratorApplier { } public static void apply(TreeBlockCanvas canvas, IrisProceduralTree tree, long baseSeed, List branchEndpoints) { - KList decorators = tree.getDecorators(); + KList decorators = tree.getDecorators(); if (decorators == null || decorators.isEmpty()) { return; } RNG rng = new RNG(baseSeed + 77777L); for (int idx = 0; idx < decorators.size(); idx++) { - IrisTreeDecorator dec = decorators.get(idx); - boolean hasBlock = (dec.getBlock() != null && !dec.getBlock().isEmpty()) || TreeTrunkBuilder.paletteSet(dec.getPalette()); + TreeDecorator dec = decorators.get(idx); + boolean hasBlock = (dec.block() != null && !dec.block().isEmpty()) || dec.palette().isPresent(); if (!hasBlock) { continue; } - switch (dec.getTarget()) { + switch (dec.target()) { case BRANCH_TIP -> branchTip(canvas, dec, idx, branchEndpoints, rng); case TRUNK_SURFACE -> trunkSurface(canvas, dec, idx, rng); case CANOPY_TOP -> canopyTop(canvas, dec, idx, rng); @@ -59,63 +59,63 @@ public final class TreeDecoratorApplier { } } - private static void branchTip(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, List branchEndpoints, RNG rng) { + private static void branchTip(TreeBlockCanvas canvas, TreeDecorator dec, int idx, List branchEndpoints, RNG rng) { if (branchEndpoints == null) { return; } for (int[] e : branchEndpoints) { - if (rng.nextDouble() > dec.getChance()) { + if (rng.nextDouble() > dec.chance()) { continue; } if (canvas.has(e[0], e[1], e[2])) { continue; } - String facing = dec.isAxisAware() ? facingAway(e[3], e[4], e[0], e[2]) : null; + String facing = dec.axisAware() ? facingAway(e[3], e[4], e[0], e[2]) : null; canvas.setDecor(e[0], e[1], e[2], idx, facing); } } - private static void trunkSurface(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void trunkSurface(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; String[] facings = {"west", "east", "north", "south"}; for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { for (int i = 0; i < sides.length; i++) { int nx = v.x() + sides[i][0]; int nz = v.z() + sides[i][1]; - if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.chance()) { continue; } - canvas.setDecor(nx, v.y(), nz, idx, dec.isAxisAware() ? facings[i] : null); + canvas.setDecor(nx, v.y(), nz, idx, dec.axisAware() ? facings[i] : null); } } } - private static void leafSurface(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void leafSurface(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; String[] facings = {"west", "east", "north", "south"}; for (TreeBlockCanvas.Vec v : new KList<>(canvas.getLeaf())) { for (int i = 0; i < sides.length; i++) { int nx = v.x() + sides[i][0]; int nz = v.z() + sides[i][1]; - if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.chance()) { continue; } - canvas.setDecor(nx, v.y(), nz, idx, dec.isAxisAware() ? facings[i] : null); + canvas.setDecor(nx, v.y(), nz, idx, dec.axisAware() ? facings[i] : null); } } } - private static void branchSurface(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void branchSurface(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { int ay = v.y() + 1; - if (canvas.has(v.x(), ay, v.z()) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(v.x(), ay, v.z()) || rng.nextDouble() > dec.chance()) { continue; } canvas.setDecor(v.x(), ay, v.z(), idx, null); } } - private static void canopyTop(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void canopyTop(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { KMap colTop = new KMap<>(); for (TreeBlockCanvas.Vec v : canvas.getCells().keySet()) { long key = pack(v.x(), v.z()); @@ -128,31 +128,31 @@ public final class TreeDecoratorApplier { int x = unpackX(e.getKey()); int z = unpackZ(e.getKey()); int aboveY = e.getValue() + 1; - if (canvas.has(x, aboveY, z) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(x, aboveY, z) || rng.nextDouble() > dec.chance()) { continue; } canvas.setDecor(x, aboveY, z, idx, null); } } - private static void canopyBottom(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void canopyBottom(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { KMap colBottom = columnLeafBottoms(canvas); for (Map.Entry e : colBottom.entrySet()) { int x = unpackX(e.getKey()); int z = unpackZ(e.getKey()); int belowY = e.getValue() - 1; - if (canvas.has(x, belowY, z) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(x, belowY, z) || rng.nextDouble() > dec.chance()) { continue; } canvas.setDecor(x, belowY, z, idx, null); } } - private static void canopyHang(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { - int maxLen = Math.max(1, dec.getLength()); + private static void canopyHang(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { + int maxLen = Math.max(1, dec.length()); KMap colBottom = columnLeafBottoms(canvas); for (Map.Entry e : colBottom.entrySet()) { - if (rng.nextDouble() > dec.getChance()) { + if (rng.nextDouble() > dec.chance()) { continue; } int x = unpackX(e.getKey()); @@ -168,7 +168,7 @@ public final class TreeDecoratorApplier { } } - private static void trunkBase(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void trunkBase(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { int[][] sides = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { if (v.y() != 0) { @@ -177,7 +177,7 @@ public final class TreeDecoratorApplier { for (int[] side : sides) { int nx = v.x() + side[0]; int nz = v.z() + side[1]; - if (canvas.has(nx, 0, nz) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(nx, 0, nz) || rng.nextDouble() > dec.chance()) { continue; } canvas.setDecor(nx, 0, nz, idx, null); @@ -185,7 +185,7 @@ public final class TreeDecoratorApplier { } } - private static void trunkTop(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void trunkTop(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { int maxY = Integer.MIN_VALUE; for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { maxY = Math.max(maxY, v.y()); @@ -198,14 +198,14 @@ public final class TreeDecoratorApplier { continue; } int aboveY = v.y() + 1; - if (canvas.has(v.x(), aboveY, v.z()) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(v.x(), aboveY, v.z()) || rng.nextDouble() > dec.chance()) { continue; } canvas.setDecor(v.x(), aboveY, v.z(), idx, null); } } - private static void groundScatter(TreeBlockCanvas canvas, IrisTreeDecorator dec, int idx, RNG rng) { + private static void groundScatter(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { double cx = 0; double cz = 0; int count = 0; @@ -237,7 +237,7 @@ public final class TreeDecoratorApplier { } int x = icx + dx; int z = icz + dz; - if (canvas.has(x, 0, z) || rng.nextDouble() > dec.getChance()) { + if (canvas.has(x, 0, z) || rng.nextDouble() > dec.chance()) { continue; } canvas.setDecor(x, 0, z, idx, null); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java index 3b223a18f..8583584fd 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeBranches; +import art.arcane.iris.builtin.objects.tree.TreeFunction; +import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeAzimuthMode; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeBranches; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeFunction; import art.arcane.volmlib.util.math.RNG; public final class TreeFunctions { @@ -65,7 +65,7 @@ public final class TreeFunctions { }; } - public static double curveProgress(IrisTreeFunction fn, double t, double steepness) { + public static double curveProgress(TreeFunction fn, double t, double steepness) { return switch (fn) { case LINEAR, CONSTANT, SINE -> t; case LOG -> Math.log(1.0 + t * (Math.E - 1.0)); @@ -78,14 +78,14 @@ public final class TreeFunctions { }; } - public static double branchLength(IrisTreeBranches b, double t) { - double base = b.getLengthBase(); - double crown = b.getLengthCrown(); - double max = b.getLengthMax(); - double v = switch (b.getLengthFunction()) { - case CONSTANT -> b.getLengthConstant(); + public static double branchLength(TreeBranches b, double t) { + double base = b.lengthBase(); + double crown = b.lengthCrown(); + double max = b.lengthMax(); + double v = switch (b.lengthFunction()) { + case CONSTANT -> b.lengthConstant(); case LINEAR, SINE -> base + (crown - base) * t; - case SIGMOID -> max / (1.0 + Math.exp(-b.getLengthSteepness() * (t - 0.5))); + case SIGMOID -> max / (1.0 + Math.exp(-b.lengthSteepness() * (t - 0.5))); case LOG -> max * Math.log(1.0 + t * (Math.E - 1.0)); case PARABOLIC -> max * (1.0 - Math.pow(2.0 * t - 1.0, 2)); case EXPONENTIAL -> geometric(base, crown, t); @@ -97,24 +97,24 @@ public final class TreeFunctions { return Math.max(1.0, v); } - public static double branchProbability(IrisTreeBranches b, double t, long seed) { - double std = Math.max(b.getProbabilityStd(), 1e-6); - return switch (b.getProbabilityFunction()) { - case CONSTANT -> b.getProbabilityConstant(); - case LINEAR -> b.getProbabilityBase() + (b.getProbabilityCrown() - b.getProbabilityBase()) * t; - case SIGMOID -> 1.0 / (1.0 + Math.exp(-b.getProbabilitySteepness() * (t - b.getProbabilityMidpoint()))); - case TOP_HEAVY -> Math.pow(t, b.getProbabilityExponent()); - case GAUSSIAN -> Math.exp(-0.5 * Math.pow((t - b.getProbabilityMean()) / std, 2)); - case NOISE -> valueNoise1D(t * b.getProbabilityScale(), seed); - case BOTTOM_HEAVY -> Math.pow(1.0 - t, b.getProbabilityExponent()); - case PERIODIC -> b.getProbabilityConstant() * Math.pow(Math.max(0.0, Math.sin(2.0 * Math.PI * t * b.getProbabilityPeriods())), 8); - case BAND -> Math.abs(t - b.getProbabilityMean()) <= b.getProbabilityStd() ? b.getProbabilityConstant() : 0.0; - case INVERSE_GAUSSIAN -> b.getProbabilityConstant() * (1.0 - Math.exp(-0.5 * Math.pow((t - b.getProbabilityMean()) / std, 2))); - case EXPONENTIAL_DECAY -> b.getProbabilityConstant() * Math.exp(-b.getProbabilityExponent() * t); + public static double branchProbability(TreeBranches b, double t, long seed) { + double std = Math.max(b.probabilityStd(), 1e-6); + return switch (b.probabilityFunction()) { + case CONSTANT -> b.probabilityConstant(); + case LINEAR -> b.probabilityBase() + (b.probabilityCrown() - b.probabilityBase()) * t; + case SIGMOID -> 1.0 / (1.0 + Math.exp(-b.probabilitySteepness() * (t - b.probabilityMidpoint()))); + case TOP_HEAVY -> Math.pow(t, b.probabilityExponent()); + case GAUSSIAN -> Math.exp(-0.5 * Math.pow((t - b.probabilityMean()) / std, 2)); + case NOISE -> valueNoise1D(t * b.probabilityScale(), seed); + case BOTTOM_HEAVY -> Math.pow(1.0 - t, b.probabilityExponent()); + case PERIODIC -> b.probabilityConstant() * Math.pow(Math.max(0.0, Math.sin(2.0 * Math.PI * t * b.probabilityPeriods())), 8); + case BAND -> Math.abs(t - b.probabilityMean()) <= b.probabilityStd() ? b.probabilityConstant() : 0.0; + case INVERSE_GAUSSIAN -> b.probabilityConstant() * (1.0 - Math.exp(-0.5 * Math.pow((t - b.probabilityMean()) / std, 2))); + case EXPONENTIAL_DECAY -> b.probabilityConstant() * Math.exp(-b.probabilityExponent() * t); }; } - public static double azimuthDegrees(IrisTreeAzimuthMode mode, double t, int index, IrisProceduralTree tree, double constantBase, RNG rng) { + public static double azimuthDegrees(TreeAzimuthMode mode, double t, int index, IrisProceduralTree tree, double constantBase, RNG rng) { return switch (mode) { case CONSTANT -> constantBase; case LINEAR -> tree.getAzimuthStart() + (tree.getAzimuthEnd() - tree.getAzimuthStart()) * t; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java index f3bfabf6f..7dc66cba2 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java @@ -18,13 +18,14 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeProfile; +import art.arcane.iris.builtin.objects.tree.TreeProfile; + public final class TreeProfiles { private TreeProfiles() { } - static double radiusScale(IrisTreeProfile profile) { + static double radiusScale(TreeProfile profile) { return switch (profile) { case OAK, DARK_OAK, CHERRY -> 1.0; case BIRCH -> 0.7; @@ -41,7 +42,7 @@ public final class TreeProfiles { }; } - static double[][] fractions(IrisTreeProfile profile) { + static double[][] fractions(TreeProfile profile) { return switch (profile) { case OAK -> new double[][]{{0.55, 0.6}, {0.65, 0.9}, {0.75, 1.0}, {0.85, 0.9}, {0.92, 0.65}, {0.98, 0.35}}; case BIRCH -> new double[][]{{0.6, 0.45}, {0.7, 0.75}, {0.8, 0.85}, {0.88, 0.75}, {0.94, 0.45}, {0.99, 0.2}}; @@ -59,7 +60,7 @@ public final class TreeProfiles { }; } - static double[][] presetLayers(IrisTreeProfile profile, int height, boolean branchDriven) { + static double[][] presetLayers(TreeProfile profile, int height, boolean branchDriven) { double scale = radiusScale(profile); int baseRadius = Math.max(3, (int) Math.round(height / 2.0 * scale)); double[][] fractions = fractions(profile); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java index 04950a18f..2a296b30a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeRootStyle; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeRootStyle; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; @@ -58,7 +58,7 @@ public final class TreeRootBuilder { } double flare = tree.getRootFlare() > 0 ? tree.getRootFlare() : baseRadius + Math.max(2.0, depth * 0.6); - IrisTreeRootStyle style = tree.getRootStyle(); + TreeRootStyle style = tree.getRootStyle(); switch (style) { case TAPROOT -> taproot(canvas, cells, cx, cz, baseRadius, depth); case BUTTRESS -> { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java index 20698ab17..25e26b971 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeAzimuthMode; import java.util.ArrayList; import java.util.List; @@ -164,7 +164,7 @@ public final class TreeTrunkBuilder { double progress = TreeFunctions.curveProgress(tree.getTrunkCurve(), t, tree.getCurveSteepness()); double maxReach = height * Math.tan(Math.toRadians(tree.getLeanAngle())); double reach = maxReach * progress; - double azDeg = tree.getLeanAzimuthMode() == IrisTreeAzimuthMode.CONSTANT + double azDeg = tree.getLeanAzimuthMode() == TreeAzimuthMode.CONSTANT ? tree.getLeanAzimuth() : TreeFunctions.azimuthDegrees(tree.getLeanAzimuthMode(), t, -1, tree, tree.getLeanAzimuth(), null); double azRad = Math.toRadians(azDeg); From 54b22c942d6d7aefc4151cd4b401a3ae5b316dcb Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:32:16 +0200 Subject: [PATCH 042/139] README: module-owned settings held by Iris's classes --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 8de696f27..0c90e19c3 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,13 @@ only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its en `art.arcane.iris.builtin.deposit`), and packs write `"iris:deposit": {"generators": [...]}` (the old `"deposits": [...]` is converted by the pack migration script). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. +Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition, +a cave profile, a floating child biome or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, +`.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). The module registers each with +`registry.registerHeldType(...)` so studio describes it from the module's own annotations; packs write the same JSON as before. Behaviour +that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the +worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`) + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. From 8cf11774dac71b973c084e519f744820626072c2 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 22:46:24 +0200 Subject: [PATCH 043/139] ResolvedDecorator exposes its seed; README describes iris:decorant --- README.md | 8 ++++++++ .../arcane/iris/engine/decorator/ResolvedDecorator.java | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/README.md b/README.md index 8de696f27..e3b8b082b 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,14 @@ only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its en `art.arcane.iris.builtin.deposit`), and packs write `"iris:deposit": {"generators": [...]}` (the old `"deposits": [...]` is converted by the pack migration script). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. +`iris:decorant` is the second: `DecorantSettings` (biome level) holds `Decorator`s in `art.arcane.iris.builtin.decorant`, +written `"iris:decorant": {"decorators": [...]}` (the old `"decorators": [...]` is converted by the migration script). +`ResolvedDecorator` resolves one decorator's blocks and noise for a world; `BiomeDecorators`, the world's state, keeps them +per biome and place. Other modules that decorate (`iris:cave`'s ceilings, floating islands) ask it. A decorator's noise +seed is the world's decorator seed, its biome's key and its place in the biome's list. The module's `warmUp` builds +them ahead of generation; `iris:terrain` and `iris:objects` warm their ore generators, placements and procedural +objects the same way. + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. diff --git a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java index b6c529176..8f9296005 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -114,6 +114,11 @@ final class ResolvedDecorator { return settings; } + /** The seed the decorator's noise is built from. */ + long seed() { + return seed; + } + DecorationPart part() { return settings.partOf(); } From 13aa3ccc68987764da1256870888f860415ce368 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 9 Oct 2026 23:27:19 +0200 Subject: [PATCH 044/139] Built-in settings declare their JSON keys: deposits, decorators, importedStructures DepositSettings and DecorantSettings hold their one option's list as the value of the key (root), StructureSettings is the object under importedStructures. The feature ids stay the modules' identity. README names the keys. --- README.md | 9 +++++++-- .../arcane/iris/builtin/decorant/DecorantSettings.java | 4 ++-- .../java/art/arcane/iris/builtin/decorant/Decorator.java | 2 +- .../arcane/iris/builtin/deposit/DepositGenerator.java | 2 +- .../art/arcane/iris/builtin/deposit/DepositSettings.java | 4 ++-- .../arcane/iris/builtin/structure/StructureSettings.java | 6 +++--- .../engine/framework/structure/StructureVanillaHook.java | 2 +- .../iris/engine/mantle/components/StructureModule.java | 2 +- 8 files changed, 18 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index c489819ad..e7dd7aae7 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ built-ins still reach the same store through `IrisChunk.state(...)` / `engine.ge Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in -`art.arcane.iris.builtin.deposit`), and packs write `"iris:deposit": {"generators": [...]}` (the old `"deposits": [...]` is converted by the pack migration script). What needs Iris (resolving the +`art.arcane.iris.builtin.deposit`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition, @@ -50,13 +50,18 @@ that needs Iris (noise built from the styles, blocks resolved through the pack, worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`). `iris:decorant` is the second: `DecorantSettings` (biome level) holds `Decorator`s in `art.arcane.iris.builtin.decorant`, -written `"iris:decorant": {"decorators": [...]}` (the old `"decorators": [...]` is converted by the migration script). +written `"decorators": [...]` as always (`@Feature(key = "decorators", root = "decorators")`). `ResolvedDecorator` resolves one decorator's blocks and noise for a world; `BiomeDecorators`, the world's state, keeps them per biome and place. Other modules that decorate (`iris:cave`'s ceilings, floating islands) ask it. A decorator's noise seed is the world's decorator seed, its biome's key and its place in the biome's list. The module's `warmUp` builds them ahead of generation; `iris:terrain` and `iris:objects` warm their ore generators, placements and procedural objects the same way. +Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` +(biome; a list) and `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest). The feature ids +(`iris:deposit`, `iris:decorant`, `iris:structure`) stay the modules' identity in the stage graph and logs. A key is unique +per target across all modules and Iris's own fields, so a new built-in or pack module picks a key no field of the target uses. + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java index 775ac54c3..3e00e8ed3 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java @@ -28,11 +28,11 @@ import java.util.Collections; import java.util.List; /** - * The decorators one biome declares, written as {@code "iris:decorant": {"decorators": [...]}}. IrisApi types only, like + * The decorators one biome declares, written as {@code "decorators": [...]}, the list of decorators. IrisApi types only, like * {@link Decorator}. */ @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") -@Feature(id = "iris:decorant", name = "Decorators", targets = Target.BIOME) +@Feature(id = "iris:decorant", name = "Decorators", key = "decorators", root = "decorators", targets = Target.BIOME) public final class DecorantSettings implements IrisFeature { @MinItems(1) @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") diff --git a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java index 9ef5e0eff..891a7778b 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java @@ -32,7 +32,7 @@ import java.util.List; import java.util.Optional; /** - * One decorator of a biome, as packs write it in the {@code decorators} of {@code "iris:decorant"} or under + * One decorator of a biome, as packs write it in the {@code "decorators"} list or under * {@code snippet/decorator/}: which blocks it places, where, how often and how tall. A value of IrisApi types only; the * decorant module resolves the blocks and builds the noise. */ diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java index 843f5757b..4b6f4e317 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java @@ -30,7 +30,7 @@ import java.util.Collections; import java.util.List; /** - * One kind of deposit a dimension, region or biome generates, as packs write it in the {@code generators} of {@code "iris:deposit"} or under + * One kind of deposit a dimension, region or biome generates, as packs write it in the {@code "deposits"} list or under * {@code snippet/deposit/}: how many clumps of which blocks, how large, at which heights and in which biomes. A value * of IrisApi types only; the deposit module builds the clumps and resolves the blocks. */ diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java index 8da34c2ce..6fd8c5987 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java @@ -26,12 +26,12 @@ import com.volmit.config.Feature; import java.util.List; /** - * The deposits one dimension, region or biome declares, written as {@code "iris:deposit": {"generators": [...]}}. Levels stack: + * The deposits one dimension, region or biome declares, written as {@code "deposits": [...]}, the list of generators. Levels stack: * a chunk gets the deposits of its dimension, its centre column's region and that column's biome. IrisApi types only, * like {@link DepositGenerator}. */ @Desc("Ores and other deposits generated in every chunk where this applies") -@Feature(id = "iris:deposit", name = "Deposits", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:deposit", name = "Deposits", key = "deposits", root = "generators", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) public final class DepositSettings implements IrisFeature { @Desc("Define deposit generators that this applies to chunks") private List generators = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java index 4ab5886cc..29c7a432a 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java @@ -33,12 +33,12 @@ import java.util.List; /** * How a dimension treats the platform's own structures (vanilla, data pack and mod structures), written as - * {@code "iris:structure": {"disabled": [...], "adjustments": [...]}}: which ones it disables, how the ones that still + * {@code "importedStructures": {"disabled": [...], "adjustments": [...]}}: which ones it disables, how the ones that still * generate are moved and fitted, how often structure sets start, and whether installed data packs may replace the - * platform's own definitions. The JSON packs wrote as {@code importedStructures}. IrisApi types only. + * platform's own definitions. IrisApi types only. */ @Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris structure list ' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") -@Feature(id = "iris:structure", name = "Structures", targets = Target.DIMENSION) +@Feature(id = "iris:structure", name = "Structures", key = "importedStructures", targets = Target.DIMENSION) public final class StructureSettings implements IrisFeature { @MinItems(1) @Ref(Reference.STRUCTURE_PREFIX) diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java index eb6475991..005a14c9c 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java @@ -42,7 +42,7 @@ import com.volmit.vanilla.VanillaStructureStartContext; import java.util.List; /** - * What {@code iris:structure} says about the platform's own structures. The dimension's {@code iris:structure} + * What {@code iris:structure} says about the platform's own structures. The dimension's {@code importedStructures} * settings ({@link ImportedStructures}) disable, adjust and set them up; the pack's structure placements replace * them ({@code vanillaSource} with native suppression), place them alongside ({@link IrisStructureLocator#isPlaced}) * and start them where their {@code nativeStructures} grids say ({@link NativeStartPlanner}). diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 4f7952044..54efeb970 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -51,7 +51,7 @@ import com.volmit.world.PackWorld; * the pack's structure files. *

* It decides over the platform's own structures through its vanilla structure hook ({@link StructureVanillaHook}): the - * dimension's {@code iris:structure} settings disable, adjust and set them up, and the pack's structure placements + * dimension's {@code importedStructures} settings disable, adjust and set them up, and the pack's structure placements * replace them, place them alongside, and start them where their {@code nativeStructures} grids say. */ public final class StructureModule implements IrisModule, ModuleLifecycle { From 3d7b82c2cb995ded9b278d97445d7442a36a5309 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 03:50:39 +0200 Subject: [PATCH 045/139] Structure fit moves into iris:structure behind the VanillaStructures service The module now owns every way a platform start meets the terrain: the surface fit (SOURCE beard, VACUUM and its foundation repair), terrain integration (SOURCE bury and encapsulate, ENCASE, BORE, FORCE_CARVE with the organic carve), rigid piece support, legacy template air and stilts, all written against StructureFit and BlockAccess in the new structure/fit package. Where a start sits (shift, band, burial) and how far it reaches are module answers too. The fit settings become the module's own: StructureTerrain, StructureTerrainMode, StructureCarveShape, StructureStilts and StructureYBand replace the Iris classes and the API values, with the same JSON. A start carries its fit as a memo (terrain JSON, stilts JSON) so every chunk it reaches fits it the same way. The jigsaw overrides of a placement are the API's JigsawOverrides. --- .../structure/StructureAdjustment.java | 9 +- .../structure/StructureCarveShape.java} | 28 +- .../builtin/structure/StructureStilts.java | 74 ++ .../structure/StructureTerrain.java} | 81 +- .../structure/StructureTerrainMode.java} | 24 +- .../builtin/structure/StructureYBand.java | 52 ++ .../framework/IrisStructureLocator.java | 26 +- .../structure/ImportedStructures.java | 16 +- .../structure/NativeStructureFit.java | 81 ++ ...k.java => StructureVanillaStructures.java} | 72 +- .../engine/framework/structure/fit/Box.java | 75 ++ .../structure/fit/CarveFootprints.java | 172 +++++ .../framework/structure/fit/FitBlocks.java | 112 +++ .../structure/fit/FitPalettes.java} | 15 +- .../framework/structure/fit/FitPiece.java | 102 +++ .../framework/structure/fit/FitStart.java | 94 +++ .../structure/fit/FoundationStilts.java | 156 ++++ .../framework/structure/fit/RigidSupport.java | 271 +++++++ .../framework/structure/fit/StartLayouts.java | 112 +++ .../structure/fit/StructureFitting.java | 129 ++++ .../structure/fit/SurfaceFitting.java | 713 ++++++++++++++++++ .../structure/fit/TemplateFootprint.java | 98 +++ .../structure/fit/TerrainIntegration.java | 633 ++++++++++++++++ .../components/StructureCarveEnvelope.java | 6 +- .../mantle/components/StructureModule.java | 19 +- .../mantle/components/StructurePlacing.java | 77 +- .../structure/IrisStructurePlacement.java | 10 +- .../structure/IrisStructureStiltSettings.java | 33 - .../object/structure/IrisStructureYBand.java | 34 - .../jigsaw/IrisJigsawConfiguration.java | 71 -- .../structure/jigsaw/IrisJigsawHeightmap.java | 30 - .../jigsaw/IrisJigsawLiquidSettings.java | 15 - .../vanilla/IrisNativeStructure.java | 4 +- .../vanilla/IrisNativeStructureDecision.java | 40 - 34 files changed, 3113 insertions(+), 371 deletions(-) rename src/main/java/art/arcane/iris/{engine/object/structure/IrisStructureCarveShape.java => builtin/structure/StructureCarveShape.java} (50%) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java rename src/main/java/art/arcane/iris/{engine/object/structure/IrisStructureTerrain.java => builtin/structure/StructureTerrain.java} (59%) rename src/main/java/art/arcane/iris/{engine/object/structure/IrisStructureTerrainMode.java => builtin/structure/StructureTerrainMode.java} (63%) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java rename src/main/java/art/arcane/iris/engine/framework/structure/{StructureVanillaHook.java => StructureVanillaStructures.java} (67%) create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java rename src/main/java/art/arcane/iris/engine/{object/structure/vanilla/NativeStructureGenerationStatus.java => framework/structure/fit/FitPalettes.java} (63%) create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java b/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java index 20c5b473a..0a214cb93 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java @@ -24,9 +24,6 @@ import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; -import com.volmit.vanilla.StructureStilts; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.YBand; import java.util.List; import java.util.Optional; @@ -45,7 +42,7 @@ public final class StructureAdjustment { private int yShift = 0; @Desc("Optional absolute world Y band. The structure is relocated so its vertical midpoint lands inside the band, deterministically from its start chunk and clamped to the world's build bounds. Precedence: preserveSourceY wins over yBand, and yBand wins over both yShift and Iris burial repositioning. Structures with a fixed vanilla alignment (ocean monument sea level, desert and jungle pyramid surface fit) ignore it.") - private YBand yBand = null; + private StructureYBand yBand = null; @Desc("When true, skip Iris burial repositioning so the structure keeps the Y its own vanilla placement chose. Underground structures are otherwise pushed below the lowest solid column across their whole footprint, which hides terrain-aware structures such as mineshafts that intentionally breach cliffs and surfaces. Vertical shifts still apply on top of the preserved Y: this dimension's undergroundYShift plus every matching adjustment's yShift.") private boolean preserveSourceY = false; @@ -59,7 +56,7 @@ public final class StructureAdjustment { public StructureAdjustment() { } - public StructureAdjustment(List match, int yShift, YBand yBand, boolean preserveSourceY, StructureStilts stilt, + public StructureAdjustment(List match, int yShift, StructureYBand yBand, boolean preserveSourceY, StructureStilts stilt, StructureTerrain terrain) { this.match = List.copyOf(match); this.yShift = yShift; @@ -78,7 +75,7 @@ public final class StructureAdjustment { return yShift; } - public Optional yBand() { + public Optional yBand() { return Optional.ofNullable(yBand); } diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java b/src/main/java/art/arcane/iris/builtin/structure/StructureCarveShape.java similarity index 50% rename from src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java rename to src/main/java/art/arcane/iris/builtin/structure/StructureCarveShape.java index 123367217..a666f7ff2 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureCarveShape.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureCarveShape.java @@ -1,9 +1,26 @@ -package art.arcane.iris.engine.object.structure; +/* + * 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.builtin.structure; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls the shape of the expanded terrain carve around an overbored structure.") -public enum IrisStructureCarveShape { +public enum StructureCarveShape { @Desc("Carves the full expanded rectangular volume with straight walls, ceiling, and floor.") BOX, @@ -13,16 +30,19 @@ public enum IrisStructureCarveShape { @Desc("Carves a rounded volume whose outer boundary is eroded by deterministic noise.") ERODED; + private static final double ERODED_CEILING_GROWTH = 0.8D; + public double maximumCeilingScale() { return maximumCeilingScale(1D); } + /** How far above its configured head room a carve of this shape may reach, as a multiple of it. */ public double maximumCeilingScale(double erosionStrength) { double strength = Double.isFinite(erosionStrength) ? Math.max(0D, Math.min(1D, erosionStrength)) : 1D; return switch (this) { case BOX, ROUNDED -> 1D; - case ERODED -> 1D + 0.8D * strength; + case ERODED -> 1D + ERODED_CEILING_GROWTH * strength; }; } diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java b/src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java new file mode 100644 index 000000000..36d53e374 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureStilts.java @@ -0,0 +1,74 @@ +/* + * 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.builtin.structure; + +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.List; +import java.util.Optional; + +/** + * Foundation columns built beneath a structure's pieces after they are placed, as packs write it: + * {"maxDepth": 32, "palette": {"palette": [{"block": "stone_bricks"}]}, "spacing": 2}. Held by structure placements and + * by the {@code importedStructures} adjustments; ownership records keep its JSON for the starts they track. + */ +@Desc("Defines foundation columns placed beneath a structure.") +public final class StructureStilts { + private static final String DEFAULT_BLOCK = "minecraft:cobblestone"; + + @MinNumber(1) + @MaxNumber(4064) + @Desc("Maximum number of blocks each foundation column may descend while searching for solid ground.") + private int maxDepth = 64; + + @Desc("Block palette used for foundation columns.") + private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); + + @MinNumber(1) + @MaxNumber(64) + @Desc("Horizontal spacing between support columns. One fills every eligible foundation column; larger values create sparse stilts.") + private int spacing = 1; + + @Desc("For Iris-authored structures, whether solid partial blocks such as slabs, stairs, and walls may seed foundation columns instead of requiring a fully occluding base block.") + private boolean supportNonOccluding = false; + + public StructureStilts() { + } + + public int maxDepth() { + return maxDepth; + } + + /** The blocks of the columns; empty when the pack wrote {@code "palette": null}. */ + public Optional palette() { + return Optional.ofNullable(palette); + } + + public int spacing() { + return spacing; + } + + public boolean supportNonOccluding() { + return supportNonOccluding; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java b/src/main/java/art/arcane/iris/builtin/structure/StructureTerrain.java similarity index 59% rename from src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java rename to src/main/java/art/arcane/iris/builtin/structure/StructureTerrain.java index 311598130..c014e65ef 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrain.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureTerrain.java @@ -1,20 +1,37 @@ -package art.arcane.iris.engine.object.structure; +/* + * 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 . + */ -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -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; +package art.arcane.iris.builtin.structure; -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Data +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.Optional; + +/** + * How a structure meets the terrain, as packs write it: {"mode": "FORCE_CARVE", "horizontalPadding": 4, "shape": "ERODED"}. + * Held by structure placements and by the {@code importedStructures} adjustments; ownership records keep its JSON for + * the starts they track, so its field names and defaults are the persisted format. + */ @Desc("Terrain integration applied after a structure graph is assembled and before its pieces are placed.") -public class IrisStructureTerrain { +public final class StructureTerrain { private static final double AUTO_LOBE_FREQUENCY_RATIO = 0.3D; private static final double DEFAULT_EROSION_STRENGTH = 0.8D; private static final double DEFAULT_EROSION_FREQUENCY = 0.07D; @@ -24,7 +41,7 @@ public class IrisStructureTerrain { private static final double MAX_LOBE_FREQUENCY = 1D; @Desc("Terrain operation. SOURCE applies the registered native structure's authored terrain adaptation and is a no-op for editable Iris structures. PRESERVE disables terrain integration. VACUUM raises terrain from processed rigid-template foundations at or below each authored ground plane with a 12-block falloff without lowering existing ground. BORE and FORCE_CARVE clear the requested envelope, while ENCASE fills it before placement so native shells are not lost to pre-carved air.") - private IrisStructureTerrainMode mode = IrisStructureTerrainMode.SOURCE; + private StructureTerrainMode mode = StructureTerrainMode.SOURCE; @MinNumber(0) @MaxNumber(128) @@ -42,10 +59,10 @@ public class IrisStructureTerrain { private int floorPadding = 0; @Desc("Shape used by FORCE_CARVE.") - private IrisStructureCarveShape shape = IrisStructureCarveShape.BOX; + private StructureCarveShape shape = StructureCarveShape.BOX; @Desc("Block palette used by ENCASE. When unset, the Overworld uses stone or deepslate, the Nether uses netherrack, and the End uses end stone.") - private IrisMaterialPalette encasePalette = null; + private PaletteSpec encasePalette = null; @MinNumber(0) @MaxNumber(1) @@ -67,12 +84,34 @@ public class IrisStructureTerrain { @Desc("Fraction of the horizontal padding the lobes may remove for ERODED force carving. Zero keeps a uniform boundary.") private double lobeStrength = DEFAULT_LOBE_STRENGTH; - public IrisStructureTerrainMode resolvedMode() { - return mode == null ? IrisStructureTerrainMode.SOURCE : mode; + public StructureTerrain() { } - public IrisStructureCarveShape resolvedShape() { - return shape == null ? IrisStructureCarveShape.BOX : shape; + /** The terrain operation; SOURCE where the pack wrote none or one Iris does not know. */ + public StructureTerrainMode resolvedMode() { + return mode == null ? StructureTerrainMode.SOURCE : mode; + } + + public int horizontalPadding() { + return horizontalPadding; + } + + public int ceilingPadding() { + return ceilingPadding; + } + + public int floorPadding() { + return floorPadding; + } + + /** The carve shape; BOX where the pack wrote none or one Iris does not know. */ + public StructureCarveShape resolvedShape() { + return shape == null ? StructureCarveShape.BOX : shape; + } + + /** The blocks ENCASE fills with; empty for the dimension's own stone. */ + public Optional encasePalette() { + return Optional.ofNullable(encasePalette); } public double resolvedErosionStrength() { diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java b/src/main/java/art/arcane/iris/builtin/structure/StructureTerrainMode.java similarity index 63% rename from src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java rename to src/main/java/art/arcane/iris/builtin/structure/StructureTerrainMode.java index 31ea63adf..d7c7cf955 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureTerrainMode.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureTerrainMode.java @@ -1,9 +1,27 @@ -package art.arcane.iris.engine.object.structure; +/* + * 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 . + */ -import art.arcane.iris.engine.object.annotations.Desc; +package art.arcane.iris.builtin.structure; + +import com.volmit.config.Desc; @Desc("Controls how terrain is integrated with a structure.") -public enum IrisStructureTerrainMode { +public enum StructureTerrainMode { @Desc("Replays the registered native structure's own authored terrain adaptation (beard surface fitting, BURY/ENCAPSULATE fill, legacy template-air clearing). Does nothing for editable Iris structures, which have no source adaptation to replay.") SOURCE, diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java b/src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java new file mode 100644 index 000000000..f21320a86 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureYBand.java @@ -0,0 +1,52 @@ +/* + * 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.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** + * A band of absolute world heights a platform structure is moved into, as packs write it: {"min": -120, "max": -20}. + * Unlike the API's heights these are world Y, as the platform's own structure definitions use them. Reversed bounds + * mean the same band. + */ +@Desc("An absolute world Y band a native structure is relocated into. Reversed bounds are normalized.") +public final class StructureYBand { + @MinNumber(-4064) + @MaxNumber(4064) + @Desc("Lowest absolute world Y of the band.") + private int min = 0; + + @MinNumber(-4064) + @MaxNumber(4064) + @Desc("Highest absolute world Y of the band.") + private int max = 0; + + public StructureYBand() { + } + + public int resolvedMin() { + return Math.min(min, max); + } + + public int resolvedMax() { + return Math.max(min, max); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index cf9cccf27..995094da1 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -31,10 +31,10 @@ 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.engine.object.structure.IrisStructureAnchorMode; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.engine.object.structure.StructureDistribution; import art.arcane.volmlib.util.collection.KList; @@ -698,17 +698,17 @@ public final class IrisStructureLocator { return null; } - IrisStructureTerrain terrain = placement.resolvedTerrain(); - IrisStructureTerrainMode terrainMode = terrain.resolvedMode(); - boolean forceCarve = terrainMode == IrisStructureTerrainMode.FORCE_CARVE; - boolean bore = terrainMode == IrisStructureTerrainMode.BORE; - int sideExtension = forceCarve || bore ? Math.max(0, terrain.getHorizontalPadding()) : 0; - IrisStructureCarveShape carveShape = terrain.resolvedShape(); + 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.getCeilingPadding(), terrain.resolvedErosionStrength()) - : bore ? Math.max(0, terrain.getCeilingPadding()) : 0; - int bottomExtension = forceCarve || bore ? Math.max(0, terrain.getFloorPadding()) : 0; + 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.getMinHeight(), placement.getMaxHeight())); int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); int minimumShift = Math.max(worldMin - (bounds[1] - bottomExtension), bandMin - baseY); @@ -719,7 +719,7 @@ public final class IrisStructureLocator { Long2IntOpenHashMap surfaceHeights = new Long2IntOpenHashMap(); surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); - if (bore || forceCarve && carveShape == IrisStructureCarveShape.BOX) { + if (bore || forceCarve && carveShape == StructureCarveShape.BOX) { maximumShift = resolveBurialEnvelopeShift( engine, bounds[0] - sideExtension, diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java index 78fb6157d..a7d215973 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java @@ -24,8 +24,6 @@ import art.arcane.iris.builtin.structure.StructureSettings; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; import com.volmit.resource.ResourceId; -import com.volmit.vanilla.VanillaStructureAdjustment; -import com.volmit.vanilla.VanillaStructureFit; import com.volmit.vanilla.VanillaStructureSetup; import java.util.List; @@ -66,8 +64,8 @@ public final class ImportedStructures { * How the platform's own starts of {@code key} are adjusted: the underground shift for underground steps, then every * matching adjustment in the order the pack lists them. */ - public VanillaStructureAdjustment adjustment(String key, boolean underground) { - VanillaStructureAdjustment adjustment = VanillaStructureAdjustment.NONE.shifted(underground ? settings.undergroundYShift() : 0); + public NativeStructureFit adjustment(String key, boolean underground) { + NativeStructureFit adjustment = NativeStructureFit.NONE.shifted(underground ? settings.undergroundYShift() : 0); for (StructureAdjustment entry : settings.adjustments()) { if (entry != null && matchesAny(entry.match(), key)) { adjustment = adjustment.then(asAdjustment(entry)); @@ -130,13 +128,9 @@ public final class ImportedStructures { return patterns.stream().anyMatch(pattern -> matchesKey(pattern, key)); } - private static VanillaStructureAdjustment asAdjustment(StructureAdjustment entry) { - VanillaStructureFit fit = VanillaStructureFit.SOURCE; - fit = entry.stilt().map(fit::withStilts).orElse(fit); - fit = entry.terrain().map(fit::withTerrain).orElse(fit); - VanillaStructureAdjustment adjustment = VanillaStructureAdjustment.NONE.shifted(entry.yShift()).withFit(fit); - adjustment = entry.yBand().map(adjustment::withYBand).orElse(adjustment); - return entry.preserveSourceY() ? adjustment.keepingSourceY() : adjustment; + private static NativeStructureFit asAdjustment(StructureAdjustment entry) { + return new NativeStructureFit(entry.yShift(), entry.yBand().orElse(null), entry.preserveSourceY(), + entry.stilt().orElse(null), entry.terrain().orElse(null)); } private static String normalize(String key) { diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java new file mode 100644 index 000000000..1add43a90 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java @@ -0,0 +1,81 @@ +/* + * 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.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureYBand; +import com.google.gson.Gson; +import com.volmit.vanilla.StartMemo; + +/** + * How {@code iris:structure} places and fits one platform structure, or one start: how far it moves the platform's own + * starts and into which band of world heights, whether they keep the platform's height, the foundation columns built + * under their pieces and how they meet the terrain. A start the module places itself carries its fit as a memo, the + * JSON of its terrain and stilts, which ownership records keep, so its later chunks use the fit it began with. + * + * @param yBand null for no band + * @param stilts null for no foundation columns + * @param terrain null for the structure's own terrain adaptation (SOURCE) + */ +public record NativeStructureFit(int yShift, StructureYBand yBand, boolean keepsSourceY, StructureStilts stilts, + StructureTerrain terrain) { + /** The platform's starts as the platform makes them. */ + public static final NativeStructureFit NONE = new NativeStructureFit(0, null, false, null, null); + + private static final Gson MEMO_JSON = new Gson(); + private static final String NO_STILTS = "null"; + + /** The fit a start's memo records: its terrain and stilts, with no vertical adjustment. */ + public static NativeStructureFit of(StartMemo memo) { + StructureStilts stilts = NO_STILTS.equals(memo.foundation()) + ? null : MEMO_JSON.fromJson(memo.foundation(), StructureStilts.class); + StructureTerrain terrain = MEMO_JSON.fromJson(memo.terrain(), StructureTerrain.class); + if (terrain == null) { + throw new IllegalStateException("A start's memo has no terrain fit: " + memo); + } + return new NativeStructureFit(0, null, false, stilts, terrain); + } + + /** The memo of a start placed with this fit's terrain and stilts. */ + public StartMemo memo() { + return new StartMemo(MEMO_JSON.toJson(resolvedTerrain()), MEMO_JSON.toJson(stilts)); + } + + /** The terrain fitting; the structure's own adaptation (SOURCE) when none is set. */ + public StructureTerrain resolvedTerrain() { + return terrain == null ? new StructureTerrain() : terrain; + } + + public NativeStructureFit shifted(int blocks) { + return new NativeStructureFit(Math.addExact(yShift, blocks), yBand, keepsSourceY, stilts, terrain); + } + + /** + * Both fits, {@code later} after this one: shifts add up, keeping the platform's height sticks, and a band, stilts + * or terrain {@code later} states replaces this one's. + */ + public NativeStructureFit then(NativeStructureFit later) { + return new NativeStructureFit(Math.addExact(yShift, later.yShift), + later.yBand == null ? yBand : later.yBand, + keepsSourceY || later.keepsSourceY, + later.stilts == null ? stilts : later.stilts, + later.terrain == null ? terrain : later.terrain); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java similarity index 67% rename from src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java rename to src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java index 005a14c9c..ccaf5a5a4 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaHook.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java @@ -23,33 +23,33 @@ import art.arcane.iris.core.modules.IrisPackWorld; 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.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; -import com.google.gson.Gson; import com.volmit.resource.ResourceId; -import com.volmit.vanilla.JigsawOverrides; -import com.volmit.vanilla.StructureStilts; -import com.volmit.vanilla.StructureTerrain; -import com.volmit.vanilla.VanillaStructureAdjustment; +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.VanillaStructureFit; -import com.volmit.vanilla.VanillaStructureHook; import com.volmit.vanilla.VanillaStructureRule; import com.volmit.vanilla.VanillaStructureSetup; import com.volmit.vanilla.VanillaStructureStart; import com.volmit.vanilla.VanillaStructureStartContext; import java.util.List; +import java.util.Optional; /** * What {@code iris:structure} says about the platform's own structures. The dimension's {@code importedStructures} - * settings ({@link ImportedStructures}) disable, adjust and set them up; the pack's structure placements replace - * them ({@code vanillaSource} with native suppression), place them alongside ({@link IrisStructureLocator#isPlaced}) - * and start them where their {@code nativeStructures} grids say ({@link NativeStartPlanner}). + * 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}). */ -public final class StructureVanillaHook implements VanillaStructureHook { - private static final Gson SAME_JSON = new Gson(); - +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 @@ -66,11 +66,6 @@ public final class StructureVanillaHook implements VanillaStructureHook { return placed ? rule.and(VanillaStructureRule.ALSO_PLACE) : rule; } - @Override - public VanillaStructureAdjustment adjustment(ResourceId structure, boolean underground, VanillaStructureContext context) { - return ImportedStructures.of(context.settings()).adjustment(structure.toString(), underground); - } - @Override public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { Engine engine = IrisPackWorld.of(context.world()).engine(); @@ -79,18 +74,43 @@ public final class StructureVanillaHook implements VanillaStructureHook { .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(); } - /** {@code plan} as the start the platform generates: heights above the bottom, the placement's fit and identity. */ + /** {@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) { IrisStructurePlacement placement = plan.placement(); + NativeStructureFit fit = new NativeStructureFit(0, null, false, placement.getStilt(), placement.resolvedTerrain()); VanillaStructureStart start = VanillaStructureStart.at(ResourceId.parse(plan.source().getStructure()), plan.chunkX(), plan.chunkZ(), plan.baseY() - minHeight) .withIdentity(StructurePlacementGrid.placementIdentity(placement)) - .withFit(fit(placement)); + .withMemo(fit.memo()); if (placement.isUnderground()) { start = start.underground(); } @@ -98,18 +118,8 @@ public final class StructureVanillaHook implements VanillaStructureHook { start = start.replacingPlatformStart(); } if (plan.source().getJigsaw() != null) { - start = start.withJigsaw(sameJson(plan.source().getJigsaw(), JigsawOverrides.class)); + start = start.withJigsaw(plan.source().getJigsaw()); } return start; } - - private static VanillaStructureFit fit(IrisStructurePlacement placement) { - VanillaStructureFit fit = VanillaStructureFit.SOURCE.withTerrain(sameJson(placement.resolvedTerrain(), StructureTerrain.class)); - return placement.getStilt() == null ? fit : fit.withStilts(sameJson(placement.getStilt(), StructureStilts.class)); - } - - /** The placement classes are Iris's; the API values read the same JSON. */ - private static T sameJson(Object irisValue, Class apiType) { - return SAME_JSON.fromJson(SAME_JSON.toJsonTree(irisValue), apiType); - } } diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java new file mode 100644 index 000000000..dd068ff8f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java @@ -0,0 +1,75 @@ +/* + * 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 com.volmit.mantle.BlockBox; + +/** A box of world blocks, every bound inclusive and Y in world heights, the way the platform's structures measure. */ +record Box(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + /** {@code box}, an API box above the dimension's bottom with exclusive maxima, in world heights. */ + static Box of(BlockBox box, int bottomY) { + return new Box(box.minX(), box.minY() + bottomY, box.minZ(), + box.maxX() - 1, box.maxY() - 1 + bottomY, box.maxZ() - 1); + } + + /** This box as an API box above the dimension's bottom. */ + BlockBox toApi(int bottomY) { + return new BlockBox(minX, minY - bottomY, minZ, maxX + 1, maxY + 1 - bottomY, maxZ + 1); + } + + int xSpan() { + return maxX - minX + 1; + } + + int ySpan() { + return maxY - minY + 1; + } + + int zSpan() { + return maxZ - minZ + 1; + } + + boolean contains(int x, int y, int z) { + return x >= minX && x <= maxX && y >= minY && y <= maxY && z >= minZ && z <= maxZ; + } + + boolean intersects(Box other) { + return maxX >= other.minX && minX <= other.maxX && maxY >= other.minY && minY <= other.maxY + && maxZ >= other.minZ && minZ <= other.maxZ; + } + + boolean intersectsHorizontally(Box other) { + return maxX >= other.minX && minX <= other.maxX && maxZ >= other.minZ && minZ <= other.maxZ; + } + + /** This box grown by {@code blocks} sideways, keeping its heights. */ + Box widened(int blocks) { + return new Box(minX - blocks, minY, minZ - blocks, maxX + blocks, maxY, maxZ + blocks); + } + + Box encapsulating(Box other) { + return new Box(Math.min(minX, other.minX), Math.min(minY, other.minY), Math.min(minZ, other.minZ), + Math.max(maxX, other.maxX), Math.max(maxY, other.maxY), Math.max(maxZ, other.maxZ)); + } + + /** The column index of a block of this box's columns, rows along X. */ + int columnIndex(int x, int z) { + return (z - minZ) * xSpan() + x - minX; + } +} 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 new file mode 100644 index 000000000..04665da60 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java @@ -0,0 +1,172 @@ +/* + * 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 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; + } + } + + /** The platform's start has no value equality, so the key pins the exact start a chunk carves against. */ + private record CarveFootprintKey(Object start, int padding) { + } + + private record CachedCarveFootprint(StructureCarvingFootprint footprint, int cells) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java new file mode 100644 index 000000000..d13254c43 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java @@ -0,0 +1,112 @@ +/* + * 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 com.volmit.block.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.resource.ResourceId; +import com.volmit.world.BlockAccess; + +/** + * The chunk's live blocks in world heights, and the block questions the structure fit asks. The fit's rules were + * written in world heights (deepslate below 0, bands of world Y, noise sampled at world heights), so it keeps them and + * converts here. + */ +final class FitBlocks { + static final BlockState AIR = new BlockState("minecraft:air"); + static final BlockState STONE = new BlockState("minecraft:stone"); + static final BlockState COBBLESTONE = new BlockState("minecraft:cobblestone"); + private static final ResourceId STRUCTURE_VOID = ResourceId.parse("minecraft:structure_void"); + private static final ResourceId JIGSAW = ResourceId.parse("minecraft:jigsaw"); + private static final ResourceId LOGS_TAG = ResourceId.parse("minecraft:logs"); + private static final ResourceId LEAVES_TAG = ResourceId.parse("minecraft:leaves"); + + private final BlockAccess access; + private final int bottomY; + + FitBlocks(BlockAccess access, int bottomY) { + this.access = access; + this.bottomY = bottomY; + } + + int bottomY() { + return bottomY; + } + + BlockState get(int x, int y, int z) { + return access.get(x, y - bottomY, z); + } + + void set(int x, int y, int z, BlockState state) { + access.set(x, y - bottomY, z, state); + } + + boolean isAir(BlockState state) { + return access.is(state, BlockTrait.AIR); + } + + boolean isSolid(BlockState state) { + return access.is(state, BlockTrait.SOLID); + } + + boolean holdsFluid(BlockState state) { + return access.is(state, BlockTrait.FLUID); + } + + /** Logs, wood, stems, hyphae and leaves: the blocks of trees the fit never treats as terrain. */ + boolean isTree(BlockState state) { + return access.is(state, BlockTrait.LOG) || access.is(state, BlockTrait.LEAVES); + } + + /** Logs or leaves by the platform's tags alone, as stilts tell vegetation from ground. */ + boolean isTaggedVegetation(BlockState state) { + return access.inTag(state, LOGS_TAG) || access.inTag(state, LEAVES_TAG); + } + + boolean inTag(BlockState state, ResourceId tag) { + return access.inTag(state, tag); + } + + /** Solid ground that is not part of a tree. */ + boolean isTerrain(BlockState state) { + return isSolid(state) && !isTree(state); + } + + /** Air or anything holding a fluid: the cells a fill may claim. */ + boolean isEncaseable(BlockState state) { + return isAir(state) || holdsFluid(state); + } + + /** A block a structure can stand on: solid, dry, and neither structure void nor a jigsaw. */ + boolean isSolidBase(BlockState state) { + return state != null && isSolid(state) + && !state.material().equals(STRUCTURE_VOID) + && !state.material().equals(JIGSAW) + && !holdsFluid(state); + } + + boolean sturdyTop(int x, int y, int z) { + return access.sturdy(x, y - bottomY, z, BlockFace.UP); + } + + BlockState fluidOf(BlockState state) { + return access.fluid(state); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPalettes.java similarity index 63% rename from src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java rename to src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPalettes.java index befae80d4..89b10df9e 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureGenerationStatus.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPalettes.java @@ -16,11 +16,14 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.structure.vanilla; +package art.arcane.iris.engine.framework.structure.fit; -public enum NativeStructureGenerationStatus { - GENERATE_NATIVE, - DISABLED_BY_PACK, - REPLACED_BY_IRIS, - INVALID_REGISTRY_KEY +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; + +/** Picks a block of a pack palette for the structure fit, seeded the way the fit's own randomness is. */ +@FunctionalInterface +interface FitPalettes { + /** The block {@code palette}, seeded with {@code seed}, gives at the world position. */ + BlockState at(PaletteSpec palette, long seed, int x, int y, int z); } diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java new file mode 100644 index 000000000..13389c1e0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java @@ -0,0 +1,102 @@ +/* + * 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 com.volmit.vanilla.PieceKind; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.TemplateCells; +import com.volmit.world.BlockPosition; + +import java.util.ArrayList; +import java.util.List; + +/** A piece of a start in world heights with inclusive bounds. */ +final class FitPiece { + private final StructureFit.Piece piece; + private final Box box; + private final int bottomY; + + FitPiece(StructureFit.Piece piece, int bottomY) { + this.piece = piece; + this.box = Box.of(piece.box(), bottomY); + this.bottomY = bottomY; + } + + Box box() { + return box; + } + + PieceKind kind() { + return piece.kind(); + } + + boolean isJigsaw() { + return piece.kind() != PieceKind.FIXED; + } + + boolean isRigid() { + return piece.kind() == PieceKind.RIGID; + } + + /** Whether the piece keeps its shape over the terrain: every piece built in code, and rigid jigsaw pieces. */ + boolean isRigidOrFixed() { + return piece.kind() != PieceKind.TERRAIN_MATCHING; + } + + int groundLevelDelta() { + return piece.groundLevelDelta(); + } + + /** The world height of the piece's ground level. */ + int groundY() { + return box.minY() + piece.groundLevelDelta(); + } + + /** The junctions, their Y the world height of the ground at their source. */ + List junctions() { + List junctions = new ArrayList<>(piece.junctions().size()); + for (BlockPosition junction : piece.junctions()) { + junctions.add(new BlockPosition(junction.x(), junction.y() + bottomY, junction.z())); + } + return junctions; + } + + TemplateCells cells(Box region) { + return piece.cells(region.toApi(bottomY)); + } + + /** The cell's world height. */ + int cellY(TemplateCells cells, int cell) { + return cells.y(cell) + bottomY; + } + + void columns(StructureFit.ColumnVisitor visitor) { + piece.columns((x, z, minY, maxY) -> visitor.column(x, z, minY + bottomY, maxY + bottomY)); + } + + /** Legacy template air inside {@code clip}, in world heights. */ + List legacyAir(Box clip) { + List air = piece.legacyAir(clip.toApi(bottomY)); + List world = new ArrayList<>(air.size()); + for (BlockPosition position : air) { + world.add(new BlockPosition(position.x(), position.y() + bottomY, position.z())); + } + return world; + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java new file mode 100644 index 000000000..07c9187ca --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java @@ -0,0 +1,94 @@ +/* + * 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.StructureTerrain; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import com.volmit.vanilla.StructureFit; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TerrainAdaptation; + +import java.util.ArrayList; +import java.util.List; + +/** A start the platform places in the chunk, with the fit {@code iris:structure} gives it, its pieces in world heights. */ +final class FitStart { + private final StructureFit.Start start; + private final NativeStructureFit fit; + private final List pieces; + + FitStart(StructureFit.Start start, NativeStructureFit fit, int bottomY) { + this.start = start; + this.fit = fit; + List converted = new ArrayList<>(start.pieces().size()); + for (StructureFit.Piece piece : start.pieces()) { + converted.add(new FitPiece(piece, bottomY)); + } + this.pieces = List.copyOf(converted); + } + + StructureFit.Start start() { + return start; + } + + String structureId() { + return start.structure().toString(); + } + + NativeStructureFit fit() { + return fit; + } + + StructureTerrain terrain() { + return fit.resolvedTerrain(); + } + + TerrainAdaptation adaptation() { + return start.adaptation(); + } + + StructureStep step() { + return start.step(); + } + + int chunkX() { + return start.chunkX(); + } + + int chunkZ() { + return start.chunkZ(); + } + + List pieces() { + return pieces; + } + + /** The box around every piece of the start. */ + Box contentBounds() { + Box bounds = pieces.getFirst().box(); + for (FitPiece piece : pieces) { + bounds = bounds.encapsulating(piece.box()); + } + return bounds; + } + + Object key() { + return start.key(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java new file mode 100644 index 000000000..f2ef96888 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FoundationStilts.java @@ -0,0 +1,156 @@ +/* + * 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 com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; + +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.IntBinaryOperator; + +/** + * Foundation columns under a placed start: in every column of the start's foundation envelope (the pieces' lowest + * layers up to one above their ground), from the lowest solid block placed there down to the first block that can + * carry it, the terrain's surface for a surface structure, at most {@code maxDepth} blocks deep. Sparse stilts keep + * only the columns on their spacing grid. + * + *

These are the vanilla structures' stilts. Objects grow theirs from their own bottom layer instead + * ({@code iris:stilt}): repeated object blocks, eroded or organic tips and a ceiling hang have no counterpart here, and + * these columns have no counterpart there, so the two stay separate. + */ +final class FoundationStilts { + private static final int FOUNDATION_VERTICAL_TOLERANCE = 1; + + private FoundationStilts() { + } + + static void placeStilts(FitBlocks blocks, Box area, FitStart start, StructureStilts settings, long seed, + FitPalettes palettes, IntBinaryOperator surfaceHeight, boolean surfaceStructure) { + Objects.requireNonNull(surfaceHeight, "Structure stilts require an Iris terrain height resolver"); + Optional palette = settings.palette(); + long paletteSeed = seed ^ start.structureId().hashCode(); + for (FoundationColumn column : foundationEnvelope(area, start)) { + if (!isStiltColumn(column.x(), column.z(), settings.spacing())) { + continue; + } + int foundationY = findFoundationY(blocks, column); + if (foundationY == Integer.MIN_VALUE) { + continue; + } + int terrainY = surfaceStructure + ? Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(column.x(), column.z()))) + : area.minY() - 1; + int anchorY = findStiltAnchorY(blocks, column.x(), column.z(), foundationY, + Math.max(1, settings.maxDepth()), terrainY, area.minY()); + if (anchorY == Integer.MIN_VALUE) { + continue; + } + for (int y = foundationY - 1; y > anchorY; y--) { + BlockState stilt = palette.isEmpty() + ? FitBlocks.COBBLESTONE + : Objects.requireNonNull(palettes.at(palette.get(), paletteSeed, column.x(), y, column.z()), + "Stilt palette returned no block for " + start.structureId() + " at " + + column.x() + "," + y + "," + column.z()); + blocks.set(column.x(), y, column.z(), stilt); + } + } + } + + static boolean isStiltColumn(int x, int z, int spacing) { + int resolvedSpacing = Math.max(1, spacing); + return resolvedSpacing == 1 || Math.floorMod(x, resolvedSpacing) == 0 && Math.floorMod(z, resolvedSpacing) == 0; + } + + static int findStiltAnchorY(FitBlocks blocks, int x, int z, int foundationY, int maxDepth, int terrainY, + int areaMinY) { + int minimumAnchorY = Math.max(areaMinY, Math.max(terrainY, foundationY - maxDepth - 1)); + for (int y = foundationY - 1; y >= minimumAnchorY; y--) { + BlockState state = blocks.get(x, y, z); + if (!blocks.isTaggedVegetation(state) && blocks.sturdyTop(x, y, z)) { + return y; + } + } + return Integer.MIN_VALUE; + } + + private static List foundationEnvelope(Box area, FitStart start) { + Box structure = start.contentBounds(); + int minX = Math.max(area.minX(), structure.minX()); + int minZ = Math.max(area.minZ(), structure.minZ()); + int maxX = Math.min(area.maxX(), structure.maxX()); + int maxZ = Math.min(area.maxZ(), structure.maxZ()); + if (minX > maxX || minZ > maxZ) { + return List.of(); + } + List columns = new ArrayList<>((maxX - minX + 1) * (maxZ - minZ + 1)); + BitSet envelope = new BitSet(area.ySpan()); + for (int z = minZ; z <= maxZ; z++) { + for (int x = minX; x <= maxX; x++) { + envelope.clear(); + markFoundationEnvelope(envelope, start, area, x, z); + int cellCount = envelope.cardinality(); + if (cellCount == 0) { + continue; + } + int[] ys = new int[cellCount]; + int cell = 0; + for (int bit = envelope.nextSetBit(0); bit >= 0; bit = envelope.nextSetBit(bit + 1)) { + ys[cell++] = area.minY() + bit; + } + columns.add(new FoundationColumn(x, z, ys)); + } + } + return List.copyOf(columns); + } + + private static void markFoundationEnvelope(BitSet envelope, FitStart start, Box area, int x, int z) { + for (FitPiece piece : start.pieces()) { + Box bounds = piece.box(); + if (x < bounds.minX() || x > bounds.maxX() || z < bounds.minZ() || z > bounds.maxZ()) { + continue; + } + int groundY = piece.groundY(); + if (piece.isJigsaw() && groundY < bounds.minY()) { + continue; + } + int minY = Math.max(area.minY(), bounds.minY()); + int maxY = Math.min(area.maxY(), Math.min(bounds.maxY(), groundY + FOUNDATION_VERTICAL_TOLERANCE)); + if (minY <= maxY) { + envelope.set(minY - area.minY(), maxY - area.minY() + 1); + } + } + } + + private static int findFoundationY(FitBlocks blocks, FoundationColumn column) { + for (int y : column.ys()) { + if (blocks.isSolid(blocks.get(column.x(), y, column.z()))) { + return y; + } + } + return Integer.MIN_VALUE; + } + + private record FoundationColumn(int x, int z, int[] ys) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java new file mode 100644 index 000000000..d0b927e20 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java @@ -0,0 +1,271 @@ +/* + * 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 com.volmit.block.BlockState; +import com.volmit.vanilla.TemplateCells; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Closes the short gaps between two rigid pieces of one surface start whose ground planes are one or two blocks apart: + * where the upper piece's lowest solid base sits two blocks over the lower piece's ground, the gap is filled with the + * terrain under the lower piece, so steps and terraces stand on ground instead of air. Only the chunk's own blocks are + * filled, never across starts, and nothing at all when the work would exceed its budget. + */ +final class RigidSupport { + private static final int MAX_BATCH_CELLS = 524_288; + private static final int MAX_BRIDGE_SPAN = 2; + + private RigidSupport() { + } + + static Set bridgeRigidPieceSupport(FitBlocks blocks, Box area, List starts) { + if (starts.isEmpty()) { + return Set.of(); + } + Map planned; + try { + BatchCellBudget budget = new BatchCellBudget(); + List requests = new ArrayList<>(); + Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); + for (FitStart start : starts) { + if (!SurfaceFitting.requiresSurfaceTerrain(start) || !seenStarts.add(start.key())) { + continue; + } + collectStartRequests(blocks, area, start, budget, requests); + } + planned = planWrites(blocks, area, requests, budget); + } catch (BatchBudgetExceeded ignored) { + return Set.of(); + } + if (planned.isEmpty()) { + return Set.of(); + } + List> ordered = new ArrayList<>(planned.entrySet()); + ordered.sort(Map.Entry.comparingByKey()); + Set written = new HashSet<>(); + for (Map.Entry entry : ordered) { + int x = TemplateFootprint.packedX(entry.getKey()); + int y = TemplateFootprint.packedY(entry.getKey()); + int z = TemplateFootprint.packedZ(entry.getKey()); + BlockState existing = blocks.get(x, y, z); + if (!blocks.isSolid(existing) && !blocks.isTree(existing) && !blocks.holdsFluid(existing)) { + blocks.set(x, y, z, entry.getValue()); + written.add(entry.getKey()); + } + } + return Set.copyOf(written); + } + + private static void collectStartRequests(FitBlocks blocks, Box area, FitStart start, BatchCellBudget budget, + List requests) { + List anchors = rigidAnchors(start); + if (anchors.size() < 2) { + return; + } + for (RigidAnchor upper : anchors) { + Map lowerMeets = candidateLowerMeets(area, upper, anchors, budget); + if (lowerMeets.isEmpty()) { + continue; + } + TemplateCells cells = upper.piece().cells(area); + budget.consume(cells.readBlocks()); + if (!cells.resolved()) { + continue; + } + for (Map.Entry entry + : lowestBridgeableCells(cells, upper.piece(), area, lowerMeets).entrySet()) { + TemplateFootprint.Cell cell = entry.getValue(); + Integer lowerMeet = lowerMeets.get(entry.getKey()); + if (lowerMeet == null || cell.blocker() || !blocks.isSolidBase(cell.state()) + || cell.y() - lowerMeet < 2 || cell.y() - lowerMeet > MAX_BRIDGE_SPAN) { + continue; + } + budget.consume(1); + requests.add(new SupportRequest(cell.x(), cell.z(), lowerMeet, cell.y())); + } + } + } + + /** + * The lowest cell of each column over a lower piece's ground, among the cells no higher than the widest bridge + * above that ground: the cells the support could stand under. + */ + private static Map lowestBridgeableCells(TemplateCells cells, FitPiece piece, Box area, + Map lowerMeets) { + Map lowest = new HashMap<>(); + for (int cell = 0; cell < cells.size(); cell++) { + int x = cells.x(cell); + int y = piece.cellY(cells, cell); + int z = cells.z(cell); + long column = TemplateFootprint.columnKey(x, z); + Integer lowerMeet = lowerMeets.get(column); + if (!area.contains(x, y, z) || lowerMeet == null || y > lowerMeet + MAX_BRIDGE_SPAN) { + continue; + } + TemplateFootprint.Cell current = lowest.get(column); + if (current == null || y < current.y()) { + lowest.put(column, new TemplateFootprint.Cell(x, y, z, cells.state(cell))); + } + } + return lowest; + } + + private static List rigidAnchors(FitStart start) { + List anchors = new ArrayList<>(); + for (FitPiece piece : start.pieces()) { + if (!piece.isRigid()) { + continue; + } + anchors.add(new RigidAnchor(piece, piece.box(), piece.groundY() - 1)); + } + return List.copyOf(anchors); + } + + private static Map candidateLowerMeets(Box area, RigidAnchor upper, List anchors, + BatchCellBudget budget) { + Map lowerMeets = new HashMap<>(); + for (RigidAnchor lower : anchors) { + budget.consume(1); + int span = upper.meetY() - lower.meetY(); + if (lower.piece() == upper.piece() || span < 1 || span > MAX_BRIDGE_SPAN + || lower.meetY() < area.minY() || lower.meetY() > area.maxY()) { + continue; + } + int minimumX = Math.max(area.minX(), Math.max(upper.bounds().minX(), lower.bounds().minX())); + int maximumX = Math.min(area.maxX(), Math.min(upper.bounds().maxX(), lower.bounds().maxX())); + int minimumZ = Math.max(area.minZ(), Math.max(upper.bounds().minZ(), lower.bounds().minZ())); + int maximumZ = Math.min(area.maxZ(), Math.min(upper.bounds().maxZ(), lower.bounds().maxZ())); + if (minimumX > maximumX || minimumZ > maximumZ) { + continue; + } + for (int x = minimumX; x <= maximumX; x++) { + for (int z = minimumZ; z <= maximumZ; z++) { + budget.consume(1); + lowerMeets.merge(TemplateFootprint.columnKey(x, z), lower.meetY(), Math::max); + } + } + } + return lowerMeets; + } + + private static Map planWrites(FitBlocks blocks, Box area, List requests, + BatchCellBudget budget) { + List eligible = new ArrayList<>(); + Set materialKeys = new HashSet<>(); + for (SupportRequest request : requests) { + BlockState lowerTerrain = blocks.get(request.x(), request.lowerMeetY(), request.z()); + if (!isTerrainSupport(blocks, lowerTerrain) || !gapIsClear(blocks, area, request, budget)) { + continue; + } + eligible.add(request); + materialKeys.add(new MaterialKey(request.x(), request.z(), request.lowerMeetY())); + } + Map materials = new HashMap<>(); + for (MaterialKey key : materialKeys) { + materials.put(key, resolveSupportState(blocks, key.x(), key.z(), key.lowerMeetY(), budget)); + } + Map planned = new HashMap<>(); + Set conflicts = new HashSet<>(); + eligible.sort(Comparator.comparingInt(SupportRequest::x) + .thenComparingInt(SupportRequest::z) + .thenComparingInt(SupportRequest::lowerMeetY) + .thenComparingInt(SupportRequest::baseY)); + for (SupportRequest request : eligible) { + BlockState material = materials.get(new MaterialKey(request.x(), request.z(), request.lowerMeetY())); + for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) { + budget.consume(1); + long positionKey = TemplateFootprint.packedPosition(request.x(), y, request.z()); + if (conflicts.contains(positionKey)) { + continue; + } + BlockState existing = planned.putIfAbsent(positionKey, material); + if (existing != null && !existing.equals(material)) { + planned.remove(positionKey); + conflicts.add(positionKey); + } + } + } + return planned; + } + + private static boolean gapIsClear(FitBlocks blocks, Box area, SupportRequest request, BatchCellBudget budget) { + for (int y = request.lowerMeetY() + 1; y < request.baseY(); y++) { + budget.consume(1); + if (!area.contains(request.x(), y, request.z())) { + return false; + } + BlockState state = blocks.get(request.x(), y, request.z()); + if (blocks.isSolid(state) || blocks.isTree(state) || blocks.holdsFluid(state)) { + return false; + } + } + return true; + } + + private static BlockState resolveSupportState(FitBlocks blocks, int x, int z, int lowerMeetY, BatchCellBudget budget) { + budget.consume(1); + BlockState below = blocks.get(x, lowerMeetY - 1, z); + if (isTerrainSupport(blocks, below)) { + return below; + } + return blocks.get(x, lowerMeetY, z); + } + + private static boolean isTerrainSupport(FitBlocks blocks, BlockState state) { + return blocks.isSolid(state) && !blocks.isTree(state) && !blocks.holdsFluid(state); + } + + private record RigidAnchor(FitPiece piece, Box bounds, int meetY) { + } + + private record SupportRequest(int x, int z, int lowerMeetY, int baseY) { + } + + private record MaterialKey(int x, int z, int lowerMeetY) { + } + + private static final class BatchCellBudget { + private int consumed; + + private void consume(int amount) { + if (amount < 0 || consumed > MAX_BATCH_CELLS - amount) { + throw BatchBudgetExceeded.INSTANCE; + } + consumed += amount; + } + } + + private static final class BatchBudgetExceeded extends RuntimeException { + private static final BatchBudgetExceeded INSTANCE = new BatchBudgetExceeded(); + + private BatchBudgetExceeded() { + super(null, null, false, false); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java new file mode 100644 index 000000000..7ef0c5255 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java @@ -0,0 +1,112 @@ +/* + * 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.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureYBand; +import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.mantle.BlockBox; +import com.volmit.vanilla.PlatformStart; +import com.volmit.vanilla.StartReach; + +/** + * Where the platform's own starts sit and how far {@code iris:structure} changes the terrain around a start. A start + * that keeps the platform's height only takes its shift; a band moves the start's middle into it, chosen per start + * chunk; an underground start is buried under the lowest terrain column above it; anything else takes its shift. A + * structure the host aligns itself only takes its shift on top of that alignment. + */ +public final class StartLayouts { + private static final int MAX_BURIAL_COLUMNS = 2_000_000; + private static final int UNDERGROUND_SURFACE_CLEARANCE = 1; + private static final long BAND_IDENTITY_X = 341873128712L; + private static final long BAND_IDENTITY_Z = 132897987541L; + + private StartLayouts() { + } + + /** How far {@code start} moves up (negative: down) under {@code fit}, before the host keeps it inside the world. */ + public static int shift(PlatformStart start, NativeStructureFit fit) { + if (start.aligned() || fit.keepsSourceY()) { + return fit.yShift(); + } + if (fit.yBand() != null) { + return bandShift(start, fit.yBand()); + } + if (start.underground()) { + return burialShift(start, fit.yShift()); + } + return fit.yShift(); + } + + /** How far around its pieces a start with {@code terrain} changes the terrain. */ + public static StartReach reach(StructureTerrain terrain) { + return switch (terrain.resolvedMode()) { + case SOURCE -> StartReach.PLATFORM; + case PRESERVE -> StartReach.blocks(0); + case VACUUM -> StartReach.blocks(SurfaceFitting.surfaceTerrainRadius()); + case BORE, FORCE_CARVE, ENCASE -> StartReach.blocks(Math.max(0, terrain.horizontalPadding())); + }; + } + + private static int bandShift(PlatformStart start, StructureYBand band) { + BlockBox bounds = start.bounds(); + int minY = bounds.minY() + start.bottomY(); + int maxY = bounds.maxY() - 1 + start.bottomY(); + int target = bandTargetMidpointY(minY, maxY, band.resolvedMin(), band.resolvedMax(), start.chunkX(), start.chunkZ()); + return Math.subtractExact(target, minY + (maxY - minY) / 2); + } + + /** The world height the middle of a start from {@code maxY - minY} high moves to, inside the band, per start chunk. */ + static int bandTargetMidpointY(int minY, int maxY, int bandMin, int bandMax, int chunkX, int chunkZ) { + int height = Math.subtractExact(maxY, minY); + int lowest = Math.addExact(bandMin, height / 2); + int highest = Math.subtractExact(bandMax, height - height / 2); + if (lowest > highest) { + // The band is shorter than the structure, so only its midpoint can be honoured. + return Math.floorDiv(Math.addExact(bandMin, bandMax), 2); + } + int span = highest - lowest + 1; + if (span == 1) { + return lowest; + } + long identity = (long) chunkX * BAND_IDENTITY_X ^ (long) chunkZ * BAND_IDENTITY_Z; + return lowest + new RNG(identity).nextInt(span); + } + + /** At most {@code requestedShift}, and low enough that the start's top stays a block under every terrain column. */ + private static int burialShift(PlatformStart start, int requestedShift) { + BlockBox bounds = start.bounds(); + long width = (long) bounds.maxX() - bounds.minX(); + long depth = (long) bounds.maxZ() - bounds.minZ(); + if (width <= 0L || depth <= 0L || width > MAX_BURIAL_COLUMNS / depth) { + throw new IllegalStateException("Underground native structure burial footprint is invalid or exceeds " + + MAX_BURIAL_COLUMNS + " columns"); + } + int topY = bounds.maxY() - 1; + int maximumShift = requestedShift; + for (int x = bounds.minX(); x < bounds.maxX(); x++) { + for (int z = bounds.minZ(); z < bounds.maxZ(); z++) { + int allowedTopY = start.surfaceY(x, z) - UNDERGROUND_SURFACE_CLEARANCE; + maximumShift = Math.min(maximumShift, allowedTopY - topY); + } + } + return maximumShift; + } +} 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 new file mode 100644 index 000000000..00a49a70c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java @@ -0,0 +1,129 @@ +/* + * 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); + 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/SurfaceFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java new file mode 100644 index 000000000..262188652 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -0,0 +1,713 @@ +/* + * 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.StructureTerrainMode; +import art.arcane.iris.engine.object.placement.IrisObjectVacuum; +import art.arcane.iris.spi.IrisLogging; +import com.volmit.block.BlockState; +import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.TemplateCells; +import com.volmit.vanilla.TerrainAdaptation; +import com.volmit.world.BlockPosition; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.IntBinaryOperator; + +/** + * Fits the surface around the platform's surface structures before their pieces are placed. SOURCE replays the + * platform's beard adaptation: the terrain within 12 blocks of the structure's ground planes bends toward them, never + * more than 6 blocks. VACUUM raises the terrain to meet the processed solid foundations of rigid pieces, again over 12 + * blocks, without ever lowering it, and after the pieces are placed fills the gaps left under their bases + * ({@link #repairVacuumFoundations}). + */ +final class SurfaceFitting { + private static final double SURFACE_TERRAIN_FALLOFF = 2.0; + private static final long SURFACE_TERRAIN_INFLUENCE_SCALE = 1_000_000L; + private static final int SURFACE_TERRAIN_RADIUS = 12; + private static final int MAX_SOURCE_SURFACE_DELTA = 6; + static final int MAX_SURFACE_TEMPLATE_CELLS = 4_194_304; + private static final int FOUNDATION_ANCHOR_STRENGTH = 2; + private static final int JUNCTION_ANCHOR_STRENGTH = 1; + private static final Set WARNED_SOURCE_BUDGET = ConcurrentHashMap.newKeySet(); + private static final Set WARNED_VACUUM_BUDGET = ConcurrentHashMap.newKeySet(); + + private SurfaceFitting() { + } + + /** The radius of the surface falloff, which a VACUUM start reaches beyond its pieces. */ + static int surfaceTerrainRadius() { + return SURFACE_TERRAIN_RADIUS; + } + + static VacuumFoundationPlan prepareSurfaceStructures(FitBlocks blocks, Box area, List starts, + IntBinaryOperator surfaceHeight, int maximumTemplateCells) { + if (starts.isEmpty()) { + return VacuumFoundationPlan.EMPTY; + } + Objects.requireNonNull(surfaceHeight, "Surface structure terrain fitting requires an Iris height resolver"); + List anchors = collectSourceSurfaceAnchors(blocks, area, starts, maximumTemplateCells); + if (!anchors.isEmpty()) { + fitSurfaceTerrain(blocks, area, anchors, surfaceHeight); + } + VacuumFootprint vacuum = collectVacuumFootprint(blocks, area, starts, maximumTemplateCells); + if (!vacuum.anchors().isEmpty()) { + fitVacuumTerrain(blocks, area, vacuum, surfaceHeight); + } + return VacuumFoundationPlan.create(vacuum.foundationBases(), vacuum.occupiedCells(), area); + } + + static void repairVacuumFoundations(FitBlocks blocks, Box area, VacuumFoundationPlan plan) { + if (plan == null || plan.foundationBases.isEmpty()) { + return; + } + for (long packedBase : plan.foundationBases) { + int baseX = TemplateFootprint.packedX(packedBase); + int baseY = TemplateFootprint.packedY(packedBase); + int baseZ = TemplateFootprint.packedZ(packedBase); + if (!area.contains(baseX, baseY, baseZ)) { + continue; + } + if (!blocks.isSolidBase(blocks.get(baseX, baseY, baseZ))) { + continue; + } + int supportY = findVacuumFoundationSupport(blocks, area, baseX, baseY - 1, baseZ); + if (supportY == Integer.MIN_VALUE || supportY == baseY - 1) { + continue; + } + if (intersectsVacuumOccupancy(plan.occupiedCells, baseX, baseZ, supportY + 1, baseY - 1)) { + continue; + } + BlockState fill = resolveSurfaceMaterials(blocks, baseX, baseZ, supportY, area.minY()).subsurface(); + for (int y = supportY + 1; y < baseY; y++) { + BlockState existing = blocks.get(baseX, y, baseZ); + if (blocks.isAir(existing) || blocks.holdsFluid(existing)) { + blocks.set(baseX, y, baseZ, fill); + } + } + } + } + + static boolean shouldPrepareSurfaceTerrain(TerrainAdaptation adaptation, StructureStep step) { + return step == StructureStep.SURFACE_STRUCTURES + && (adaptation == TerrainAdaptation.BEARD_THIN || adaptation == TerrainAdaptation.BEARD_BOX); + } + + static int resolveSurfaceTarget(List anchors, int worldX, int worldZ, int originalY) { + return resolveSurface(anchors, worldX, worldZ, originalY).targetY(); + } + + private static SurfaceResolution resolveSurface(List anchors, int worldX, int worldZ, int originalY) { + int localTargetY = originalY; + SurfaceAnchor selectedLocal = null; + long totalInfluence = 0L; + long weightedTargetY = 0L; + long maximumInfluence = 0L; + for (SurfaceAnchor anchor : anchors) { + int outX = IrisObjectVacuum.outset(worldX, anchor.minX(), anchor.maxX()); + int outZ = IrisObjectVacuum.outset(worldZ, anchor.minZ(), anchor.maxZ()); + boolean containsColumn = outX == 0 && outZ == 0; + long distanceSquared = (long) outX * outX + (long) outZ * outZ; + long radiusSquared = (long) SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; + if (distanceSquared > radiusSquared) { + continue; + } + double distance = Math.sqrt(distanceSquared); + double factor = Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF); + if (factor <= 0D) { + continue; + } + int boundedTargetY = boundedSurfaceTarget(originalY, anchor.meetY()); + if (containsColumn) { + if (precedes(anchor, selectedLocal)) { + localTargetY = boundedTargetY; + selectedLocal = anchor; + } + continue; + } + long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE); + if (influence <= 0L) { + continue; + } + long weightedInfluence = influence * Math.max(1, anchor.strength()); + totalInfluence += weightedInfluence; + weightedTargetY += weightedInfluence * boundedTargetY; + maximumInfluence = Math.max(maximumInfluence, influence); + } + if (selectedLocal != null) { + return new SurfaceResolution(localTargetY, + selectedLocal.strength() > 1 && localTargetY == selectedLocal.meetY()); + } + if (totalInfluence == 0L) { + return new SurfaceResolution(originalY, false); + } + double blendedTargetY = weightedTargetY / (double) totalInfluence; + double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE; + return new SurfaceResolution(blendSurfaceTarget(originalY, blendedTargetY, factor), false); + } + + private static int boundedSurfaceTarget(int originalY, int meetY) { + int delta = Math.max(-MAX_SOURCE_SURFACE_DELTA, Math.min(MAX_SOURCE_SURFACE_DELTA, meetY - originalY)); + return originalY + delta; + } + + private static int blendSurfaceTarget(int originalY, double targetY, double factor) { + double delta = (targetY - originalY) * factor; + int magnitude = (int) Math.round(Math.abs(delta)); + return originalY + (delta < 0D ? -magnitude : magnitude); + } + + private static boolean precedes(SurfaceAnchor candidate, SurfaceAnchor selected) { + if (selected == null) { + return true; + } + if (candidate.strength() != selected.strength()) { + return candidate.strength() > selected.strength(); + } + if (candidate.meetY() != selected.meetY()) { + return candidate.meetY() < selected.meetY(); + } + if (candidate.minX() != selected.minX()) { + return candidate.minX() < selected.minX(); + } + if (candidate.minZ() != selected.minZ()) { + return candidate.minZ() < selected.minZ(); + } + if (candidate.maxX() != selected.maxX()) { + return candidate.maxX() < selected.maxX(); + } + if (candidate.maxZ() != selected.maxZ()) { + return candidate.maxZ() < selected.maxZ(); + } + return false; + } + + private static List collectSourceSurfaceAnchors(FitBlocks blocks, Box area, List starts, + int maximumTemplateCells) { + Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); + List anchors = new ArrayList<>(); + Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); + for (FitStart start : starts) { + if (!requiresSourceSurfaceTerrain(start) || !seenStarts.add(start.key())) { + continue; + } + TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells); + boolean budgetExceeded = false; + for (FitPiece piece : start.pieces()) { + if (piece.isJigsaw()) { + if (!budgetExceeded && piece.box().intersectsHorizontally(influenceArea)) { + try { + List pieceAnchors = new ArrayList<>(); + addProcessedSurfaceAnchors(blocks, influenceArea, piece, budget, pieceAnchors); + anchors.addAll(pieceAnchors); + } catch (TemplateBudgetExceeded ignored) { + budgetExceeded = true; + warnBudget(WARNED_SOURCE_BUDGET, start, "SOURCE", + "skipping remaining processed footprints for this start"); + } + } + for (BlockPosition junction : piece.junctions()) { + anchors.add(new SurfaceAnchor(junction.x(), junction.x(), junction.z(), junction.z(), + junction.y() - 1, JUNCTION_ANCHOR_STRENGTH)); + } + continue; + } + Box bounds = piece.box(); + anchors.add(surfaceAnchor(bounds, bounds.minY(), FOUNDATION_ANCHOR_STRENGTH)); + } + } + return List.copyOf(anchors); + } + + private static void addProcessedSurfaceAnchors(FitBlocks blocks, Box influenceArea, FitPiece piece, + TemplateCellBudget budget, List anchors) { + TemplateCells cells = piece.cells(influenceArea); + budget.consume(cells.readBlocks()); + if (!cells.resolved()) { + return; + } + int maximumFoundationY = piece.groundY(); + for (TemplateFootprint.Cell cell : TemplateFootprint.lowestSolidCells(cells, piece, blocks).values()) { + budget.consume(1); + if (piece.isRigid() && cell.y() > maximumFoundationY) { + continue; + } + int groundY = piece.isRigid() ? maximumFoundationY : cell.y(); + Box column = new Box(cell.x(), groundY, cell.z(), cell.x(), groundY, cell.z()); + anchors.add(surfaceAnchor(column, groundY, FOUNDATION_ANCHOR_STRENGTH)); + } + } + + private static void warnBudget(Set warned, FitStart start, String mode, String consequence) { + if (warned.add(start.structureId())) { + IrisLogging.warn("Native structure " + mode + " fitting for '" + start.structureId() + + "' exceeded its bounded template budget; " + consequence); + } + } + + private static VacuumFootprint collectVacuumFootprint(FitBlocks blocks, Box area, List starts, + int maximumTemplateCells) { + Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); + Map anchors = new HashMap<>(); + Map columnCaps = new HashMap<>(); + Set foundationBases = new HashSet<>(); + Set occupiedCells = new HashSet<>(); + Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); + for (FitStart start : starts) { + if (start.terrain().resolvedMode() != StructureTerrainMode.VACUUM || !seenStarts.add(start.key())) { + continue; + } + Map targetAnchors = new HashMap<>(); + Map targetCaps = new HashMap<>(); + Set targetFoundationBases = new HashSet<>(); + Set targetOccupiedCells = new HashSet<>(); + TemplateCellBudget budget = new TemplateCellBudget(maximumTemplateCells); + try { + for (FitPiece piece : start.pieces()) { + if (!piece.box().intersectsHorizontally(influenceArea) || !piece.isRigid()) { + continue; + } + addVacuumJunctionAnchors(anchors, influenceArea, piece); + TemplateCells cells = piece.cells(influenceArea); + budget.consume(cells.readBlocks()); + if (!cells.resolved()) { + continue; + } + for (int cell = 0; cell < cells.size(); cell++) { + targetOccupiedCells.add(TemplateFootprint.packedPosition( + cells.x(cell), piece.cellY(cells, cell), cells.z(cell))); + } + int groundY = piece.groundY() - 1; + for (TemplateFootprint.Cell cell : TemplateFootprint.lowestCells(cells, piece).values()) { + budget.consume(1); + long column = TemplateFootprint.columnKey(cell.x(), cell.z()); + targetCaps.merge(column, Math.min(cell.y(), groundY), Math::min); + if (cell.blocker() || cell.y() > groundY + 1 || !blocks.isSolidBase(cell.state())) { + continue; + } + addVacuumAnchor(targetAnchors, cell.x(), cell.z(), + new VacuumAnchor(cell.y() - 1, FOUNDATION_ANCHOR_STRENGTH)); + targetFoundationBases.add(TemplateFootprint.packedPosition(cell.x(), cell.y(), cell.z())); + } + } + } catch (TemplateBudgetExceeded ignored) { + warnBudget(WARNED_VACUUM_BUDGET, start, "VACUUM", "using jigsaw junction smoothing for oversized starts"); + continue; + } + targetAnchors.forEach((column, anchor) -> anchors.merge(column, anchor, SurfaceFitting::preferredVacuumAnchor)); + targetCaps.forEach((column, cap) -> columnCaps.merge(column, cap, Math::min)); + foundationBases.addAll(targetFoundationBases); + occupiedCells.addAll(targetOccupiedCells); + } + return new VacuumFootprint(Map.copyOf(anchors), Map.copyOf(columnCaps), + Set.copyOf(foundationBases), Set.copyOf(occupiedCells)); + } + + private static void addVacuumJunctionAnchors(Map anchors, Box influenceArea, FitPiece piece) { + for (BlockPosition junction : piece.junctions()) { + if (junction.x() < influenceArea.minX() || junction.x() > influenceArea.maxX() + || junction.z() < influenceArea.minZ() || junction.z() > influenceArea.maxZ()) { + continue; + } + addVacuumAnchor(anchors, junction.x(), junction.z(), + new VacuumAnchor(junction.y() - 1, JUNCTION_ANCHOR_STRENGTH)); + } + } + + private static void addVacuumAnchor(Map anchors, int x, int z, VacuumAnchor candidate) { + anchors.merge(TemplateFootprint.columnKey(x, z), candidate, SurfaceFitting::preferredVacuumAnchor); + } + + private static VacuumAnchor preferredVacuumAnchor(VacuumAnchor first, VacuumAnchor second) { + if (first.strength() != second.strength()) { + return first.strength() > second.strength() ? first : second; + } + return first.surfaceY() <= second.surfaceY() ? first : second; + } + + static SurfaceAnchor surfaceAnchor(Box bounds, int groundY, int strength) { + return new SurfaceAnchor(bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), groundY - 1, strength); + } + + /** Whether the start's pieces need the surface fitted around them: VACUUM, or SOURCE with a beard adaptation. */ + static boolean requiresSurfaceTerrain(FitStart start) { + return start.terrain().resolvedMode() == StructureTerrainMode.VACUUM || requiresSourceSurfaceTerrain(start); + } + + private static boolean requiresSourceSurfaceTerrain(FitStart start) { + return start.terrain().resolvedMode() == StructureTerrainMode.SOURCE + && shouldPrepareSurfaceTerrain(start.adaptation(), start.step()); + } + + private static void fitSurfaceTerrain(FitBlocks blocks, Box area, List anchors, + IntBinaryOperator surfaceHeight) { + int width = area.xSpan(); + int depth = area.zSpan(); + int[] originalHeights = new int[width * depth]; + int[] targetHeights = new int[width * depth]; + boolean[] rigidBaseSupport = new boolean[width * depth]; + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + int originalY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z))); + SurfaceResolution resolution = resolveSurface(anchors, x, z, originalY); + originalHeights[column] = originalY; + targetHeights[column] = Math.max(area.minY(), Math.min(area.maxY(), resolution.targetY())); + rigidBaseSupport[column] = resolution.rigidBaseSupport(); + } + } + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + applySurfaceColumn(blocks, x, z, originalHeights[column], targetHeights[column], area.minY(), area.maxY(), + rigidBaseSupport[column]); + } + } + } + + private static void fitVacuumTerrain(FitBlocks blocks, Box area, VacuumFootprint footprint, + IntBinaryOperator surfaceHeight) { + int width = area.xSpan(); + int depth = area.zSpan(); + int[] originalHeights = new int[width * depth]; + int[] targetHeights = new int[width * depth]; + boolean[] rigidBaseSupport = new boolean[width * depth]; + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + int nominalY = Math.max(area.minY(), Math.min(area.maxY(), surfaceHeight.applyAsInt(x, z))); + long columnKey = TemplateFootprint.columnKey(x, z); + VacuumAnchor local = footprint.anchors().get(columnKey); + Integer cap = footprint.columnCaps().get(columnKey); + boolean suppressed = local != null && local.strength() > 1 && cap != null && cap < local.surfaceY(); + int scanStartY = local != null && local.strength() > 1 && !suppressed + ? Math.max(area.minY(), Math.min(area.maxY(), local.surfaceY())) + : nominalY; + int originalY = resolveVacuumSurfaceHeight(blocks, x, z, scanStartY, area.minY()); + SurfaceResolution resolution = resolveVacuumSurface(footprint, x, z, originalY); + originalHeights[column] = originalY; + targetHeights[column] = Math.max(originalY, Math.min(area.maxY(), resolution.targetY())); + rigidBaseSupport[column] = resolution.rigidBaseSupport() && targetHeights[column] > originalY; + } + } + for (int z = area.minZ(); z <= area.maxZ(); z++) { + for (int x = area.minX(); x <= area.maxX(); x++) { + int column = area.columnIndex(x, z); + applySurfaceColumn(blocks, x, z, originalHeights[column], targetHeights[column], area.minY(), area.maxY(), + rigidBaseSupport[column]); + } + } + } + + private static int resolveVacuumSurfaceHeight(FitBlocks blocks, int x, int z, int nominalY, int worldMinY) { + for (int y = nominalY; y >= worldMinY; y--) { + if (blocks.isTerrain(blocks.get(x, y, z))) { + return y; + } + } + return nominalY; + } + + private static int findVacuumFoundationSupport(FitBlocks blocks, Box area, int x, int startY, int z) { + if (startY < area.minY()) { + return Integer.MIN_VALUE; + } + int maximumY = Math.min(area.maxY(), startY); + for (int y = maximumY; y >= area.minY(); y--) { + BlockState state = blocks.get(x, y, z); + if (blocks.isTerrain(state)) { + return y; + } + if (!blocks.isAir(state) && !blocks.holdsFluid(state)) { + return Integer.MIN_VALUE; + } + } + return Integer.MIN_VALUE; + } + + private static boolean intersectsVacuumOccupancy(Set occupiedCells, int x, int z, int minimumY, int maximumY) { + for (int y = minimumY; y <= maximumY; y++) { + if (occupiedCells.contains(TemplateFootprint.packedPosition(x, y, z))) { + return true; + } + } + return false; + } + + private static SurfaceResolution resolveVacuumSurface(VacuumFootprint footprint, int worldX, int worldZ, int originalY) { + long column = TemplateFootprint.columnKey(worldX, worldZ); + Integer cap = footprint.columnCaps().get(column); + VacuumAnchor local = footprint.anchors().get(column); + if (local != null && local.strength() > 1) { + int localTargetY = cap == null ? local.surfaceY() : Math.min(local.surfaceY(), cap); + if (localTargetY <= originalY) { + return new SurfaceResolution(originalY, false); + } + return new SurfaceResolution(localTargetY, localTargetY == local.surfaceY()); + } + long totalInfluence = 0L; + long weightedSurfaceY = 0L; + long maximumInfluence = 0L; + int radiusSquared = SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; + for (int offsetX = -SURFACE_TERRAIN_RADIUS; offsetX <= SURFACE_TERRAIN_RADIUS; offsetX++) { + for (int offsetZ = -SURFACE_TERRAIN_RADIUS; offsetZ <= SURFACE_TERRAIN_RADIUS; offsetZ++) { + int horizontalDistanceSquared = offsetX * offsetX + offsetZ * offsetZ; + if (horizontalDistanceSquared > radiusSquared) { + continue; + } + VacuumAnchor anchor = footprint.anchors().get( + TemplateFootprint.columnKey(worldX + offsetX, worldZ + offsetZ)); + if (anchor == null || anchor.surfaceY() <= originalY) { + continue; + } + int verticalDistance = Math.abs(anchor.surfaceY() + 1 - originalY); + long distanceSquared = horizontalDistanceSquared + (long) verticalDistance * verticalDistance; + double factor = 0D; + if (distanceSquared <= radiusSquared) { + factor = surfaceFactor(Math.sqrt(distanceSquared)); + } + if (anchor.strength() > 1 && verticalDistance > SURFACE_TERRAIN_RADIUS) { + double rescueProgress = Math.min(1D, + (verticalDistance - SURFACE_TERRAIN_RADIUS) / (double) SURFACE_TERRAIN_RADIUS); + double rescueWeight = rescueProgress * rescueProgress * (3D - 2D * rescueProgress); + factor = Math.max(factor, surfaceFactor(Math.sqrt(horizontalDistanceSquared)) * rescueWeight); + } + long influence = Math.round(factor * SURFACE_TERRAIN_INFLUENCE_SCALE); + if (influence <= 0L) { + continue; + } + long weightedInfluence = influence * Math.max(1, anchor.strength()); + totalInfluence += weightedInfluence; + weightedSurfaceY += weightedInfluence * anchor.surfaceY(); + maximumInfluence = Math.max(maximumInfluence, influence); + } + } + if (totalInfluence == 0L) { + return new SurfaceResolution(originalY, false); + } + double blendedSurfaceY = weightedSurfaceY / (double) totalInfluence; + double factor = maximumInfluence / (double) SURFACE_TERRAIN_INFLUENCE_SCALE; + int targetY = (int) Math.round(originalY + ((blendedSurfaceY - originalY) * factor)); + if (cap != null) { + targetY = Math.min(targetY, cap); + } + return new SurfaceResolution(Math.max(originalY, targetY), false); + } + + private static double surfaceFactor(double distance) { + return Math.pow(1D - distance / SURFACE_TERRAIN_RADIUS, SURFACE_TERRAIN_FALLOFF); + } + + static void applySurfaceColumn(FitBlocks blocks, int x, int z, int originalY, int targetY, int worldMinY, + int worldMaxY, boolean requireRigidBaseSupport) { + if (targetY == originalY) { + if (requireRigidBaseSupport) { + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY); + } + return; + } + SurfaceMaterials materials = resolveSurfaceMaterials(blocks, x, z, originalY, worldMinY); + if (targetY < originalY) { + BlockState clearedState = clearSurfaceDecorationAndResolveFill(blocks, x, z, originalY, worldMaxY); + for (int y = originalY; y > targetY; y--) { + blocks.set(x, y, z, clearedState); + } + blocks.set(x, targetY, z, materials.surface()); + if (requireRigidBaseSupport) { + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials); + } + return; + } + for (int y = originalY + 1; y < targetY; y++) { + if (!blocks.isTree(blocks.get(x, y, z))) { + blocks.set(x, y, z, materials.subsurface()); + } + } + if (!blocks.isTree(blocks.get(x, targetY, z))) { + blocks.set(x, targetY, z, materials.surface()); + } + if (requireRigidBaseSupport) { + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials); + } + } + + private static void ensureRigidBaseTerrain(FitBlocks blocks, int x, int z, int targetY, int worldMinY) { + int supportY = targetY - 1; + boolean targetIsTerrain = blocks.isTerrain(blocks.get(x, targetY, z)); + boolean supportIsTerrain = supportY < worldMinY || blocks.isTerrain(blocks.get(x, supportY, z)); + if (targetIsTerrain && supportIsTerrain) { + return; + } + SurfaceMaterials materials = resolveSurfaceMaterials(blocks, x, z, targetY, worldMinY); + ensureRigidBaseTerrain(blocks, x, z, targetY, worldMinY, materials); + } + + private static void ensureRigidBaseTerrain(FitBlocks blocks, int x, int z, int targetY, int worldMinY, + SurfaceMaterials materials) { + int supportY = targetY - 1; + if (!blocks.isTerrain(blocks.get(x, targetY, z))) { + blocks.set(x, targetY, z, materials.surface()); + } + if (supportY < worldMinY) { + return; + } + if (!blocks.isTerrain(blocks.get(x, supportY, z))) { + blocks.set(x, supportY, z, materials.subsurface()); + } + } + + private static BlockState clearSurfaceDecorationAndResolveFill(FitBlocks blocks, int x, int z, int originalY, + int worldMaxY) { + for (int y = originalY + 1; y <= worldMaxY; y++) { + BlockState state = blocks.get(x, y, z); + if (blocks.isAir(state)) { + return FitBlocks.AIR; + } + if (blocks.holdsFluid(state)) { + BlockState fluid = blocks.fluidOf(state); + if (!state.equals(fluid)) { + blocks.set(x, y, z, fluid); + } + return fluid; + } + if (blocks.isSolid(state) || blocks.isTree(state)) { + return FitBlocks.AIR; + } + blocks.set(x, y, z, FitBlocks.AIR); + } + return FitBlocks.AIR; + } + + private static SurfaceMaterials resolveSurfaceMaterials(FitBlocks blocks, int x, int z, int originalY, int worldMinY) { + BlockState surface = blocks.get(x, originalY, z); + BlockState subsurface = null; + for (int y = originalY - 1; y >= worldMinY; y--) { + BlockState candidate = blocks.get(x, y, z); + if (blocks.isTerrain(candidate)) { + subsurface = candidate; + break; + } + } + if (subsurface == null) { + subsurface = blocks.isTerrain(surface) ? surface : FitBlocks.STONE; + } + if (!blocks.isTerrain(surface)) { + surface = subsurface; + } + return new SurfaceMaterials(surface, subsurface); + } + + record SurfaceAnchor(int minX, int maxX, int minZ, int maxZ, int meetY, int strength) { + } + + private record SurfaceMaterials(BlockState surface, BlockState subsurface) { + } + + private record SurfaceResolution(int targetY, boolean rigidBaseSupport) { + } + + private record VacuumFootprint(Map anchors, Map columnCaps, + Set foundationBases, Set occupiedCells) { + } + + private record VacuumAnchor(int surfaceY, int strength) { + } + + /** The foundation bases VACUUM raised the terrain to, kept until the pieces are placed for the repair. */ + static final class VacuumFoundationPlan { + static final VacuumFoundationPlan EMPTY = new VacuumFoundationPlan(List.of(), Set.of()); + + private final List foundationBases; + private final Set occupiedCells; + + private VacuumFoundationPlan(List foundationBases, Set occupiedCells) { + this.foundationBases = foundationBases; + this.occupiedCells = occupiedCells; + } + + private static VacuumFoundationPlan create(Set packedBases, Set packedOccupancy, Box area) { + if (packedBases.isEmpty()) { + return EMPTY; + } + List bases = new ArrayList<>(packedBases.size()); + Set columns = new HashSet<>(); + for (long packedBase : packedBases) { + int x = TemplateFootprint.packedX(packedBase); + int z = TemplateFootprint.packedZ(packedBase); + if (!area.contains(x, TemplateFootprint.packedY(packedBase), z)) { + continue; + } + bases.add(packedBase); + columns.add(TemplateFootprint.columnKey(x, z)); + } + if (bases.isEmpty()) { + return EMPTY; + } + bases.sort((first, second) -> { + int yOrder = Integer.compare(TemplateFootprint.packedY(first), TemplateFootprint.packedY(second)); + return yOrder == 0 ? Long.compare(first, second) : yOrder; + }); + Set occupancy = new HashSet<>(); + for (long packedCell : packedOccupancy) { + if (columns.contains(TemplateFootprint.columnKey( + TemplateFootprint.packedX(packedCell), TemplateFootprint.packedZ(packedCell)))) { + occupancy.add(packedCell); + } + } + return new VacuumFoundationPlan(List.copyOf(bases), Set.copyOf(occupancy)); + } + } + + /** Bounds the template blocks one start may read for one fitting. */ + static final class TemplateCellBudget { + private final int maximum; + private int consumed; + + TemplateCellBudget(int maximum) { + if (maximum < 0) { + throw new IllegalArgumentException("Native structure surface template budget cannot be negative"); + } + this.maximum = maximum; + } + + void consume(int amount) { + if (amount < 0 || consumed > maximum - amount) { + throw TemplateBudgetExceeded.INSTANCE; + } + consumed += amount; + } + } + + static final class TemplateBudgetExceeded extends RuntimeException { + static final TemplateBudgetExceeded INSTANCE = new TemplateBudgetExceeded(); + + private TemplateBudgetExceeded() { + super(null, null, false, false); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java new file mode 100644 index 000000000..8d6b107e8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/TemplateFootprint.java @@ -0,0 +1,98 @@ +/* + * 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 com.volmit.block.BlockState; +import com.volmit.vanilla.TemplateCells; + +import java.util.HashMap; +import java.util.Map; + +/** The lowest template cell of each column of a piece, the cells a structure stands on. */ +final class TemplateFootprint { + private static final int PACKED_HORIZONTAL_BITS = 26; + private static final int PACKED_VERTICAL_BITS = 12; + private static final long PACKED_HORIZONTAL_MASK = (1L << PACKED_HORIZONTAL_BITS) - 1L; + private static final long PACKED_VERTICAL_MASK = (1L << PACKED_VERTICAL_BITS) - 1L; + private static final int PACKED_X_OFFSET = PACKED_VERTICAL_BITS + PACKED_HORIZONTAL_BITS; + private static final int PACKED_Z_OFFSET = PACKED_VERTICAL_BITS; + + private TemplateFootprint() { + } + + /** The lowest cell of every column, removed blocks included. */ + static Map lowestCells(TemplateCells cells, FitPiece piece) { + Map lowest = new HashMap<>(); + for (int cell = 0; cell < cells.size(); cell++) { + keepLowest(lowest, cells, piece, cell); + } + return lowest; + } + + /** The lowest cell of every column that a structure can stand on. */ + static Map lowestSolidCells(TemplateCells cells, FitPiece piece, FitBlocks blocks) { + Map lowest = new HashMap<>(); + for (int cell = 0; cell < cells.size(); cell++) { + if (cells.removed(cell) || !blocks.isSolidBase(cells.state(cell))) { + continue; + } + keepLowest(lowest, cells, piece, cell); + } + return lowest; + } + + private static void keepLowest(Map lowest, TemplateCells cells, FitPiece piece, int cell) { + int y = piece.cellY(cells, cell); + long column = columnKey(cells.x(cell), cells.z(cell)); + Cell current = lowest.get(column); + if (current == null || y < current.y()) { + lowest.put(column, new Cell(cells.x(cell), y, cells.z(cell), cells.state(cell))); + } + } + + static long columnKey(int x, int z) { + return (long) x << 32 ^ z & 0xffffffffL; + } + + /** A block position packed the way the platform packs positions, so sets of them sort the platform's way. */ + static long packedPosition(int x, int y, int z) { + return ((long) x & PACKED_HORIZONTAL_MASK) << PACKED_X_OFFSET + | ((long) y & PACKED_VERTICAL_MASK) + | ((long) z & PACKED_HORIZONTAL_MASK) << PACKED_Z_OFFSET; + } + + static int packedX(long packed) { + return (int) (packed << (64 - PACKED_X_OFFSET - PACKED_HORIZONTAL_BITS) >> (64 - PACKED_HORIZONTAL_BITS)); + } + + static int packedY(long packed) { + return (int) (packed << (64 - PACKED_VERTICAL_BITS) >> (64 - PACKED_VERTICAL_BITS)); + } + + static int packedZ(long packed) { + return (int) (packed << (64 - PACKED_Z_OFFSET - PACKED_HORIZONTAL_BITS) >> (64 - PACKED_HORIZONTAL_BITS)); + } + + /** A template cell at its world position; no state for a block the processors removed. */ + record Cell(int x, int y, int z, BlockState state) { + boolean blocker() { + return state == null; + } + } +} 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 new file mode 100644 index 000000000..74687fcf6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java @@ -0,0 +1,633 @@ +/* + * 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/mantle/components/StructureCarveEnvelope.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java index e5420b6fa..a33ed27ec 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.util.project.noise.CNG; /** @@ -129,12 +129,12 @@ public final class StructureCarveEnvelope { return 1D - clampedStrength * (1D - clampedNoise); } - public static boolean shouldCarveOverboreCell(IrisStructureCarveShape shape, double distanceSquared, + public static boolean shouldCarveOverboreCell(StructureCarveShape shape, double distanceSquared, double noise, double strength) { if (distanceSquared <= 0.0) { return true; } - IrisStructureCarveShape resolvedShape = shape == null ? IrisStructureCarveShape.ERODED : shape; + StructureCarveShape resolvedShape = shape == null ? StructureCarveShape.ERODED : shape; return switch (resolvedShape) { case BOX -> true; case ROUNDED -> distanceSquared <= 1D; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 54efeb970..5ffbbd75f 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -20,6 +20,8 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.structure.StructureSettings; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.core.modules.IrisPackWorld; @@ -28,15 +30,17 @@ import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.StructureLocating; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.framework.structure.StructureValidator; -import art.arcane.iris.engine.framework.structure.StructureVanillaHook; +import art.arcane.iris.engine.framework.structure.StructureVanillaStructures; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; import com.volmit.config.PackSettings; import com.volmit.service.StructureLocator; +import com.volmit.service.VanillaStructures; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; +import com.volmit.vanilla.JigsawOverrides; import com.volmit.world.PackWorld; /** @@ -50,9 +54,11 @@ import com.volmit.world.PackWorld; * {@link StructureLocating}, and forgets a world's structure index when the world stops, which includes every reload of * the pack's structure files. *

- * It decides over the platform's own structures through its vanilla structure hook ({@link StructureVanillaHook}): the - * dimension's {@code importedStructures} settings disable, adjust and set them up, and the pack's structure placements - * replace them, place them alongside, and start them where their {@code nativeStructures} grids say. + * It decides over the platform's own structures through its {@link VanillaStructures} provider + * ({@link StructureVanillaStructures}): the dimension's {@code importedStructures} settings disable, move, fit and set + * them up, and the pack's structure placements replace them, place them alongside, start them where their + * {@code nativeStructures} grids say and fit them into the terrain. It describes the fit settings Iris's structure + * placements hold. */ public final class StructureModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @@ -75,7 +81,10 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { registry.registerValidator(new StructureValidator()); registry.registerService(StructureLocator.class, new StructureLocating()); registry.registerLifecycle(this); - registry.registerVanillaStructureHook(new StructureVanillaHook()); + registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); + registry.registerHeldType(StructureTerrain.class); + registry.registerHeldType(StructureStilts.class); + registry.registerHeldType(JigsawOverrides.class); } /** The structure index is still kept per engine rather than in the world's state, so a stopping world drops it. */ 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 index fd02c5d15..912253a29 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -22,7 +22,6 @@ 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.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.Cache; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.PlacedStructurePiece; @@ -33,15 +32,16 @@ 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.material.IrisMaterialPalette; 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.engine.object.structure.IrisStructureCarveShape; +import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureTerrainMode; +import art.arcane.iris.builtin.structure.StructureStilts; +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.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; @@ -61,7 +61,6 @@ import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import java.util.HashMap; import java.util.Map; -import java.util.Objects; /** * Places the Iris structures of the dimension, its regions and biomes into the mantle for @@ -119,24 +118,24 @@ public class StructurePlacing { clearIntersectingObjectTrees(writer, resolved); } - IrisStructureTerrain terrain = placement.resolvedTerrain(); - IrisStructureTerrainMode terrainMode = terrain.resolvedMode(); - if (terrainMode == IrisStructureTerrainMode.FORCE_CARVE) { + StructureTerrain terrain = placement.resolvedTerrain(); + StructureTerrainMode terrainMode = terrain.resolvedMode(); + if (terrainMode == StructureTerrainMode.FORCE_CARVE) { forceCarveStructure(writer, pieces, terrain); - } else if (terrainMode == IrisStructureTerrainMode.BORE) { + } else if (terrainMode == StructureTerrainMode.BORE) { boreStructure(writer, pieces, terrain); - } else if (terrainMode != IrisStructureTerrainMode.PRESERVE - && terrainMode != IrisStructureTerrainMode.SOURCE) { + } 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; - IrisStructureStiltSettings stilt = placement.getStilt(); + StructureStilts stilt = placement.getStilt(); Long2IntOpenHashMap foundationColumns = stilt == null ? null : new Long2IntOpenHashMap(); - boolean supportNonOccluding = stilt != null && stilt.isSupportNonOccluding(); + boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding(); if (placement.isAnchoredUnderground()) { ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG) ? mode : ObjectPlaceMode.STRUCTURE_PIECE; @@ -173,12 +172,13 @@ public class StructurePlacing { } private void placeFoundation(MantleWriter writer, Long2IntOpenHashMap columns, - IrisStructureStiltSettings settings, RNG rng, + StructureStilts settings, RNG rng, boolean surfaceStructure) { - IrisMaterialPalette palette = Objects.requireNonNull( - settings.getPalette(), "Structure stilt palette must not be null"); + 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.getMaxDepth()); + 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()); @@ -206,17 +206,16 @@ public class StructurePlacing { continue; } StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> { - writeFoundationSupport( - writer, palette, rng, engine.getData(), worldX, y, worldZ, mantleOffset); + writeFoundationSupport(writer, picker, worldX, y, worldZ, mantleOffset); }); } } - static void writeFoundationSupport(MantleWriter writer, IrisMaterialPalette palette, RNG rng, - IrisData data, int worldX, int mantleY, int worldZ, + /** 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 = palette.get(rng, worldX, worldY, worldZ, data); + 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); @@ -251,17 +250,17 @@ public class StructurePlacing { } private void boreStructure(MantleWriter writer, KList pieces, - IrisStructureTerrain terrain) { + StructureTerrain terrain) { int[] bounds = computePieceBounds(pieces); if (bounds == null) { return; } - int pad = Math.max(0, terrain.getHorizontalPadding()); + int pad = Math.max(0, terrain.horizontalPadding()); int minX = bounds[0] - pad; - int minY = bounds[1] - Math.max(0, terrain.getFloorPadding()); + 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.getCeilingPadding()); + 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; @@ -281,22 +280,22 @@ public class StructurePlacing { } private void forceCarveStructure(MantleWriter writer, KList pieces, - IrisStructureTerrain terrain) { + StructureTerrain terrain) { int[] bounds = computePieceBounds(pieces); if (bounds == null) { return; } - IrisStructureCarveShape shape = terrain.resolvedShape(); - int margin = Math.max(0, terrain.getHorizontalPadding()); - int head = Math.max(0, terrain.getCeilingPadding()); - int floorCut = Math.max(0, terrain.getFloorPadding()); + 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 == IrisStructureCarveShape.BOX) { + if (shape == StructureCarveShape.BOX) { carveOverboreBox(writer, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax); return; } @@ -309,7 +308,7 @@ public class StructurePlacing { } double frequency = terrain.resolvedErosionFrequency(); - boolean eroded = shape == IrisStructureCarveShape.ERODED && strength > 0D; + boolean eroded = shape == StructureCarveShape.ERODED && strength > 0D; CNG blob = null; CNG roll = null; if (eroded) { @@ -604,10 +603,10 @@ public class StructurePlacing { if (!placement.hasIrisStructures()) { continue; } - IrisStructureTerrain terrain = placement.resolvedTerrain(); - int carvePadding = terrain.resolvedMode() == IrisStructureTerrainMode.FORCE_CARVE - || terrain.resolvedMode() == IrisStructureTerrainMode.BORE - ? Math.max(0, terrain.getHorizontalPadding()) : 0; + 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.getStructures()) { IrisStructure structure = StructureResources.structure(engine.getData(), key); if (structure != null) { diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java index 421098ab9..d7d5315c9 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.structure; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -119,16 +121,16 @@ public class IrisStructurePlacement { private int caveMinimumClearance = 3; @Desc("Terrain integration for this placement. The editable structures backend supports SOURCE, PRESERVE, BORE, and FORCE_CARVE. The nativeStructures backend supports every terrain mode.") - private IrisStructureTerrain terrain = new IrisStructureTerrain(); + private StructureTerrain terrain = new StructureTerrain(); @Desc("Optional foundation columns placed beneath the assembled structure's occupied bottom cells. Columns pass through air and fluids until they reach solid ground, up to maxDepth.") - private IrisStructureStiltSettings stilt = null; + private StructureStilts stilt = null; @Desc("If false, the placement is skipped when its selected surface or cave column is submerged.") private boolean underwater = false; - public IrisStructureTerrain resolvedTerrain() { - return terrain == null ? new IrisStructureTerrain() : terrain; + public StructureTerrain resolvedTerrain() { + return terrain == null ? new StructureTerrain() : terrain; } public boolean hasIrisStructures() { diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java deleted file mode 100644 index 7d1e90337..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureStiltSettings.java +++ /dev/null @@ -1,33 +0,0 @@ -package art.arcane.iris.engine.object.structure; - -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -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 -@Desc("Defines foundation columns placed beneath a structure.") -@Data -public class IrisStructureStiltSettings { - @MinNumber(1) - @MaxNumber(4064) - @Desc("Maximum number of blocks each foundation column may descend while searching for solid ground.") - private int maxDepth = 64; - - @Desc("Block palette used for foundation columns.") - private IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:cobblestone"); - - @MinNumber(1) - @MaxNumber(64) - @Desc("Horizontal spacing between support columns. One fills every eligible foundation column; larger values create sparse stilts.") - private int spacing = 1; - - @Desc("For Iris-authored structures, whether solid partial blocks such as slabs, stairs, and walls may seed foundation columns instead of requiring a fully occluding base block.") - private boolean supportNonOccluding = false; -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java deleted file mode 100644 index c6c50e025..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureYBand.java +++ /dev/null @@ -1,34 +0,0 @@ -package art.arcane.iris.engine.object.structure; - -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("An absolute world Y band a native structure is relocated into. Reversed bounds are normalized.") -public class IrisStructureYBand { - @MinNumber(-4064) - @MaxNumber(4064) - @Desc("Lowest absolute world Y of the band.") - private int min = 0; - - @MinNumber(-4064) - @MaxNumber(4064) - @Desc("Highest absolute world Y of the band.") - private int max = 0; - - public int resolvedMin() { - return Math.min(min, max); - } - - public int resolvedMax() { - return Math.max(min, max); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java deleted file mode 100644 index b34a5419f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConfiguration.java +++ /dev/null @@ -1,71 +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 art.arcane.iris.engine.object.annotations.RegistryListNativeJigsawPool; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Data -@Desc("Optional overrides applied to a live vanilla, datapack, or modded jigsaw definition before Minecraft assembles it. Omitted values preserve the registered source definition.") -public class IrisJigsawConfiguration { - @Desc("Optional registered template-pool key used instead of the source jigsaw's start pool. Empty preserves the source pool.") - @RegistryListNativeJigsawPool - private String startPool = ""; - - @Desc("Optional start connector name. Empty preserves the source value; the literal NONE removes the source constraint.") - private String startJigsawName = ""; - - @MinNumber(0) - @MaxNumber(20) - @Desc("Maximum jigsaw recursion depth. Null preserves the source value.") - private Integer maxDepth = null; - - @MinNumber(1) - @MaxNumber(128) - @Desc("Exact horizontal block distance allowed from the start. Null preserves the source value.") - private Integer maxDistanceHorizontal = null; - - @MinNumber(1) - @MaxNumber(4064) - @Desc("Exact vertical block distance allowed from the start. Null preserves the source value.") - private Integer maxDistanceVertical = null; - - @Desc("Expansion-hack override. Null preserves the source value.") - private Boolean useExpansionHack = null; - - @Desc("Heightmap projection override. SOURCE preserves the registered value and NONE removes projection.") - private IrisJigsawHeightmap projectStartToHeightmap = IrisJigsawHeightmap.SOURCE; - - @MinNumber(0) - @MaxNumber(Integer.MAX_VALUE) - @Desc("Minimum distance retained above the dimension floor. Null preserves the source value.") - private Integer dimensionPaddingBottom = null; - - @MinNumber(0) - @MaxNumber(Integer.MAX_VALUE) - @Desc("Minimum distance retained below the dimension ceiling. Null preserves the source value.") - private Integer dimensionPaddingTop = null; - - @Desc("Waterlogging override. SOURCE preserves the registered value.") - private IrisJigsawLiquidSettings liquidSettings = IrisJigsawLiquidSettings.SOURCE; - - public boolean hasOverrides() { - return (startPool != null && !startPool.isBlank()) - || (startJigsawName != null && !startJigsawName.isBlank()) - || maxDepth != null - || maxDistanceHorizontal != null - || maxDistanceVertical != null - || useExpansionHack != null - || (projectStartToHeightmap != null && projectStartToHeightmap != IrisJigsawHeightmap.SOURCE) - || dimensionPaddingBottom != null - || dimensionPaddingTop != null - || (liquidSettings != null && liquidSettings != IrisJigsawLiquidSettings.SOURCE); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java deleted file mode 100644 index 79de9f12b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawHeightmap.java +++ /dev/null @@ -1,30 +0,0 @@ -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Controls whether a configured native jigsaw projects its start onto a Minecraft heightmap.") -public enum IrisJigsawHeightmap { - @Desc("Keeps the registered structure's own heightmap projection exactly as the vanilla, datapack, or mod definition declares it.") - SOURCE, - - @Desc("Removes heightmap projection entirely, so the start piece lands at the structure's literal start height instead of following terrain.") - NONE, - - @Desc("Drops the start piece onto the terrain top counting water as solid, so ocean starts sit on the water surface.") - WORLD_SURFACE_WG, - - @Desc("Identical to WORLD_SURFACE_WG in Iris worlds: the start piece rides the terrain top including water.") - WORLD_SURFACE, - - @Desc("Drops the start piece onto solid terrain, ignoring water, so ocean starts sit on the seabed.") - OCEAN_FLOOR_WG, - - @Desc("Identical to OCEAN_FLOOR_WG in Iris worlds: the start piece sits on solid ground beneath any water.") - OCEAN_FLOOR, - - @Desc("Behaves like WORLD_SURFACE in Iris worlds; the start piece sits on the terrain top including water.") - MOTION_BLOCKING, - - @Desc("Behaves like WORLD_SURFACE in Iris worlds; Iris height queries have no leaf layer to skip.") - MOTION_BLOCKING_NO_LEAVES -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java deleted file mode 100644 index d6004db29..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawLiquidSettings.java +++ /dev/null @@ -1,15 +0,0 @@ -package art.arcane.iris.engine.object.structure.jigsaw; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Controls waterlogging behavior for a configured native jigsaw.") -public enum IrisJigsawLiquidSettings { - @Desc("Keeps the registered structure's own liquid setting; vanilla defaults to applying waterlogging when the definition omits it.") - SOURCE, - - @Desc("Places pieces dry: existing water is displaced and waterloggable blocks stay unwaterlogged, leaving air-filled interiors underwater.") - IGNORE_WATERLOGGING, - - @Desc("Re-applies pre-existing water into placed waterloggable blocks and floods from neighboring sources, so underwater pieces come out waterlogged.") - APPLY_WATERLOGGING -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java index f4f4c8fdb..357b0002d 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java @@ -1,6 +1,5 @@ package art.arcane.iris.engine.object.structure.vanilla; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConfiguration; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MinNumber; import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; @@ -9,6 +8,7 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import com.volmit.vanilla.JigsawOverrides; @Accessors(chain = true) @NoArgsConstructor @@ -26,5 +26,5 @@ public class IrisNativeStructure { private int weight = 1; @Desc("Optional jigsaw-only assembly overrides. Null preserves the complete registered structure definition.") - private IrisJigsawConfiguration jigsaw = null; + private JigsawOverrides jigsaw = null; } diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java deleted file mode 100644 index cadbd1dc7..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructureDecision.java +++ /dev/null @@ -1,40 +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.object.structure.vanilla; - -import art.arcane.iris.engine.object.structure.IrisStructureStiltSettings; -import art.arcane.iris.engine.object.structure.IrisStructureTerrain; -import art.arcane.iris.engine.object.structure.IrisStructureYBand; -public record IrisNativeStructureDecision( - NativeStructureGenerationStatus status, - int yShift, - IrisStructureYBand yBand, - boolean preserveSourceY, - IrisStructureStiltSettings stilt, - IrisStructureTerrain terrain -) { - public boolean generate() { - return status == NativeStructureGenerationStatus.GENERATE_NATIVE; - } - - public IrisNativeStructureDecision withStatus(NativeStructureGenerationStatus replacement) { - return new IrisNativeStructureDecision( - replacement, yShift, yBand, preserveSourceY, stilt, terrain); - } -} From 95817f6d17f3016ba4cbac9e052e221f1569f495 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 03:54:40 +0200 Subject: [PATCH 046/139] Object place modes are data the placement stages ask Each ObjectPlaceMode carries a PlaceMode: its height sampling, its stilt, its VacuumProfile (default radius, column step, edge) and its traits (RAW_STAMP, FREE_HEIGHT, UPSIDE_DOWN, CAVE_ANCHORED). The stages, the structure placer, the locator and the replacement validation ask the data instead of comparing modes; a floating island derives its stilt-free mode from the data. The JSON names are unchanged. Core and the adapters no longer read ObjectPlaceMode: the jigsaw export asks the structure whether it stamps its pieces where assembled, and the structure commands take IrisObjectPlacement.stampingStructurePieces(). --- .../iris/builtin/anchor/ObjectPlaceMode.java | 80 ++++++++++--------- .../arcane/iris/builtin/anchor/PlaceMode.java | 47 +++++++++++ .../iris/builtin/anchor/PlaceTrait.java | 30 +++++++ .../iris/builtin/anchor/VacuumProfile.java | 61 ++++++++++++++ .../framework/IrisStructureLocator.java | 8 +- .../NativeReplacementValidation.java | 7 +- .../components/FloatingObjectPlacing.java | 18 +---- .../mantle/components/ObjectPlacing.java | 13 +-- .../mantle/components/StructurePlacing.java | 7 +- .../engine/object/placement/AnchorModule.java | 4 +- .../engine/object/placement/BlocksModule.java | 4 +- .../object/placement/IrisObjectPlacement.java | 5 ++ .../object/placement/IrisObjectVacuum.java | 18 +---- .../object/placement/PrepareModule.java | 4 +- .../object/placement/PreparedPlacement.java | 9 ++- .../engine/object/placement/VacuumModule.java | 14 ++-- .../object/placement/ValidateModule.java | 13 ++- .../engine/object/placement/WorldVolume.java | 4 +- .../object/structure/IrisStructure.java | 6 ++ 19 files changed, 241 insertions(+), 111 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java create mode 100644 src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java create mode 100644 src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java diff --git a/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java b/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java index b57e3d7c1..116120b50 100644 --- a/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java +++ b/src/main/java/art/arcane/iris/builtin/anchor/ObjectPlaceMode.java @@ -25,106 +25,114 @@ import com.volmit.config.Desc; public enum ObjectPlaceMode { @Desc("The default place mode. This mode picks a center point (where the center of the object will be) and takes the height. That height is used for the whole object.") - CENTER_HEIGHT(AnchorSampling.CENTER, StiltShape.NONE), + CENTER_HEIGHT(PlaceMode.of(AnchorSampling.CENTER, StiltShape.NONE)), @Desc("Samples a lot of points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.") - MAX_HEIGHT(AnchorSampling.HIGHEST, StiltShape.NONE), + MAX_HEIGHT(PlaceMode.of(AnchorSampling.HIGHEST, StiltShape.NONE)), @Desc("Samples only 4 points where the object will cover (horizontally) and picks the highest height, that height is then used to place the object. This mode is useful for preventing any part of your object from being buried though it will float off of cliffs.\"") - FAST_MAX_HEIGHT(AnchorSampling.HIGHEST_CORNER, StiltShape.NONE), + FAST_MAX_HEIGHT(PlaceMode.of(AnchorSampling.HIGHEST_CORNER, StiltShape.NONE)), @Desc("Samples a lot of points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") - MIN_HEIGHT(AnchorSampling.LOWEST, StiltShape.NONE), + MIN_HEIGHT(PlaceMode.of(AnchorSampling.LOWEST, StiltShape.NONE)), @Desc("Samples only 4 points where the object will cover (horizontally) and picks the lowest height, that height is then used to place the object. This mode is useful for preventing any part of your object from overhanging a cliff though it gets buried a lot") - FAST_MIN_HEIGHT(AnchorSampling.LOWEST_CORNER, StiltShape.NONE), + FAST_MIN_HEIGHT(PlaceMode.of(AnchorSampling.LOWEST_CORNER, StiltShape.NONE)), @Desc("Stilting is MAX_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - STILT(AnchorSampling.HIGHEST, StiltShape.STRAIGHT), + STILT(PlaceMode.of(AnchorSampling.HIGHEST, StiltShape.STRAIGHT)), @Desc("Just like stilting but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") - FAST_STILT(AnchorSampling.HIGHEST_CORNER, StiltShape.STRAIGHT), + FAST_STILT(PlaceMode.of(AnchorSampling.HIGHEST_CORNER, StiltShape.STRAIGHT)), @Desc("Stilting is MIN_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - MIN_STILT(AnchorSampling.LOWEST, StiltShape.STRAIGHT), + MIN_STILT(PlaceMode.of(AnchorSampling.LOWEST, StiltShape.STRAIGHT)), @Desc("Just like MIN_STILT but very inaccurate. Useful for stilting a lot of objects without too much care on accuracy (you can use the over-stilt value to force stilts under ground further)") - FAST_MIN_STILT(AnchorSampling.LOWEST_CORNER, StiltShape.STRAIGHT), + FAST_MIN_STILT(PlaceMode.of(AnchorSampling.LOWEST_CORNER, StiltShape.STRAIGHT)), @Desc("Stilting is CENTER_HEIGHT but it repeats the bottom most block of your object until it hits the surface. This is expensive because it has to first sample every height value for each x,z position of your object. Avoid using this unless its structures for performance reasons.") - CENTER_STILT(AnchorSampling.CENTER, StiltShape.STRAIGHT), + CENTER_STILT(PlaceMode.of(AnchorSampling.CENTER, StiltShape.STRAIGHT)), @Desc("Erode stilting tapers columns downward like an ice cream cone. Blocks near the center extend deepest while edge blocks drop off first. Blocks are randomly skipped in the lower portion for a rough organic eroded texture.") - ERODE_STILT(AnchorSampling.HIGHEST, StiltShape.ERODE), + ERODE_STILT(PlaceMode.of(AnchorSampling.HIGHEST, StiltShape.ERODE)), @Desc("Organic stilting scans straight down from the bottom of the object to the first solid block (the cave floor, or terrain) and fills the gap with the object's own bottom block. Each column stops at a slightly different, noise-varied depth and the lower portion is randomly broken up, so the underside reads as rough organic roots rather than a flat disc. Designed for objects placed inside caves so they connect to the floor instead of floating. Tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") - ORGANIC_STILT(AnchorSampling.CENTER, StiltShape.ORGANIC), + ORGANIC_STILT(PlaceMode.of(AnchorSampling.CENTER, StiltShape.ORGANIC, PlaceTrait.CAVE_ANCHORED)), @Desc("Hangs the object upside-down from a cave ceiling. The object is flipped vertically (its tip points down like a stalactite) and its top is anchored to the ceiling, while an organic, noise-varied stilt grows up into the ceiling so it never floats below the roof. Use inside caves; tune with stilt-settings (organicMaxScan, organicJitter, organicScratch).") - CEILING_HANG(AnchorSampling.CENTER, StiltShape.CEILING), + CEILING_HANG(PlaceMode.of(AnchorSampling.CENTER, StiltShape.CEILING, PlaceTrait.UPSIDE_DOWN, PlaceTrait.CAVE_ANCHORED)), @Desc("Anchors the object at the terrain surface (plus translate.y) like CENTER_HEIGHT, then bends the surrounding terrain to be flush with the object's base. Columns inside the object footprint are raised (or lowered) to meet the base, and the deformation falls off parabolically out to a radius so the terrain smoothly blends back to its natural height. Use this to seat a floating/translated object on the ground without a flat stilt disc, e.g. a cube translated up 10 on a mountain pulls the terrain up to meet it. Tune with vacuum-settings (radius, falloff).") - VACUUM(AnchorSampling.CENTER, StiltShape.NONE), + VACUUM(PlaceMode.vacuum(VacuumProfile.STANDARD)), @Desc("VACUUM with a larger radius and finer per-column sampling for the smoothest terrain blend. More expensive.") - VACUUM_HIGH(AnchorSampling.CENTER, StiltShape.NONE), + VACUUM_HIGH(PlaceMode.vacuum(VacuumProfile.HIGH)), @Desc("VACUUM with a smaller radius and coarser sampling for performance. Use when seating many objects.") - VACUUM_FAST(AnchorSampling.CENTER, StiltShape.NONE), + VACUUM_FAST(PlaceMode.vacuum(VacuumProfile.FAST)), @Desc("VACUUM whose falloff radius is perturbed by noise per column, so the terrain meets the object with an irregular organic edge rather than a clean parabolic bowl.") - VACUUM_ORGANIC(AnchorSampling.CENTER, StiltShape.NONE), + VACUUM_ORGANIC(PlaceMode.vacuum(VacuumProfile.ORGANIC)), @Desc("VACUUM whose terrain bend is bent by smooth coherent simplex noise so the surface meets the object with a gently rolling, wavy slope instead of the ragged white-noise edge of VACUUM_ORGANIC or a clean parabolic bowl. The object itself still seats flush; the waves fade to zero under the object and at the outer rim, peaking across the mid-slope. Tune with vacuum-settings (waveAmplitude, waveScale).") - VACUUM_WAVY(AnchorSampling.CENTER, StiltShape.NONE), + VACUUM_WAVY(PlaceMode.vacuum(VacuumProfile.WAVY)), @Desc("Samples the height of the terrain at every x,z position of your object and pushes it down to the surface. It's pretty much like a melt function over the terrain.") - PAINT(AnchorSampling.SURFACE, StiltShape.NONE), + PAINT(PlaceMode.of(AnchorSampling.SURFACE, StiltShape.NONE)), @Desc("Places the object in pure air at an absolute Y driven entirely by translate.y (plus optional translate.yRandom). Terrain height, underwater, and carving anchor checks are skipped. Use this for floating islands, sky structures, clouds, or blimps where the object must not be translated to the ground.") - FLOATING(AnchorSampling.TRANSLATION, StiltShape.NONE), + FLOATING(PlaceMode.of(AnchorSampling.TRANSLATION, StiltShape.NONE, PlaceTrait.FREE_HEIGHT)), @Desc("Raw stamp at the caller-supplied (x, y, z). No terrain sampling, no stilting, no Y recomputation, no underwater or carving anchor guards. Used internally to route native Minecraft structure pieces (villages etc.) through the Iris object placer.") - STRUCTURE_PIECE(AnchorSampling.REQUESTED, StiltShape.NONE); + STRUCTURE_PIECE(PlaceMode.of(AnchorSampling.REQUESTED, StiltShape.NONE, PlaceTrait.RAW_STAMP, PlaceTrait.FREE_HEIGHT)); - private final AnchorSampling anchor; - private final StiltShape stilt; + private final PlaceMode placeMode; - ObjectPlaceMode(AnchorSampling anchor, StiltShape stilt) { - this.anchor = anchor; - this.stilt = stilt; + ObjectPlaceMode(PlaceMode placeMode) { + this.placeMode = placeMode; } - /** How a placement without a requested height finds one. */ - public AnchorSampling anchor() { - return anchor; + /** What the mode does, for the placement stages to ask. */ + public PlaceMode placeMode() { + return placeMode; } - /** The stilt this mode grows under or above the object. */ - public StiltShape stilt() { - return stilt; - } - - public boolean isVacuum() { - return this == VACUUM || this == VACUUM_HIGH || this == VACUUM_FAST || this == VACUUM_ORGANIC || this == VACUUM_WAVY; + /** + * The mode an object takes on a floating island, which has no ground below to grow stilts to or to stamp into: a + * stilt down to the ground becomes the same height sampling without the stilt, a raw stamp the default mode. + */ + public ObjectPlaceMode onFloatingIsland() { + if (placeMode.has(PlaceTrait.RAW_STAMP)) { + return CENTER_HEIGHT; + } + if (placeMode.stilt() != StiltShape.STRAIGHT && placeMode.stilt() != StiltShape.ERODE) { + return this; + } + for (ObjectPlaceMode mode : values()) { + if (mode.placeMode.equals(PlaceMode.of(placeMode.anchor(), StiltShape.NONE))) { + return mode; + } + } + throw new IllegalStateException("No place mode samples " + placeMode.anchor() + " without a stilt"); } } diff --git a/src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java b/src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java new file mode 100644 index 000000000..ca9905946 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/anchor/PlaceMode.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.anchor; + +import java.util.Set; + +/** + * What an object place mode does, as data the placement stages ask instead of comparing modes: how it finds its + * height, the stilt it grows, how it bends the terrain around the object, and its traits. + */ +public record PlaceMode(AnchorSampling anchor, StiltShape stilt, VacuumProfile vacuum, Set traits) { + public PlaceMode { + traits = Set.copyOf(traits); + } + + public static PlaceMode of(AnchorSampling anchor, StiltShape stilt, PlaceTrait... traits) { + return new PlaceMode(anchor, stilt, VacuumProfile.NONE, Set.of(traits)); + } + + public static PlaceMode vacuum(VacuumProfile vacuum) { + return new PlaceMode(AnchorSampling.CENTER, StiltShape.NONE, vacuum, Set.of()); + } + + public boolean has(PlaceTrait trait) { + return traits.contains(trait); + } + + /** Whether the mode bends the terrain to meet the object's base. */ + public boolean bendsTerrain() { + return vacuum != VacuumProfile.NONE; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java b/src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java new file mode 100644 index 000000000..19a6bde7b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/anchor/PlaceTrait.java @@ -0,0 +1,30 @@ +/* + * 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.builtin.anchor; + +/** A trait of an object place mode that changes what the placement stages do. */ +public enum PlaceTrait { + /** Stamps the object at the requested position as it is: no terrain sampling, no height recomputation. */ + RAW_STAMP, + /** Takes its height from the placement alone, so the terrain, water and carving guards do not apply. */ + FREE_HEIGHT, + /** Flips the object upside down and anchors its top. */ + UPSIDE_DOWN, + /** Anchors to a cave's floor or ceiling, so it keeps its own mode underground. */ + CAVE_ANCHORED +} diff --git a/src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java b/src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java new file mode 100644 index 000000000..2267d1a15 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/anchor/VacuumProfile.java @@ -0,0 +1,61 @@ +/* + * 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.builtin.anchor; + +/** How a place mode bends the terrain around the object to meet its base; NONE leaves the terrain alone. */ +public enum VacuumProfile { + NONE(0, 1, Edge.PARABOLIC), + STANDARD(12, 1, Edge.PARABOLIC), + HIGH(20, 1, Edge.PARABOLIC), + FAST(8, 2, Edge.PARABOLIC), + ORGANIC(12, 1, Edge.JITTERED), + WAVY(12, 1, Edge.WAVY); + + /** The shape of the bend's outer edge. */ + public enum Edge { + PARABOLIC, + /** The radius perturbed per column. */ + JITTERED, + /** The bend rolled by smooth noise. */ + WAVY + } + + private final int defaultRadiusBlocks; + private final int columnStepBlocks; + private final Edge edge; + + VacuumProfile(int defaultRadiusBlocks, int columnStepBlocks, Edge edge) { + this.defaultRadiusBlocks = defaultRadiusBlocks; + this.columnStepBlocks = columnStepBlocks; + this.edge = edge; + } + + /** How far the bend reaches when the vacuum settings leave the radius open. */ + public int defaultRadiusBlocks() { + return defaultRadiusBlocks; + } + + /** Every how many columns the bend samples the terrain. */ + public int columnStepBlocks() { + return columnStepBlocks; + } + + public Edge edge() { + return edge; + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index 995094da1..b2c446447 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -18,8 +18,8 @@ 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.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; @@ -807,8 +807,7 @@ public final class IrisStructureLocator { IrisStructurePlacement placement, IrisStructure structure, int baseY) { if (placement.isAnchoredUnderground() || pieces.size() <= 1 - || structure.getPlaceMode() == ObjectPlaceMode.STRUCTURE_PIECE - || structure.getPlaceMode() == ObjectPlaceMode.FLOATING) { + || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) { return pieces; } int[] bounds = computeBounds(pieces); @@ -818,8 +817,7 @@ public final class IrisStructureLocator { static boolean hasExactY(IrisStructurePlacement placement, IrisStructure structure, KList pieces) { return placement.isAnchoredUnderground() || pieces.size() > 1 - || structure.getPlaceMode() == ObjectPlaceMode.STRUCTURE_PIECE - || structure.getPlaceMode() == ObjectPlaceMode.FLOATING; + || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT); } private static boolean fitsVerticalBounds(KList pieces, int worldMin, int worldMax) { 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 index 21c83a39b..befa246d1 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java @@ -18,6 +18,7 @@ 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; @@ -234,8 +235,7 @@ public final class NativeReplacementValidation { for (StructureGraphValidation.SampledVerticalEnvelope sampled : sampledVerticalEnvelopes) { boolean exactY = placementBounds.underground() || sampled.pieceCount() > 1 - || placeMode == ObjectPlaceMode.STRUCTURE_PIECE - || placeMode == ObjectPlaceMode.FLOATING; + || placeMode.placeMode().has(PlaceTrait.FREE_HEIGHT); if (!exactY) { continue; } @@ -244,8 +244,7 @@ public final class NativeReplacementValidation { long maximumYOffset = sampled.maximumYOffset(); boolean surfaceAligned = !placementBounds.underground() && sampled.pieceCount() > 1 - && placeMode != ObjectPlaceMode.STRUCTURE_PIECE - && placeMode != ObjectPlaceMode.FLOATING; + && !placeMode.placeMode().has(PlaceTrait.FREE_HEIGHT); if (surfaceAligned) { maximumYOffset -= minimumYOffset; minimumYOffset = 0L; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 2f9e6c9d2..2a74bfb86 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; @@ -272,7 +271,7 @@ public class FloatingObjectPlacing { int wz = minZ + pickedZf - fp.getTallestKz(); IrisObjectPlacement anchored = placement.toPlacement(obj.getLoadKey()); - anchored.setMode(translateStiltModeForFloating(anchored.getMode())); + anchored.setMode(anchored.getMode().onFloatingIsland()); anchored.setTranslate(new IrisObjectTranslate()); anchored.setRotation(ROTATION_NONE); anchored.setForcePlace(true); @@ -374,7 +373,7 @@ public class FloatingObjectPlacing { int wz = invertedBaseZ(minZ, pickedZf, fp, invertedRotation); IrisObjectPlacement inverted = placement.toPlacement(obj.getLoadKey()); - inverted.setMode(translateStiltModeForFloating(inverted.getMode())); + inverted.setMode(inverted.getMode().onFloatingIsland()); inverted.setTranslate(new IrisObjectTranslate()); inverted.setRotation(invertedRotation); inverted.setForcePlace(true); @@ -536,19 +535,6 @@ public class FloatingObjectPlacing { return key + "@" + id; } - private static ObjectPlaceMode translateStiltModeForFloating(ObjectPlaceMode m) { - return switch (m) { - case STILT -> ObjectPlaceMode.MAX_HEIGHT; - case FAST_STILT -> ObjectPlaceMode.FAST_MAX_HEIGHT; - case MIN_STILT -> ObjectPlaceMode.MIN_HEIGHT; - case FAST_MIN_STILT -> ObjectPlaceMode.FAST_MIN_HEIGHT; - case CENTER_STILT -> ObjectPlaceMode.CENTER_HEIGHT; - case ERODE_STILT -> ObjectPlaceMode.MAX_HEIGHT; - case STRUCTURE_PIECE -> ObjectPlaceMode.CENTER_HEIGHT; - default -> m; - }; - } - /** How far, in blocks along X and Z, placements may write beyond their chunk. */ public int reach() { int maxObjectExtent = 16; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index f169a87eb..88d18f4b8 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.builtin.carve.CaveProfile; @@ -428,7 +429,7 @@ public class ObjectPlacing { IrisObjectPlacement placement = p.asPlacement(); boolean carving = placement.getCarvingSupport() == CarvingMode.CARVING_ONLY; CaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); - if (placement.getMode() == ObjectPlaceMode.CEILING_HANG) { + if (placement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { anchorMode = CaveAnchorMode.CEILING; } int anchorScanStep = resolveAnchorScanStep(caveProfile); @@ -618,7 +619,7 @@ public class ObjectPlacing { ) { CaveObjectPlacementTransaction transaction = new CaveObjectPlacementTransaction(placer, anchorY, minDepthBelowSurface); int placeY = anchorY; - if (placement.getMode() == ObjectPlaceMode.CEILING_HANG) { + if (placement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { placeY = Math.max(1, transaction.getCaveCeiling(x, z) - 1 - Math.floorDiv(object.getH(), 2)); } String marker = placementMarker(object, id, markerContext); @@ -792,7 +793,7 @@ public class ObjectPlacing { int minZ = chunkZ << 4; int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); CaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); - if (objectPlacement.getMode() == ObjectPlaceMode.CEILING_HANG) { + if (objectPlacement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { anchorMode = CaveAnchorMode.CEILING; } int anchorScanStep = resolveAnchorScanStep(caveProfile); @@ -1195,7 +1196,7 @@ public class ObjectPlacing { } ObjectPlaceMode mode = objectPlacement.getMode(); - if (mode == ObjectPlaceMode.FLOATING || mode == ObjectPlaceMode.STRUCTURE_PIECE) { + if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { return objectPlacement; } boolean needsModeChange = mode != ObjectPlaceMode.FAST_MIN_STILT; @@ -1549,8 +1550,8 @@ public class ObjectPlacing { int warp = placement.getWarp() != null && !placement.getWarp().isFlat() ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) : 0; - int vacuum = IrisObjectVacuum.isVacuumMode(placement.getMode()) - ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode(), placement.getVacuumSettings()) + int vacuum = placement.getMode().placeMode().bendsTerrain() + ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode().placeMode().vacuum(), placement.getVacuumSettings()) : 0; long reach = (long) footprint + translation + warp + vacuum; return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; 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 index 912253a29..82fb45784 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -18,6 +18,7 @@ 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; @@ -137,7 +138,7 @@ public class StructurePlacing { ? null : new Long2IntOpenHashMap(); boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding(); if (placement.isAnchoredUnderground()) { - ObjectPlaceMode undergroundMode = (mode == ObjectPlaceMode.ORGANIC_STILT || mode == ObjectPlaceMode.CEILING_HANG) + 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, @@ -145,7 +146,7 @@ public class StructurePlacing { failedPieces++; } } - } else if (mode == ObjectPlaceMode.STRUCTURE_PIECE || mode == ObjectPlaceMode.FLOATING) { + } 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) { @@ -543,7 +544,7 @@ public class StructurePlacing { if (!structure.getEdit().isEmpty()) { config.setEdit(structure.getEdit()); } - if (mode != ObjectPlaceMode.STRUCTURE_PIECE && mode != ObjectPlaceMode.FLOATING) { + if (!mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { config.setForcePlace(true); } int placeY = (y == -1) ? -1 : y - engine.getMinHeight(); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index acbf04d8d..e85c47696 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.AnchorHeight; import art.arcane.iris.core.modules.IrisPlacement; @@ -57,7 +57,7 @@ public final class AnchorModule implements IrisModule { IrisPlacement placement = IrisPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); - boolean structurePiece = prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE; + boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); if (!config.isFromBottom() && placement.requestedY() < 0) { return new AnchorHeight(sampled(context, placement, prepared)); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 160ad94d4..169edfde5 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.blocks.ObjectReplace; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; @@ -116,7 +116,7 @@ public final class BlocksModule implements IrisModule { y = offset.y() + Math.floorDiv(placement.object().h, 2) + prepared.terrain().getHighest(x, z, placement.object().getLoader(), config.isUnderwater()); } - boolean structurePiece = prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE; + boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); if (config.isMeld() && !structurePiece && !world.isSolid(x, y, z)) { return; } 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 index 2eb137730..ee0075335 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -208,6 +208,11 @@ public class IrisObjectPlacement { /** 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)); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java index 101f9215d..e0337d45a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectVacuum.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.VacuumProfile; import art.arcane.iris.builtin.vacuum.VacuumSettings; public final class IrisObjectVacuum { @@ -30,26 +30,14 @@ public final class IrisObjectVacuum { private IrisObjectVacuum() { } - public static boolean isVacuumMode(ObjectPlaceMode mode) { - return mode != null && mode.isVacuum(); - } - - public static int resolveRadius(ObjectPlaceMode mode, VacuumSettings settings) { - int radius = switch (mode) { - case VACUUM_HIGH -> 20; - case VACUUM_FAST -> 8; - default -> 12; - }; + public static int resolveRadius(VacuumProfile vacuum, VacuumSettings settings) { + int radius = vacuum.defaultRadiusBlocks(); if (settings != null && settings.radius() > 0) { radius = settings.radius(); } return Math.max(0, Math.min(MAX_RADIUS_BLOCKS, radius)); } - public static int resolveStep(ObjectPlaceMode mode) { - return mode == ObjectPlaceMode.VACUUM_FAST ? 2 : 1; - } - public static double resolveFalloff(VacuumSettings settings) { return settings != null ? Math.max(0.25, settings.falloff()) : 2.0; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 00b911609..1ed36114b 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.prepare.SlopeClip; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.prepare.AxisRotationClamp; @@ -135,7 +135,7 @@ public final class PrepareModule implements IrisModule { : null; int randomY = randomHeightOffset(translate.getYRandom(), rng); int warpMargin = config.getWarp().isFlat() ? 0 : (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D); - TransformedBounds bounds = transformedBounds(object, spin, translation, config.getMode() == ObjectPlaceMode.CEILING_HANG, warpMargin); + TransformedBounds bounds = transformedBounds(object, spin, translation, config.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN), warpMargin); CNG surfaceWarp = config.getWarp().isFlat() ? null : config.getSurfaceWarp(rng, object.getLoader()); return new PreparedPlacement(config, terrain, spin, spinX, spinY, spinZ, translation, rotatedCenterY, translatedCenterY, randomY, warpMargin, bounds, surfaceWarp); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java index b8179078a..5ca9cb784 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java @@ -18,7 +18,8 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.PlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.math.IrisBlockVector; import art.arcane.iris.util.project.noise.CNG; @@ -73,8 +74,8 @@ public final class PreparedPlacement { return terrain; } - ObjectPlaceMode mode() { - return config.getMode(); + PlaceMode mode() { + return config.getMode().placeMode(); } int spinX() { @@ -131,7 +132,7 @@ public final class PreparedPlacement { BlockPosition transform(BlockPosition local) { IrisBlockVector offset = new IrisBlockVector(local.x(), local.y(), local.z()); spin.rotate(offset); - if (mode() == ObjectPlaceMode.CEILING_HANG) { + if (mode().has(PlaceTrait.UPSIDE_DOWN)) { offset.setY(-offset.getBlockY()); } if (translation != null) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index b876b78ea..e3c199da8 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.VacuumProfile; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.IrisStages; @@ -69,7 +69,7 @@ public final class VacuumModule implements IrisModule { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); Engine engine = prepared.terrain().getEngine(); - if (!prepared.mode().isVacuum() || written.isEmpty() || engine == null) { + if (!prepared.mode().bendsTerrain() || written.isEmpty() || engine == null) { return; } int baseY = written.blocks().stream().mapToInt(block -> block.position().y()).min().orElseThrow(); @@ -94,19 +94,19 @@ public final class VacuumModule implements IrisModule { private final int highestY; private Bend(PlacementStageContext context, PreparedPlacement prepared, Engine engine) { - ObjectPlaceMode mode = prepared.mode(); + VacuumProfile vacuum = prepared.mode().vacuum(); this.placement = IrisPlacement.current(); this.prepared = prepared; this.world = new PlacementWorld(context.access(), placement.states()); this.complex = engine.getComplex(); VacuumSettings settings = prepared.config().getVacuumSettings(); - this.radius = IrisObjectVacuum.resolveRadius(mode, settings); - this.step = IrisObjectVacuum.resolveStep(mode); + this.radius = IrisObjectVacuum.resolveRadius(vacuum, settings); + this.step = vacuum.columnStepBlocks(); this.falloff = IrisObjectVacuum.resolveFalloff(settings); this.jitter = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); - this.waves = mode == ObjectPlaceMode.VACUUM_WAVY && waveAmplitude > 0 ? new SimplexNoise(WAVE_SEED) : null; + this.waves = vacuum.edge() == VacuumProfile.Edge.WAVY && waveAmplitude > 0 ? new SimplexNoise(WAVE_SEED) : null; this.lowestY = IrisObjectVacuum.LOWEST_TARGET_Y; this.highestY = engine.getHeight() - 1; } @@ -142,7 +142,7 @@ public final class VacuumModule implements IrisModule { /** The radius, perturbed per column for the organic mode. */ private double effectiveRadius(int x, int z) { - if (prepared.mode() != ObjectPlaceMode.VACUUM_ORGANIC || jitter <= 0) { + if (prepared.mode().vacuum().edge() != VacuumProfile.Edge.JITTERED || jitter <= 0) { return radius; } long hash = ((long) x * HASH_X) ^ ((long) z * HASH_Z); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 1987e39c2..a2d0db2dc 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.validate.ObjectLimit; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; @@ -81,8 +81,7 @@ public final class ValidateModule implements IrisModule { IrisPlacement placement = IrisPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); - if (config.isForcePlace() || config.isFromBottom() || prepared.mode() == ObjectPlaceMode.FLOATING - || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { + if (config.isForcePlace() || config.isFromBottom() || prepared.mode().has(PlaceTrait.FREE_HEIGHT)) { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y(); @@ -117,13 +116,13 @@ public final class ValidateModule implements IrisModule { IrisPlacement placement = IrisPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); - if (config.isForcePlace() || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { + if (config.isForcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP)) { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y(); int rotated = prepared.rotatedCenterY(); int translated = prepared.translatedCenterY(); - if (placement.requestedY() < 0 && prepared.mode() != ObjectPlaceMode.FLOATING && !config.isUnderwater() + if (placement.requestedY() < 0 && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !config.isUnderwater() && !config.isOnwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) { context.reject("underwater-anchor"); } else if (placement.cave() != null @@ -138,7 +137,7 @@ public final class ValidateModule implements IrisModule { private static void checkNativeStructures(PlacementStageContext context) { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - if (prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE) { + if (prepared.mode().has(PlaceTrait.RAW_STAMP)) { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY(); @@ -208,7 +207,7 @@ public final class ValidateModule implements IrisModule { IrisPlacement placement = IrisPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); IrisObjectPlacement config = prepared.config(); - if (config.isForcePlace() || prepared.mode() == ObjectPlaceMode.STRUCTURE_PIECE + if (config.isForcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP) || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { return; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java index 918216a59..d23d77bbb 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.AnchorSampling; import art.arcane.iris.core.modules.IrisPlacement; /** @@ -51,6 +51,6 @@ record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { /** Whether each block of the placement follows the surface of its own column. */ static boolean isPainted(IrisPlacement placement, PreparedPlacement prepared) { - return placement.requestedY() < 0 && prepared.mode() == ObjectPlaceMode.PAINT; + return placement.requestedY() < 0 && prepared.mode().anchor() == AnchorSampling.SURFACE; } } 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 index 609939ce1..5e7d3de5f 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -18,6 +18,7 @@ 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.engine.object.loot.IrisLootTable; @@ -109,6 +110,11 @@ public class IrisStructure extends IrisRegistrant { @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; } From 7a0d269780554484b03eb7ece117648688a16dd5 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 03:56:04 +0200 Subject: [PATCH 047/139] README: iris:structure provides VanillaStructures and owns the structure fit; place modes are data --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index e7dd7aae7..4bf62dc47 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,13 @@ provides `ObjectsAt` (the objects a chunk would get, for the object search and s provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a world places, and their nearest start for the find commands). `iris:structure` also has a lifecycle hook that drops a world's structure index when the world stops, which includes every reload of the pack's structure files. +`iris:structure` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: +which ones its placements replace or the dimension's `importedStructures` disables, the starts its `nativeStructures` +placements make, the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, +PRESERVE, VACUUM, ENCASE, BORE, FORCE_CARVE, stilts) in `engine/framework/structure/fit`, written against IrisApi's +`StructureFit` and `BlockAccess` only. A start carries its fit as a memo (its terrain and stilts JSON), so every +chunk it reaches and every restart fits it the same way. Object place modes are data (`PlaceMode`: height sampling, +stilt, `VacuumProfile`, `PlaceTrait`s) that the placement stages ask; the pack JSON keeps the mode names. `iris:objects` also provides `SaplingGrowth` (`TreeGrowing`: the tree a sapling grows into, as placed blocks, and which objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). `iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to From dcf5cc045afa88bc46b15783eacac512a971ad5a Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:05:00 +0200 Subject: [PATCH 048/139] Delete RegistryListNativeJigsawPool: the jigsaw start pool completes through Reference.TEMPLATE_POOL --- .../annotations/RegistryListNativeJigsawPool.java | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java deleted file mode 100644 index 8fcf6d18d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListNativeJigsawPool.java +++ /dev/null @@ -1,14 +0,0 @@ -package art.arcane.iris.engine.object.annotations; - -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 RegistryListNativeJigsawPool { -} From 6617cc3957b9f591b710d2d7ba443ab6e926392f Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:27:45 +0200 Subject: [PATCH 049/139] Ores, hideOresForHiddenOre, deposit variants and the ore deposit multipliers are settings of iris:terrain and iris:deposit OreSettings (ores), HideOresSettings (hideOresForHiddenOre), DepositVariantSettings (depositVariants), OreFrequencySettings and OreSizeSettings are IrisApi-typed features under the keys packs always wrote. ResolvedOre/ResolvedOres/TerrainOres keep the resolved blocks and the chance noise per world, warmed in the same order and with the same seeds as before; ResolvedDepositVariant resolves the remaps. IrisBiome, IrisRegion and IrisDimension lose the fields and their caches; IrisOreGenerator, IrisBiomeOres, IrisOreGeneratorBounds and IrisDepositVariant are deleted. Inferred biome variants keep the module settings of the biome they are copied from. --- .../iris/builtin/deposit/DepositVariant.java | 67 +++++++++ .../deposit/DepositVariantSettings.java | 52 +++++++ .../builtin/deposit/OreFrequencySettings.java | 49 +++++++ .../iris/builtin/deposit/OreSizeSettings.java | 49 +++++++ .../builtin/terrain/HideOresSettings.java | 46 +++++++ .../iris/builtin/terrain/OreGenerator.java | 80 +++++++++++ .../iris/builtin/terrain/OreSettings.java | 52 +++++++ .../iris/engine/actuator/HiddenOres.java | 32 +++++ .../iris/engine/actuator/OreWarmUp.java | 29 ++-- .../iris/engine/actuator/ResolvedOre.java | 125 +++++++++++++++++ .../iris/engine/actuator/ResolvedOres.java | 119 ++++++++++++++++ .../iris/engine/actuator/TerrainModule.java | 83 +++++------ .../iris/engine/actuator/TerrainOres.java | 53 +++++++ .../iris/engine/modifier/DepositModule.java | 11 ++ .../iris/engine/modifier/DepositPlacer.java | 44 ++++-- .../engine/modifier/PerfectionModule.java | 3 +- .../modifier/ResolvedDepositVariant.java | 66 +++++++++ .../object/terrain/deposit/IrisBiomeOres.java | 130 ------------------ .../terrain/deposit/IrisDepositVariant.java | 87 ------------ .../terrain/deposit/IrisOreGenerator.java | 81 ----------- .../deposit/IrisOreGeneratorBounds.java | 44 ------ .../engine/object/world/biome/IrisBiome.java | 73 +--------- .../object/world/dimension/IrisDimension.java | 101 -------------- .../object/world/region/IrisRegion.java | 99 ------------- 24 files changed, 884 insertions(+), 691 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java create mode 100644 src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java new file mode 100644 index 000000000..582301354 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java @@ -0,0 +1,67 @@ +/* + * 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.builtin.deposit; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.Map; + +/** + * One deposit ore remap rule, an entry of {@code depositVariants}: within a vertical band, ore blocks are rewritten to + * alternate blocks. A value of IrisApi types only; {@code ResolvedDepositVariant} resolves the blocks. + */ +@Snippet("deposit-variant") +@Desc("Remaps ore block ids to alternate block ids within a vertical band. Ores declared at dimension, region, and biome scope can be rewritten at placement time (for example, iron_ore -> deepslate_iron_ore inside a deep carving band, or yourmod:iron -> yourmod:moon_iron inside a lunar biome).") +public final class DepositVariant { + @Required + @MinNumber(-2048) + @MaxNumber(8192) + @Desc("Inclusive minimum world Y this variant applies at.") + private int minHeight = 0; + + @Required + @MinNumber(-2048) + @MaxNumber(8192) + @Desc("Inclusive maximum world Y this variant applies at.") + private int maxHeight = 0; + + @Required + @Desc("Source block id (for example `minecraft:iron_ore`) -> replacement block id (for example `minecraft:deepslate_iron_ore`). Any block id the data loader resolves is accepted, including external/mod blocks. Source match is by material only, so block properties on the source key are ignored.") + private Map remap = Map.of(); + + public DepositVariant() { + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public Map remap() { + return remap == null ? Map.of() : Collections.unmodifiableMap(remap); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java new file mode 100644 index 000000000..e6a6d15ef --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java @@ -0,0 +1,52 @@ +/* + * 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.builtin.deposit; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The deposit ore remap rules one dimension, region or biome declares, written as {@code "depositVariants": [...]}, the list + * of {@link DepositVariant}s. The biome's rules apply first, then the region's, then the dimension's; the first matching rule wins. + */ +@Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") +@Feature(id = "iris:deposit/variants", name = "Deposit variants", key = "depositVariants", root = "variants", + targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class DepositVariantSettings implements IrisFeature { + @MinItems(1) + @Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") + private List variants = List.of(); + + public DepositVariantSettings() { + } + + public DepositVariantSettings(List variants) { + this.variants = List.copyOf(variants); + } + + public List variants() { + return variants == null ? List.of() : Collections.unmodifiableList(variants); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java b/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java new file mode 100644 index 000000000..e279b0df6 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java @@ -0,0 +1,49 @@ +/* + * 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.builtin.deposit; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A biome's {@code oreDepositFrequencyMultiplier}, written as the bare number. */ +@Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") +@Feature(id = "iris:deposit/ore-frequency", name = "Ore deposit frequency", key = "oreDepositFrequencyMultiplier", root = "multiplier", targets = Target.BIOME) +public final class OreFrequencySettings implements IrisFeature { + private static final double UNCHANGED = 1D; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") + private double multiplier = UNCHANGED; + + public OreFrequencySettings() { + } + + public OreFrequencySettings(double multiplier) { + this.multiplier = multiplier; + } + + public double multiplier() { + return multiplier; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java new file mode 100644 index 000000000..80e1d5892 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java @@ -0,0 +1,49 @@ +/* + * 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.builtin.deposit; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A biome's {@code oreDepositSizeMultiplier}, written as the bare number. */ +@Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") +@Feature(id = "iris:deposit/ore-size", name = "Ore deposit size", key = "oreDepositSizeMultiplier", root = "multiplier", targets = Target.BIOME) +public final class OreSizeSettings implements IrisFeature { + private static final double UNCHANGED = 1D; + + @MinNumber(0.01) + @MaxNumber(16) + @Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") + private double multiplier = UNCHANGED; + + public OreSizeSettings() { + } + + public OreSizeSettings(double multiplier) { + this.multiplier = multiplier; + } + + public double multiplier() { + return multiplier; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java new file mode 100644 index 000000000..afebc3443 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java @@ -0,0 +1,46 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * A dimension's {@code hideOresForHiddenOre}: whether every ore block the generator would place is replaced with its base + * material. Written as the bare boolean. + */ +@Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") +@Feature(id = "iris:terrain/hide-ores", name = "Hide ores", key = "hideOresForHiddenOre", root = "hide", targets = Target.DIMENSION) +public final class HideOresSettings implements IrisFeature { + @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") + private boolean hide = false; + + public HideOresSettings() { + } + + public HideOresSettings(boolean hide) { + this.hide = hide; + } + + public boolean hide() { + return hide; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java b/src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java new file mode 100644 index 000000000..1f9cb8f47 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java @@ -0,0 +1,80 @@ +/* + * 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.builtin.terrain; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Range; +import com.volmit.noise.NoiseStyle; + +import java.util.List; + +/** + * One ore generator of a dimension, region or biome, an entry of its {@code ores} list: single ore blocks scattered + * through the terrain by a noise field, in a vertical band. A value of IrisApi types only; the terrain module resolves + * its blocks and builds its noise ({@code ResolvedOre}). + */ +@Desc("Scatters single ore blocks through terrain by sampling a noise field at every block in a vertical band. Defined on dimensions, regions, or biomes; the most specific level wins.") +public final class OreGenerator { + private static final double DEFAULT_THRESHOLD = 0.5; + private static final double DEFAULT_RANGE_MIN = 30; + private static final double DEFAULT_RANGE_MAX = 80; + + @Desc("The ore blocks to place. An empty palette generates nothing, so this must be set for the generator to have any effect.") + private PaletteSpec palette = PaletteSpec.of(List.of()); + + @Desc("The noise style sampled per block to decide where ore appears. STATIC gives independent random speckle; smoother styles give veiny clusters.") + private NoiseStyle chanceStyle = NoiseStyle.of("STATIC"); + + @Desc("When true this generator also replaces surface-layer blocks (it runs before layers and fluid); when false it only replaces underground rock.") + private boolean generateSurface = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Noise cutoff: a block becomes ore when the sampled noise is at or below this value, so higher means more ore. 0 disables, 1 replaces everything in range.") + private double threshold = DEFAULT_THRESHOLD; + + @Desc("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.") + private Range range = Range.of(DEFAULT_RANGE_MIN, DEFAULT_RANGE_MAX); + + public OreGenerator() { + } + + public PaletteSpec palette() { + return palette; + } + + public NoiseStyle chanceStyle() { + return chanceStyle; + } + + public boolean generateSurface() { + return generateSurface; + } + + public double threshold() { + return threshold; + } + + public Range range() { + return range; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java new file mode 100644 index 000000000..ae2d39553 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java @@ -0,0 +1,52 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The ore generators one dimension, region or biome declares, written as {@code "ores": [...]}, the list of generators. + * Levels stack: a column's ores come from its biome first, then its region, then the dimension. IrisApi types only, + * like {@link OreGenerator}. + */ +@Desc("Collection of ores to be generated") +@Feature(id = "iris:terrain/ores", name = "Ores", key = "ores", root = "generators", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class OreSettings implements IrisFeature { + @MinItems(1) + @Desc("Collection of ores to be generated") + private List generators = List.of(); + + public OreSettings() { + } + + public OreSettings(List generators) { + this.generators = List.copyOf(generators); + } + + public List generators() { + return generators == null ? List.of() : Collections.unmodifiableList(generators); + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java b/src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java new file mode 100644 index 000000000..48b5a3535 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java @@ -0,0 +1,32 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; + +/** Whether a dimension hides its ores ({@code hideOresForHiddenOre}): the terrain places none and the perfection pass turns the rest into their base blocks. */ +public final class HiddenOres { + private HiddenOres() { + } + + public static boolean in(IrisDimension dimension) { + return dimension.getModuleSettings().find(HideOresSettings.class).map(HideOresSettings::hide).orElse(false); + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java index 0e5bbbaf9..11935ef1f 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -19,55 +19,52 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; 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 art.arcane.volmlib.util.math.RNG; import java.util.Comparator; +import java.util.function.LongSupplier; /** * Builds the noise of every ore generator the world's biomes, regions and dimension declare before generation needs it. - * A generator keeps the noise of the first random it is given, so each one is warmed with the random of its place in + * A generator keeps the noise of the first seed it is given, so each one is warmed with the seed of its place in * this order: the biomes by key, the regions by key, then the dimension. The order is part of what a world generates. */ final class OreWarmUp { private static final long ROOT_SEED_SALT = 7777L; private final Engine engine; + private final TerrainOres ores; private final RNG root; private int warmed; OreWarmUp(Engine engine) { + this(engine, TerrainOres.of(engine)); + } + + OreWarmUp(Engine engine, TerrainOres ores) { this.engine = engine; + this.ores = ores; this.root = new RNG(engine.getSeedManager().getComponent() + ROOT_SEED_SALT); } void warm() { + LongSupplier seeds = () -> root.nextParallelRNG(warmed++).getSeed(); + KList biomes = engine.getAllBiomes(); biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); for (IrisBiome biome : biomes) { - warmAll(biome.getOres()); + ores.of(biome).warm(seeds); } KList regions = engine.getDimension().getAllRegions(engine); regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); for (IrisRegion region : regions) { - warmAll(region.getOres()); + ores.of(region).warm(seeds); } - warmAll(engine.getDimension().getOres()); - } - - private void warmAll(KList ores) { - if (ores == null) { - return; - } - for (IrisOreGenerator ore : ores) { - if (ore != null) { - ore.warm(root.nextParallelRNG(warmed++), engine.getData()); - } - } + ores.of(engine.getDimension()).warm(seeds); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java new file mode 100644 index 000000000..ee0b330a4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java @@ -0,0 +1,125 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.terrain.OreGenerator; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSampler; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; + +import java.util.ArrayList; +import java.util.List; + +/** + * One {@link OreGenerator} made ready for one world: its palette resolved to the platform's blocks and the noise that + * decides where it places ore, built from the seed it is warmed with or, when nothing warmed it, from the terrain seed + * of its first use. The palette picks with the terrain seed. What the generator describes stays in the settings; + * everything that needs the platform, the pack or the world seed is here. + */ +final class ResolvedOre { + private final OreGenerator settings; + private final NoiseFactory noise; + private final BlockRegistry blockRegistry; + private final long terrainSeed; + private final List blocks; + private final AtomicCache chance = new AtomicCache<>(); + private final AtomicCache palette = new AtomicCache<>(); + + /** + * @param terrainSeed the seed the palette picks with, and the noise is built from when nothing warmed it first + * @param blocks the palette as the platform's blocks, each repeated by its weight + */ + ResolvedOre(OreGenerator settings, NoiseFactory noise, BlockRegistry blockRegistry, long terrainSeed, List blocks) { + this.settings = settings; + this.noise = noise; + this.blockRegistry = blockRegistry; + this.terrainSeed = terrainSeed; + this.blocks = List.copyOf(blocks); + } + + /** {@code settings} ready for {@code engine}: its blocks resolved through the pack, its picks seeded with the terrain seed. */ + static ResolvedOre of(OreGenerator settings, Engine engine) { + var resources = engine.getData().getPackResources(); + BlockRegistry registry = resources.blocks(); + return new ResolvedOre(settings, resources.noise(), registry, engine.getSeedManager().getTerrain(), weighted(registry, settings.palette().palette())); + } + + private static List weighted(BlockRegistry registry, List specs) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : specs) { + PlatformBlockState state = B.getState(registry.resolve(spec).key()); + if (state == null) { + continue; + } + for (int n = 0; n < spec.weight(); n++) { + weighted.add(state); + } + } + return weighted; + } + + boolean generatesSurface() { + return settings.generateSurface(); + } + + double minY() { + return settings.range().min(); + } + + double maxY() { + return settings.range().max(); + } + + /** Builds the chance noise from {@code seed}, unless it is built already: the first seed it is given is the one it keeps. */ + void warm(long seed) { + chance.aquire(() -> noise.sampler(settings.chanceStyle(), seed)); + } + + /** The ore block at the position, or null when the position is out of the band, the chance noise is above the threshold or the palette has no block. */ + PlatformBlockState generate(int x, int y, int z) { + if (!settings.range().contains(y)) { + return null; + } + if (settings.palette().palette().isEmpty()) { + return null; + } + NoiseSampler sampler = chance.aquire(() -> noise.sampler(settings.chanceStyle(), terrainSeed)); + if (sampler.sample(x, y, z) > settings.threshold()) { + return null; + } + return pick(x, y, z); + } + + private PlatformBlockState pick(int x, int y, int z) { + if (blocks.isEmpty()) { + return null; + } + if (blocks.size() == 1) { + return blocks.getFirst(); + } + PaletteSampler sampler = palette.aquire(() -> blockRegistry.palette(settings.palette(), terrainSeed)); + return B.getState(sampler.at(x, y, z).key()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java new file mode 100644 index 000000000..e3df4ad35 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java @@ -0,0 +1,119 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.terrain.OreGenerator; +import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.PlatformBlockState; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.LongSupplier; + +/** + * The ore generators of one dimension, region or biome made ready ({@link ResolvedOre}), in the order its settings list them + * and split into the ones that also replace surface blocks and the ones that only replace rock. A level without ores is + * {@link #NONE}. + */ +final class ResolvedOres { + static final ResolvedOres NONE = new ResolvedOres(List.of()); + + private final List all; + private final List surface; + private final List underground; + private final YBand surfaceBand; + private final YBand undergroundBand; + + ResolvedOres(List all) { + this.all = List.copyOf(all); + this.surface = this.all.stream().filter(ResolvedOre::generatesSurface).toList(); + this.underground = this.all.stream().filter(ore -> !ore.generatesSurface()).toList(); + this.surfaceBand = YBand.of(surface); + this.undergroundBand = YBand.of(underground); + } + + /** {@code settings} ready for {@code engine}; generators the pack wrote as {@code null} are left out. */ + static ResolvedOres of(OreSettings settings, Engine engine) { + List ores = new ArrayList<>(); + for (OreGenerator generator : settings.generators()) { + if (generator != null) { + ores.add(ResolvedOre.of(generator, engine)); + } + } + return ores.isEmpty() ? NONE : new ResolvedOres(ores); + } + + /** The heights where any surface ore can generate. */ + YBand surfaceBand() { + return surfaceBand; + } + + /** The heights where any rock-only ore can generate. */ + YBand undergroundBand() { + return undergroundBand; + } + + /** Warms every ore in the order the settings list them, each with the next seed. */ + void warm(LongSupplier seeds) { + for (ResolvedOre ore : all) { + ore.warm(seeds.getAsLong()); + } + } + + PlatformBlockState generateSurface(int x, int y, int z) { + return firstOre(surface, x, y, z); + } + + PlatformBlockState generateUnderground(int x, int y, int z) { + return firstOre(underground, x, y, z); + } + + private static PlatformBlockState firstOre(List ores, int x, int y, int z) { + for (int index = 0; index < ores.size(); index++) { + PlatformBlockState ore = ores.get(index).generate(x, y, z); + if (ore != null) { + return ore; + } + } + return null; + } + + /** The lowest and highest height any of a set of ores reaches; empty when there are none. */ + record YBand(boolean hasOres, double min, double max) { + static final YBand EMPTY = new YBand(false, 0, 0); + + static YBand of(List ores) { + if (ores.isEmpty()) { + return EMPTY; + } + double min = Double.POSITIVE_INFINITY; + double max = Double.NEGATIVE_INFINITY; + for (ResolvedOre ore : ores) { + min = Math.min(min, ore.minY()); + max = Math.max(max, ore.maxY()); + } + return new YBand(true, min, max); + } + + boolean contains(int y) { + return hasOres && y >= min && y <= max; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 7926c0357..3ebec481d 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -19,14 +19,15 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.builtin.terrain.OreSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.actuator.ResolvedOres.YBand; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -63,6 +64,8 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { @Override public void register(FeatureRegistry registry) { + registry.registerSettings(OreSettings.class); + registry.registerSettings(HideOresSettings.class); registry.registerLifecycle(this); } @@ -86,10 +89,16 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { private static final PlatformBlockState BEDROCK = B.getState("BEDROCK"); private final Engine engine; + private final TerrainOres ores; private final RNG rng; TerrainShaper(Engine engine) { + this(engine, TerrainOres.of(engine)); + } + + TerrainShaper(Engine engine, TerrainOres ores) { this.engine = engine; + this.ores = ores; this.rng = new RNG(engine.getSeedManager().getTerrain()); } @@ -115,7 +124,7 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { int fluidHeight = dimension.getFluidHeight(); int clampedFluidHeight = Math.min(chunkHeight, fluidHeight); boolean bedrockEnabled = dimension.isBedrock(); - boolean hideOres = dimension.isHideOresForHiddenOre(); + boolean hideOres = HiddenOres.in(dimension); ChunkedDataCache biomeCache = context.getBiome(); ChunkedDataCache regionCache = context.getRegion(); ChunkedDataCache fluidCache = context.getFluid(); @@ -123,11 +132,10 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { int realX = xf + x; UpperDimensionContext upperContext = engine.getUpperContext(); // Dimension-level ore lookups are chunk-invariant; resolving them per column paid - // four accessor chains times 256 per chunk for constants. - KList dimensionSurfaceOres = hideOres ? null : dimension.getSurfaceOreGenerators(); - KList dimensionUndergroundOres = hideOres ? null : dimension.getUndergroundOreGenerators(); - IrisOreGeneratorBounds dimensionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getSurfaceOreGeneratorBounds(); - IrisOreGeneratorBounds dimensionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : dimension.getUndergroundOreGeneratorBounds(); + // the settings lookup times 256 per chunk for a constant. + ResolvedOres dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(dimension); + YBand dimensionSurfaceBand = dimensionOres.surfaceBand(); + YBand dimensionUndergroundBand = dimensionOres.undergroundBand(); for (int zf = 0; zf < chunkDepth; zf++) { int realZ = zf + z; @@ -143,16 +151,14 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { PlatformBlockState fluid = fluidCache.get(xf, zf); PlatformBlockState rock = rockCache.get(xf, zf); PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ); - KList biomeSurfaceOres = hideOres ? null : biome.getSurfaceOreGenerators(); - KList regionSurfaceOres = hideOres ? null : region.getSurfaceOreGenerators(); - KList biomeUndergroundOres = hideOres ? null : biome.getUndergroundOreGenerators(); - KList regionUndergroundOres = hideOres ? null : region.getUndergroundOreGenerators(); - IrisOreGeneratorBounds biomeSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getSurfaceOreGeneratorBounds(); - IrisOreGeneratorBounds regionSurfaceOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getSurfaceOreGeneratorBounds(); - IrisOreGeneratorBounds biomeUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : biome.getUndergroundOreGeneratorBounds(); - IrisOreGeneratorBounds regionUndergroundOreBounds = hideOres ? IrisOreGeneratorBounds.EMPTY : region.getUndergroundOreGeneratorBounds(); - boolean hasSurfaceOres = biomeSurfaceOreBounds.hasOres() || regionSurfaceOreBounds.hasOres() || dimensionSurfaceOreBounds.hasOres(); - boolean hasUndergroundOres = biomeUndergroundOreBounds.hasOres() || regionUndergroundOreBounds.hasOres() || dimensionUndergroundOreBounds.hasOres(); + ResolvedOres biomeOres = hideOres ? ResolvedOres.NONE : ores.of(biome); + ResolvedOres regionOres = hideOres ? ResolvedOres.NONE : ores.of(region); + YBand biomeSurfaceBand = biomeOres.surfaceBand(); + YBand regionSurfaceBand = regionOres.surfaceBand(); + YBand biomeUndergroundBand = biomeOres.undergroundBand(); + YBand regionUndergroundBand = regionOres.undergroundBand(); + boolean hasSurfaceOres = biomeSurfaceBand.hasOres() || regionSurfaceBand.hasOres() || dimensionSurfaceBand.hasOres(); + boolean hasUndergroundOres = biomeUndergroundBand.hasOres() || regionUndergroundBand.hasOres() || dimensionUndergroundBand.hasOres(); KList blocks = null; KList fblocks = null; @@ -164,14 +170,14 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { PlatformBlockState ore = null; if (hasSurfaceOres) { - if (biomeSurfaceOreBounds.contains(i)) { - ore = generateOres(biomeSurfaceOres, realX, i, realZ, localRng, data); + if (biomeSurfaceBand.contains(i)) { + ore = biomeOres.generateSurface(realX, i, realZ); } - if (ore == null && regionSurfaceOreBounds.contains(i)) { - ore = generateOres(regionSurfaceOres, realX, i, realZ, localRng, data); + if (ore == null && regionSurfaceBand.contains(i)) { + ore = regionOres.generateSurface(realX, i, realZ); } - if (ore == null && dimensionSurfaceOreBounds.contains(i)) { - ore = generateOres(dimensionSurfaceOres, realX, i, realZ, localRng, data); + if (ore == null && dimensionSurfaceBand.contains(i)) { + ore = dimensionOres.generateSurface(realX, i, realZ); } } if (ore != null) { @@ -209,14 +215,14 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { } if (hasUndergroundOres) { - if (biomeUndergroundOreBounds.contains(i)) { - ore = generateOres(biomeUndergroundOres, realX, i, realZ, localRng, data); + if (biomeUndergroundBand.contains(i)) { + ore = biomeOres.generateUnderground(realX, i, realZ); } - if (ore == null && regionUndergroundOreBounds.contains(i)) { - ore = generateOres(regionUndergroundOres, realX, i, realZ, localRng, data); + if (ore == null && regionUndergroundBand.contains(i)) { + ore = regionOres.generateUnderground(realX, i, realZ); } - if (ore == null && dimensionUndergroundOreBounds.contains(i)) { - ore = generateOres(dimensionUndergroundOres, realX, i, realZ, localRng, data); + if (ore == null && dimensionUndergroundBand.contains(i)) { + ore = dimensionOres.generateUnderground(realX, i, realZ); } } @@ -264,22 +270,5 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { } } } - - private PlatformBlockState generateOres(KList oreGenerators, int x, int y, int z, RNG rng, IrisData data) { - if (oreGenerators == null || oreGenerators.isEmpty()) { - return null; - } - - int oreCount = oreGenerators.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = oreGenerators.get(oreIndex); - PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); - if (ore != null) { - return ore; - } - } - - return null; - } } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java new file mode 100644 index 000000000..8dc6a9b0e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -0,0 +1,53 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.engine.framework.Engine; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the terrain module keeps for one world: the ore generators of its dimension, regions and biomes made ready + * ({@link ResolvedOres}), built from their {@link OreSettings} when first asked for or ahead of generation by {@link OreWarmUp}. + */ +final class TerrainOres { + private final Engine engine; + private final Map resolved = new ConcurrentHashMap<>(); + + TerrainOres(Engine engine) { + this.engine = engine; + } + + /** The ores of the world {@code engine} generates now. */ + static TerrainOres of(Engine engine) { + return engine.getGeneration().state(TerrainOres.class, TerrainOres::new); + } + + /** The ore generators {@code owner}, a dimension, region or biome, declares; {@link ResolvedOres#NONE} when it declares none. */ + ResolvedOres of(IrisRegistrant owner) { + OreSettings settings = owner.getModuleSettings().find(OreSettings.class).orElse(null); + if (settings == null) { + return ResolvedOres.NONE; + } + return resolved.computeIfAbsent(settings, declared -> ResolvedOres.of(declared, engine)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index f2889714b..668755e37 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -21,7 +21,11 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositSettings; +import art.arcane.iris.builtin.deposit.DepositVariantSettings; +import art.arcane.iris.builtin.deposit.OreFrequencySettings; +import art.arcane.iris.builtin.deposit.OreSizeSettings; import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.FeatureSettings; @@ -48,6 +52,13 @@ public final class DepositModule implements IrisModule { return ModuleInfo.of("iris:deposit", "Deposits", VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerSettings(DepositVariantSettings.class); + registry.registerSettings(OreFrequencySettings.class); + registry.registerSettings(OreSizeSettings.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Deposit.ORES) diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index ff3844442..2a8906b69 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -21,10 +21,14 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositHeightDistribution; import art.arcane.iris.builtin.deposit.DepositPlacementScope; +import art.arcane.iris.builtin.deposit.DepositVariant; +import art.arcane.iris.builtin.deposit.DepositVariantSettings; +import art.arcane.iris.builtin.deposit.OreFrequencySettings; +import art.arcane.iris.builtin.deposit.OreSizeSettings; +import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedComponent; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.engine.object.prefab.IrisObject; @@ -52,7 +56,10 @@ import java.util.concurrent.ConcurrentHashMap; */ public class DepositPlacer extends EngineAssignedComponent { private final RNG rng; + private static final double UNCHANGED_ORE_MULTIPLIER = 1D; + private final Map resolved = new ConcurrentHashMap<>(); + private final Map variants = new ConcurrentHashMap<>(); public DepositPlacer(Engine engine) { super(engine, "Deposit"); @@ -150,13 +157,13 @@ public class DepositPlacer extends EngineAssignedComponent { if (oreDeposit) { if (depositBiome != null) { - double frequencyMultiplier = depositBiome.getOreDepositFrequencyMultiplier(); + double frequencyMultiplier = oreFrequencyMultiplier(depositBiome); if (frequencyMultiplier < 1D && !passesOreFrequency(frequencyMultiplier, rng.d())) { continue; } - double sizeMultiplier = depositBiome.getOreDepositSizeMultiplier(); + double sizeMultiplier = oreSizeMultiplier(depositBiome); if (sizeMultiplier != 1D) { IrisObject scaledClump = deposit.clump(rng, sizeMultiplier); int scaledDimension = scaledClump.getW(); @@ -317,7 +324,7 @@ public class DepositPlacer extends EngineAssignedComponent { IrisBiome biome = getEngine().getCaveBiome(worldX, localY, worldZ, carvingState); if (biome != null) { - PlatformBlockState match = matchDepositVariant(biome.getDepositVariants(), ore, worldY); + PlatformBlockState match = matchDepositVariant(biome, ore, worldY); if (match != null) { return match; } @@ -325,14 +332,14 @@ public class DepositPlacer extends EngineAssignedComponent { IrisRegion region = context.getRegion().get(nx, nz); if (region != null) { - PlatformBlockState match = matchDepositVariant(region.getDepositVariants(), ore, worldY); + PlatformBlockState match = matchDepositVariant(region, ore, worldY); if (match != null) { return match; } } if (dimension != null) { - PlatformBlockState match = matchDepositVariant(dimension.getDepositVariants(), ore, worldY); + PlatformBlockState match = matchDepositVariant(dimension, ore, worldY); if (match != null) { return match; } @@ -341,17 +348,14 @@ public class DepositPlacer extends EngineAssignedComponent { return null; } - private PlatformBlockState matchDepositVariant(java.util.List variants, PlatformBlockState ore, int y) { - if (variants == null || variants.isEmpty()) { - return null; - } - - for (IrisDepositVariant variant : variants) { - if (y < variant.getMinHeight() || y > variant.getMaxHeight()) { + private PlatformBlockState matchDepositVariant(IrisRegistrant owner, PlatformBlockState ore, int y) { + for (DepositVariant declared : variantsOf(owner)) { + ResolvedDepositVariant variant = variants.computeIfAbsent(declared, ResolvedDepositVariant::new); + if (!variant.appliesAt(y)) { continue; } - PlatformBlockState swapped = variant.remapOrNull(ore, getData()); + PlatformBlockState swapped = variant.remapOrNull(ore); if (swapped != null) { return swapped; } @@ -359,4 +363,16 @@ public class DepositPlacer extends EngineAssignedComponent { return null; } + + private static List variantsOf(IrisRegistrant owner) { + return owner.getModuleSettings().find(DepositVariantSettings.class).map(DepositVariantSettings::variants).orElse(List.of()); + } + + private static double oreFrequencyMultiplier(IrisBiome biome) { + return biome.getModuleSettings().find(OreFrequencySettings.class).map(OreFrequencySettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); + } + + private static double oreSizeMultiplier(IrisBiome biome) { + return biome.getModuleSettings().find(OreSizeSettings.class).map(OreSizeSettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); + } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index 6e45f193f..cc98dc82c 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -20,6 +20,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.actuator.HiddenOres; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.world.dimension.IrisDimension; @@ -68,7 +69,7 @@ public final class PerfectionModule implements IrisModule { IrisDimension dimension = engine.getDimension(); PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); Hunk blocks = chunk.blocks(); - if (dimension.isHideOresForHiddenOre()) { + if (HiddenOres.in(dimension)) { hideOres(blocks); } boolean removed; diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java new file mode 100644 index 000000000..b1a6dce34 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java @@ -0,0 +1,66 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.deposit.DepositVariant; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; + +import java.util.HashMap; +import java.util.Map; + +/** + * One {@link DepositVariant} made ready: its source and replacement block ids resolved to the platform's blocks, built once on + * first use. A rule whose source or replacement the platform does not know remaps nothing. + */ +final class ResolvedDepositVariant { + private final DepositVariant settings; + private final AtomicCache> remapped = new AtomicCache<>(); + + ResolvedDepositVariant(DepositVariant settings) { + this.settings = settings; + } + + boolean appliesAt(int worldY) { + return worldY >= settings.minHeight() && worldY <= settings.maxHeight(); + } + + /** The block {@code ore} is rewritten to, or null when the rule does not remap its material. */ + PlatformBlockState remapOrNull(PlatformBlockState ore) { + if (ore == null || settings.remap().isEmpty()) { + return null; + } + return remapped.aquire(this::resolveRemap).get(IrisProceduralBlocks.materialKey(ore)); + } + + private Map resolveRemap() { + Map resolved = new HashMap<>(); + for (Map.Entry entry : settings.remap().entrySet()) { + PlatformBlockState source = B.getStateOrNull(entry.getKey(), false); + PlatformBlockState target = B.getStateOrNull(entry.getValue(), true); + if (source == null || target == null) { + continue; + } + resolved.put(IrisProceduralBlocks.materialKey(source), target); + } + return resolved; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java deleted file mode 100644 index 1473d3b1b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisBiomeOres.java +++ /dev/null @@ -1,130 +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.deposit; - -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -/** - * Ore generation for {@link IrisBiome}. IrisBiome is Gson deserialized from pack JSON, so its - * fields stay put and only the behavior lives here. Note that {@code IrisBiome.setOres(KList)} - * stays on IrisBiome: it is a hand written Lombok setter override that resets these caches. - */ -public final class IrisBiomeOres { - private IrisBiomeOres() { - } - - public static PlatformBlockState generateOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data, boolean surface) { - KList localOres = surface ? getSurfaceOres(biome) : getUndergroundOres(biome); - return generateOres(localOres, x, y, z, rng, data); - } - - public static PlatformBlockState generateSurfaceOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getSurfaceOres(biome), x, y, z, rng, data); - } - - public static PlatformBlockState generateUndergroundOres(IrisBiome biome, int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getUndergroundOres(biome), x, y, z, rng, data); - } - - public static boolean hasSurfaceOres(IrisBiome biome) { - return !getSurfaceOres(biome).isEmpty(); - } - - public static boolean hasUndergroundOres(IrisBiome biome) { - return !getUndergroundOres(biome).isEmpty(); - } - - public static KList getSurfaceOreGenerators(IrisBiome biome) { - return getOres(biome, true); - } - - public static KList getUndergroundOreGenerators(IrisBiome biome) { - return getOres(biome, false); - } - - public static IrisOreGeneratorBounds getSurfaceOreGeneratorBounds(IrisBiome biome) { - // getIfPresent fast path: aquire allocates a capturing lambda even on a hit, and this - // runs per column on the terrain hot path. - IrisOreGeneratorBounds cached = biome.getSurfaceOreBoundsCache().getIfPresent(); - if (cached != null) { - return cached; - } - return biome.getSurfaceOreBoundsCache().aquire(() -> IrisOreGeneratorBounds.of(getSurfaceOres(biome))); - } - - public static IrisOreGeneratorBounds getUndergroundOreGeneratorBounds(IrisBiome biome) { - IrisOreGeneratorBounds cached = biome.getUndergroundOreBoundsCache().getIfPresent(); - if (cached != null) { - return cached; - } - return biome.getUndergroundOreBoundsCache().aquire(() -> IrisOreGeneratorBounds.of(getUndergroundOres(biome))); - } - - private static KList getSurfaceOres(IrisBiome biome) { - return getOres(biome, true); - } - - private static KList getUndergroundOres(IrisBiome biome) { - return getOres(biome, false); - } - - private static KList getOres(IrisBiome biome, boolean surface) { - AtomicCache> oreCache = surface ? biome.getSurfaceOreCache() : biome.getUndergroundOreCache(); - KList cached = oreCache.getIfPresent(); - - if (cached != null) { - return cached; - } - - return oreCache.aquire(() -> { - KList filtered = new KList<>(); - KList localOres = biome.getOres(); - int oreCount = localOres.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = localOres.get(oreIndex); - if (oreGenerator.isGenerateSurface() == surface) { - filtered.add(oreGenerator); - } - } - - return filtered; - }); - } - - private static PlatformBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { - if (localOres.isEmpty()) { - return null; - } - - int oreCount = localOres.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = localOres.get(oreIndex); - PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); - if (ore != null) { - return ore; - } - } - return null; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java deleted file mode 100644 index 966a751d1..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisDepositVariant.java +++ /dev/null @@ -1,87 +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.deposit; - -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.volmlib.util.collection.KMap; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import lombok.experimental.Accessors; - -@Snippet("deposit-variant") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Remaps ore block ids to alternate block ids within a vertical band. Ores declared at dimension, region, and biome scope can be rewritten at placement time (for example, iron_ore -> deepslate_iron_ore inside a deep carving band, or yourmod:iron -> yourmod:moon_iron inside a lunar biome).") -@Data -public class IrisDepositVariant { - private final transient AtomicCache> resolved = new AtomicCache<>(); - - @Required - @MinNumber(-2048) - @MaxNumber(8192) - @Desc("Inclusive minimum world Y this variant applies at.") - private int minHeight = 0; - - @Required - @MinNumber(-2048) - @MaxNumber(8192) - @Desc("Inclusive maximum world Y this variant applies at.") - private int maxHeight = 0; - - @Required - @Desc("Source block id (for example `minecraft:iron_ore`) -> replacement block id (for example `minecraft:deepslate_iron_ore`). Any block id the data loader resolves is accepted, including external/mod blocks. Source match is by material only, so block properties on the source key are ignored.") - private KMap remap = new KMap<>(); - - public PlatformBlockState remapOrNull(PlatformBlockState ore, IrisData rdata) { - if (ore == null || remap == null || remap.isEmpty()) { - return null; - } - - KMap map = resolved.aquire(() -> buildResolved(rdata)); - return map.get(IrisProceduralBlocks.materialKey(ore)); - } - - private KMap buildResolved(IrisData rdata) { - KMap out = new KMap<>(); - - for (java.util.Map.Entry entry : remap.entrySet()) { - PlatformBlockState source = B.getStateOrNull(entry.getKey(), false); - PlatformBlockState target = B.getStateOrNull(entry.getValue(), true); - - if (source == null || target == null) { - continue; - } - - out.put(IrisProceduralBlocks.materialKey(source), target); - } - - return out; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java deleted file mode 100644 index ed5e9502e..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGenerator.java +++ /dev/null @@ -1,81 +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.deposit; - -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Scatters single ore blocks through terrain by sampling a noise field at every block in a vertical band. Defined on dimensions, regions, or biomes; the most specific level wins.") -@Data -public class IrisOreGenerator { - @Desc("The ore blocks to place. An empty palette generates nothing, so this must be set for the generator to have any effect.") - private IrisMaterialPalette palette = new IrisMaterialPalette().qclear(); - @Desc("The noise style sampled per block to decide where ore appears. STATIC gives independent random speckle; smoother styles give veiny clusters.") - private IrisGeneratorStyle chanceStyle = new IrisGeneratorStyle(NoiseStyle.STATIC); - @Desc("When true this generator also replaces surface-layer blocks (it runs before layers and fluid); when false it only replaces underground rock.") - private boolean generateSurface = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("Noise cutoff: a block becomes ore when the sampled noise is at or below this value, so higher means more ore. 0 disables, 1 replaces everything in range.") - private double threshold = 0.5; - @Desc("Vertical band (min, max) this ore can generate in, in engine-local Y where 0 is the bottom of the dimension, not world Y.") - private IrisRange range = new IrisRange(30, 80); - - private transient AtomicCache chanceCache = new AtomicCache<>(); - - public void warm(RNG rng, IrisData data) { - chanceCache.aquire(() -> chanceStyle.create(rng, data)); - palette.getLayerGenerator(rng, data); - } - - public PlatformBlockState generate(int x, int y, int z, RNG rng, IrisData data) { - if (!range.contains(y)) { - return null; - } - - if (palette.getPalette().isEmpty()) { - return null; - } - - CNG chance = chanceCache.aquire(() -> chanceStyle.create(rng, data)); - - if (chance.noise(x, y, z) > threshold) { - return null; - } - - return palette.get(rng, x, y, z, data); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java b/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java deleted file mode 100644 index aea87f2c0..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/deposit/IrisOreGeneratorBounds.java +++ /dev/null @@ -1,44 +0,0 @@ -package art.arcane.iris.engine.object.terrain.deposit; - -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.volmlib.util.collection.KList; - -public final class IrisOreGeneratorBounds { - public static final IrisOreGeneratorBounds EMPTY = new IrisOreGeneratorBounds(false, 0D, 0D); - - private final boolean hasOres; - private final double min; - private final double max; - - private IrisOreGeneratorBounds(boolean hasOres, double min, double max) { - this.hasOres = hasOres; - this.min = min; - this.max = max; - } - - public static IrisOreGeneratorBounds of(KList ores) { - if (ores == null || ores.isEmpty()) { - return EMPTY; - } - - double min = Double.POSITIVE_INFINITY; - double max = Double.NEGATIVE_INFINITY; - int oreCount = ores.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = ores.get(oreIndex); - IrisRange range = oreGenerator.getRange(); - min = Math.min(min, range.getMin()); - max = Math.max(max, range.getMax()); - } - - return new IrisOreGeneratorBounds(true, min, max); - } - - public boolean hasOres() { - return hasOres; - } - - public boolean contains(int y) { - return hasOres && y >= min && y <= max; - } -} 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 index 2be388ff5..d6da53ad2 100644 --- 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 @@ -31,10 +31,6 @@ import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.terrain.IrisBiomeLayerGenerator; import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; -import art.arcane.iris.engine.object.terrain.deposit.IrisBiomeOres; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; 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; @@ -78,7 +74,7 @@ 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 IrisBiomeLayerGenerator}, {@link IrisBiomeDerivatives}, {@link IrisBiomeOres}, + * {@link IrisBiomeLayerGenerator}, {@link IrisBiomeDerivatives}, * {@link IrisBiomeColorRenderer} and {@link IrisBiomeGenLinks}. */ @Accessors(chain = true) @@ -112,10 +108,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { private final transient AtomicCache> realChildren = new AtomicCache<>(); private final transient AtomicCache> layerHeightGenerators = new AtomicCache<>(); private final transient AtomicCache> layerSeaHeightGenerators = new AtomicCache<>(); - private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); - private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); - private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); - private final transient AtomicCache undergroundOreBoundsCache = new AtomicCache<>(); private final transient AtomicCache derivativeResolved = new AtomicCache<>(); private final transient AtomicCache vanillaDerivativeResolved = new AtomicCache<>(); private final transient AtomicCache> biomeScatterResolved = new AtomicCache<>(); @@ -217,44 +209,10 @@ public class IrisBiome extends IrisRegistrant implements IRare { @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()); - @MinNumber(0) - @MaxNumber(1) - @Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") - private double oreDepositFrequencyMultiplier = 1D; - @MinNumber(0.01) - @MaxNumber(16) - @Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") - private double oreDepositSizeMultiplier = 1D; - @ArrayType(min = 1, type = IrisDepositVariant.class) - @Desc("Deposit ore remap rules scoped to this biome. Each entry declares a vertical band and a source->replacement block id map. Applied before regional and dimension rules; first matching biome rule wins.") - private KList depositVariants = new KList<>(); private transient volatile InferredType inferredType; @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private final transient EnumMap inferredVariants = new EnumMap<>(InferredType.class); - @Desc("Collection of ores to be generated") - @ArrayType(type = IrisOreGenerator.class, min = 1) - private KList ores = new KList<>(); - - public PlatformBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { - return IrisBiomeOres.generateOres(this, x, y, z, rng, data, surface); - } - - public PlatformBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { - return IrisBiomeOres.generateSurfaceOres(this, x, y, z, rng, data); - } - - public PlatformBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { - return IrisBiomeOres.generateUndergroundOres(this, x, y, z, rng, data); - } - - public boolean hasSurfaceOres() { - return IrisBiomeOres.hasSurfaceOres(this); - } - - public boolean hasUndergroundOres() { - return IrisBiomeOres.hasUndergroundOres(this); - } public synchronized IrisBiome setInferredType(InferredType inferredType) { this.inferredType = inferredType; @@ -292,39 +250,12 @@ public class IrisBiome extends IrisRegistrant implements IRare { variant.setLoader(data); variant.setLoadKey(getLoadKey()); variant.setLoadFile(getLoadFile()); + variant.setModuleSettings(getModuleSettings()); variant.inferredType = type; inferredVariants.put(type, variant); return variant; } - /** - * Hand written override of the Lombok setter. It must stay here because it invalidates the ore - * caches that {@link IrisBiomeOres} reads. - */ - public void setOres(KList ores) { - this.ores = ores == null ? new KList<>() : ores; - surfaceOreCache.reset(); - undergroundOreCache.reset(); - surfaceOreBoundsCache.reset(); - undergroundOreBoundsCache.reset(); - } - - public KList getSurfaceOreGenerators() { - return IrisBiomeOres.getSurfaceOreGenerators(this); - } - - public KList getUndergroundOreGenerators() { - return IrisBiomeOres.getUndergroundOreGenerators(this); - } - - public IrisOreGeneratorBounds getSurfaceOreGeneratorBounds() { - return IrisBiomeOres.getSurfaceOreGeneratorBounds(this); - } - - public IrisOreGeneratorBounds getUndergroundOreGeneratorBounds() { - return IrisBiomeOres.getUndergroundOreGeneratorBounds(this); - } - public Biome getDerivative() { Biome cached = derivativeResolved.getIfPresent(); 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 index 8f37e4768..b59850df2 100644 --- 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 @@ -35,9 +35,6 @@ import art.arcane.iris.engine.object.procedural.tree.IrisTreeSettings; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.world.IrisEnvironment; import art.arcane.iris.engine.object.world.IrisWorldBoundary; @@ -114,10 +111,6 @@ public class IrisDimension extends IrisRegistrant { private final transient AtomicCache rad = new AtomicCache<>(); private final transient AtomicCache featuresUsed = new AtomicCache<>(); private final transient AtomicCache> carvingEntryIndex = new AtomicCache<>(); - private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); - private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); - private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); - private final transient AtomicCache undergroundOreBoundsCache = new AtomicCache<>(); @MinNumber(2) @Required @Desc("The human readable name of this dimension") @@ -176,8 +169,6 @@ public class IrisDimension extends IrisRegistrant { private boolean debugSmartBore = false; @Desc("Generate decorations or not") private boolean decorate = true; - @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") - private boolean hideOresForHiddenOre = false; @Desc("Use post processing or not") private boolean postProcessing = true; @Desc("Add slabs in post processing") @@ -275,9 +266,6 @@ public class IrisDimension extends IrisRegistrant { private boolean useMantle = true; @Desc("Prevent Leaf decay as if placed in creative mode") private boolean preventLeafDecay = false; - @ArrayType(min = 1, type = IrisDepositVariant.class) - @Desc("Dimension-wide deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied after biome and region rules; first matching dimension rule wins.") - private KList depositVariants = new KList<>(); @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) @Desc("Overlay additional noise on top of the interoplated terrain.") private KList overlayNoise = new KList<>(); @@ -285,9 +273,6 @@ public class IrisDimension extends IrisRegistrant { private IrisMaterialPalette rockPalette = new IrisMaterialPalette().qclear().qadd("stone"); @Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("water"); - @Desc("Collection of ores to be generated") - @ArrayType(type = IrisOreGenerator.class, min = 1) - private KList ores = new KList<>(); @Desc("Dimension-wide Iris structure placements, independent of biome/region placements") @ArrayType(type = IrisStructurePlacement.class, min = 1) private KList structures = new KList<>(); @@ -343,92 +328,6 @@ public class IrisDimension extends IrisRegistrant { carvingEntryIndex.reset(); } - public PlatformBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { - KList localOres = surface ? getSurfaceOres() : getUndergroundOres(); - return generateOres(localOres, x, y, z, rng, data); - } - - public PlatformBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getSurfaceOres(), x, y, z, rng, data); - } - - public PlatformBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getUndergroundOres(), x, y, z, rng, data); - } - - public boolean hasSurfaceOres() { - return !getSurfaceOres().isEmpty(); - } - - public boolean hasUndergroundOres() { - return !getUndergroundOres().isEmpty(); - } - - private PlatformBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { - if (localOres.isEmpty()) { - return null; - } - - int oreCount = localOres.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = localOres.get(oreIndex); - PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); - if (ore != null) { - return ore; - } - } - return null; - } - - public void setOres(KList ores) { - this.ores = ores == null ? new KList<>() : ores; - surfaceOreCache.reset(); - undergroundOreCache.reset(); - surfaceOreBoundsCache.reset(); - undergroundOreBoundsCache.reset(); - } - - public KList getSurfaceOreGenerators() { - return getOres(true); - } - - public KList getUndergroundOreGenerators() { - return getOres(false); - } - - public IrisOreGeneratorBounds getSurfaceOreGeneratorBounds() { - return surfaceOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getSurfaceOres())); - } - - public IrisOreGeneratorBounds getUndergroundOreGeneratorBounds() { - return undergroundOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getUndergroundOres())); - } - - private KList getSurfaceOres() { - return getOres(true); - } - - private KList getUndergroundOres() { - return getOres(false); - } - - private KList getOres(boolean surface) { - AtomicCache> oreCache = surface ? surfaceOreCache : undergroundOreCache; - return oreCache.aquire(() -> { - KList filtered = new KList<>(); - KList localOres = ores; - int oreCount = localOres.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = localOres.get(oreIndex); - if (oreGenerator.isGenerateSurface() == surface) { - filtered.add(oreGenerator); - } - } - - return filtered; - }); - } - public int getFluidHeight() { return fluidHeight - (int) dimensionHeight.getMin(); } 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 index 8c03c3310..60b0583ce 100644 --- 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 @@ -26,9 +26,6 @@ import art.arcane.iris.engine.object.loot.IrisLootReference; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; -import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; 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; @@ -77,10 +74,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { private final transient AtomicCache> realShoreBiomes = new AtomicCache<>(); private final transient AtomicCache> realCaveBiomes = new AtomicCache<>(); private final transient AtomicCache cacheColor = new AtomicCache<>(); - private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); - private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); - private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); - private final transient AtomicCache undergroundOreBoundsCache = new AtomicCache<>(); @MinNumber(2) @Required @Desc("The name of the region") @@ -149,100 +142,8 @@ public class IrisRegion extends IrisRegistrant implements IRare { @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<>(); - @ArrayType(min = 1, type = IrisDepositVariant.class) - @Desc("Deposit ore remap rules scoped to this region. Each entry declares a vertical band and a source->replacement block id map. Applied after biome rules but before dimension rules; first matching region rule wins.") - private KList depositVariants = 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; - @Desc("Collection of ores to be generated") - @ArrayType(type = IrisOreGenerator.class, min = 1) - private KList ores = new KList<>(); - - public PlatformBlockState generateOres(int x, int y, int z, RNG rng, IrisData data, boolean surface) { - KList localOres = surface ? getSurfaceOres() : getUndergroundOres(); - return generateOres(localOres, x, y, z, rng, data); - } - - public PlatformBlockState generateSurfaceOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getSurfaceOres(), x, y, z, rng, data); - } - - public PlatformBlockState generateUndergroundOres(int x, int y, int z, RNG rng, IrisData data) { - return generateOres(getUndergroundOres(), x, y, z, rng, data); - } - - public boolean hasSurfaceOres() { - return !getSurfaceOres().isEmpty(); - } - - public boolean hasUndergroundOres() { - return !getUndergroundOres().isEmpty(); - } - - private PlatformBlockState generateOres(KList localOres, int x, int y, int z, RNG rng, IrisData data) { - if (localOres.isEmpty()) { - return null; - } - - int oreCount = localOres.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = localOres.get(oreIndex); - PlatformBlockState ore = oreGenerator.generate(x, y, z, rng, data); - if (ore != null) { - return ore; - } - } - return null; - } - - public void setOres(KList ores) { - this.ores = ores == null ? new KList<>() : ores; - surfaceOreCache.reset(); - undergroundOreCache.reset(); - surfaceOreBoundsCache.reset(); - undergroundOreBoundsCache.reset(); - } - - public KList getSurfaceOreGenerators() { - return getOres(true); - } - - public KList getUndergroundOreGenerators() { - return getOres(false); - } - - public IrisOreGeneratorBounds getSurfaceOreGeneratorBounds() { - return surfaceOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getSurfaceOres())); - } - - public IrisOreGeneratorBounds getUndergroundOreGeneratorBounds() { - return undergroundOreBoundsCache.aquire(() -> IrisOreGeneratorBounds.of(getUndergroundOres())); - } - - private KList getSurfaceOres() { - return getOres(true); - } - - private KList getUndergroundOres() { - return getOres(false); - } - - private KList getOres(boolean surface) { - AtomicCache> oreCache = surface ? surfaceOreCache : undergroundOreCache; - return oreCache.aquire(() -> { - KList filtered = new KList<>(); - KList localOres = ores; - int oreCount = localOres.size(); - for (int oreIndex = 0; oreIndex < oreCount; oreIndex++) { - IrisOreGenerator oreGenerator = localOres.get(oreIndex); - if (oreGenerator.isGenerateSurface() == surface) { - filtered.add(oreGenerator); - } - } - - return filtered; - }); - } public String getName() { return name; From 23eaa15e86f48fe112880266a516db9f09886d61 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:36:44 +0200 Subject: [PATCH 050/139] Layers, slab, wall, sea and cave ceiling layers, rock and fluid palettes and the post processing switches become iris:terrain and iris:post settings IrisBiomePaletteLayer is the PaletteLayer value, IrisBiomeLayerGenerator is BiomeLayers over ResolvedLayer, the dimension's rock and fluid streams are TerrainPalettes. The decorator slope and SlopeClip are one class. A biome's inferred variants keep its module settings. --- README.md | 9 + source-patterns.txt | 1 + .../iris/builtin/decorant/Decorator.java | 7 +- .../iris/builtin/decorant/DecoratorSlope.java | 64 ---- .../builtin/floating/FloatingChildBiome.java | 6 +- .../builtin/post/PostProcessingSettings.java | 44 +++ .../post/PostProcessingSlabsSettings.java | 43 +++ .../post/PostProcessingWallsSettings.java | 43 +++ .../iris/builtin/prepare/SlopeClip.java | 2 +- .../terrain/CaveCeilingLayersSettings.java | 43 +++ .../builtin/terrain/FluidPaletteSettings.java | 47 +++ .../iris/builtin/terrain/LayersSettings.java | 44 +++ .../terrain/LockLayersMaxSettings.java | 41 ++ .../builtin/terrain/LockLayersSettings.java | 39 ++ .../iris/builtin/terrain/PaletteLayer.java | 103 +++++ .../builtin/terrain/RockPaletteSettings.java | 47 +++ .../builtin/terrain/SeaLayersSettings.java | 43 +++ .../iris/builtin/terrain/SlabSettings.java | 41 ++ .../iris/builtin/terrain/WallSettings.java | 42 ++ .../iris/engine/actuator/TerrainModule.java | 48 ++- .../engine/mantle/components/CaveCarving.java | 7 +- .../iris/engine/modifier/CaveApplying.java | 18 +- .../iris/engine/modifier/FloatingIslands.java | 24 +- .../iris/engine/modifier/PostModule.java | 11 + .../engine/modifier/SurfaceSmoothing.java | 22 +- .../engine/object/placement/VacuumModule.java | 8 +- .../terrain/IrisBiomeLayerGenerator.java | 360 ------------------ .../object/terrain/IrisBiomePaletteLayer.java | 165 -------- .../engine/object/world/biome/IrisBiome.java | 67 +--- .../world/biome/IrisBiomeColorRenderer.java | 6 +- .../object/world/dimension/IrisDimension.java | 11 - .../iris/engine/terrain/BiomeLayers.java | 344 +++++++++++++++++ .../iris/engine/terrain/PaletteBlocks.java | 48 +++ .../iris/engine/terrain/ResolvedLayer.java | 139 +++++++ .../iris/engine/terrain/TerrainPalettes.java | 137 +++++++ 35 files changed, 1412 insertions(+), 712 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java create mode 100644 src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java create mode 100644 src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java create mode 100644 src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java create mode 100644 src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java create mode 100644 src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java diff --git a/README.md b/README.md index 4bf62dc47..1cf202039 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,15 @@ seed is the world's decorator seed, its biome's key and its place in the biome's them ahead of generation; `iris:terrain` and `iris:objects` warm their ore generators, placements and procedural objects the same way. +`iris:terrain` and `iris:post` own the fields that shape a column's blocks. Per biome: `layers`, `seaLayers`, `caveCeilingLayers` (lists of +`PaletteLayer`, the old biome palette layer, in `art.arcane.iris.builtin.terrain`), `slab` and `wall` (one `PaletteLayer` each), `lockLayers` (a +boolean) and `lockLayersMax` (a number). Per dimension: `rockPalette` and `fluidPalette` (a `PaletteSpec` each) in `art.arcane.iris.builtin.terrain`, and +`postProcessing`, `postProcessingSlabs`, `postProcessingWalls` (booleans) in `art.arcane.iris.builtin.post`. A key a pack leaves out has the +default Iris always had (one grass layer, no slab or wall, stone and water, post processing on). `ResolvedLayer` resolves one layer's blocks and noise +for a pack, `BiomeLayers`, the world's state, keeps them and stacks a biome's layers into the blocks of a column, and `TerrainPalettes` is the world's +rock and fluid as a block for every column; the terrain, cave, floating and post stages ask them. The slope limit of a layer, a decorator and an +object placement is the one `SlopeClip`. + Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` (biome; a list) and `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest). The feature ids (`iris:deposit`, `iris:decorant`, `iris:structure`) stay the modules' identity in the stage graph and logs. A key is unique diff --git a/source-patterns.txt b/source-patterns.txt index 31bac204e..c42d04a72 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -1,5 +1,6 @@ art/arcane/iris/engine/actuator/** art/arcane/iris/engine/decorator/** +art/arcane/iris/engine/terrain/** art/arcane/iris/engine/modifier/** art/arcane/iris/engine/mantle/components/** art/arcane/iris/engine/object/** diff --git a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java index 891a7778b..db788c086 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java @@ -18,6 +18,7 @@ package art.arcane.iris.builtin.decorant; +import art.arcane.iris.builtin.prepare.SlopeClip; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; @@ -60,7 +61,7 @@ public final class Decorator { private List blacklist; @Desc("The slope at which this decorator can be placed. Range from 0 to 10 by default. Calculated from a 3-block radius from the center of the decorator placement.") - private DecoratorSlope slopeCondition = new DecoratorSlope(); + private SlopeClip slopeCondition = new SlopeClip(); @Desc("If stackMax is set to true, use this to limit its max height for large caverns") private int absoluteMaxStack = 30; @@ -143,8 +144,8 @@ public final class Decorator { return blacklist != null; } - public DecoratorSlope slopeCondition() { - return slopeCondition == null ? new DecoratorSlope() : slopeCondition; + public SlopeClip slopeCondition() { + return slopeCondition == null ? new SlopeClip() : slopeCondition; } public int absoluteMaxStack() { diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java b/src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java deleted file mode 100644 index f7ea80716..000000000 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecoratorSlope.java +++ /dev/null @@ -1,64 +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.builtin.decorant; - -import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; - -/** The terrain slopes a decorator may be placed on, as packs write it in a decorator's {@code slopeCondition}. */ -@Desc("Limits placement to a minimum and maximum terrain slope") -public final class DecoratorSlope { - private static final double UNLIMITED_MINIMUM = 0; - private static final double UNLIMITED_MAXIMUM = 10; - - @MinNumber(0) - @MaxNumber(1024) - @Desc("The minimum slope for placement") - private double minimumSlope = UNLIMITED_MINIMUM; - - @MinNumber(0) - @MaxNumber(1024) - @Desc("The maximum slope for placement") - private double maximumSlope = UNLIMITED_MAXIMUM; - - public DecoratorSlope() { - } - - public double minimumSlope() { - return minimumSlope; - } - - public double maximumSlope() { - return maximumSlope; - } - - /** Whether every slope passes: the limits are the defaults, or looser. */ - public boolean isDefault() { - return minimumSlope <= UNLIMITED_MINIMUM && maximumSlope >= UNLIMITED_MAXIMUM; - } - - public boolean isValid(double slope) { - if (isDefault()) { - return true; - } - - return !(minimumSlope > slope) && !(maximumSlope < slope); - } -} diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java index 608be30c7..efd8dd462 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java @@ -19,7 +19,7 @@ package art.arcane.iris.builtin.floating; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; +import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; @@ -149,7 +149,7 @@ public final class FloatingChildBiome { @MinItems(1) @Desc("Custom palette layers used near the underside when bottomPaletteMode=CUSTOM. The layer format is the same as normal biome layers.") - private List bottomPalette = List.of(); + private List bottomPalette = List.of(); @MinNumber(1) @MaxNumber(512) @@ -315,7 +315,7 @@ public final class FloatingChildBiome { return bottomPaletteMode == null ? FloatingBottomPaletteMode.DEPTH : bottomPaletteMode; } - public List bottomPalette() { + public List bottomPalette() { return bottomPalette == null ? List.of() : Collections.unmodifiableList(bottomPalette); } diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java new file mode 100644 index 000000000..ceb2f1442 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java @@ -0,0 +1,44 @@ +/* + * 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.builtin.post; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * Whether a dimension is post processed, written as {@code "postProcessing": true}. Iris has never read this flag: surface smoothing runs + * whatever it says, so it is declared to keep the key valid in packs. + */ +@Desc("Use post processing or not") +@Feature(id = "iris:post/enabled", name = "Post processing", key = "postProcessing", root = "enabled", targets = Target.DIMENSION) +public final class PostProcessingSettings implements IrisFeature { + public static final boolean DEFAULT_ENABLED = true; + + @Desc("Use post processing or not") + private boolean enabled = DEFAULT_ENABLED; + + public PostProcessingSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java new file mode 100644 index 000000000..a6bffc932 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.post; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * Whether post processing adds slabs on steps in a dimension, written as {@code "postProcessingSlabs": false}. A dimension without the key adds them. + */ +@Desc("Add slabs in post processing") +@Feature(id = "iris:post/slabs", name = "Post processing slabs", key = "postProcessingSlabs", root = "enabled", targets = Target.DIMENSION) +public final class PostProcessingSlabsSettings implements IrisFeature { + public static final boolean DEFAULT_ENABLED = true; + + @Desc("Add slabs in post processing") + private boolean enabled = DEFAULT_ENABLED; + + public PostProcessingSlabsSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java b/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java new file mode 100644 index 000000000..f49e5e6a7 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.post; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * Whether post processing paints walls on steep faces in a dimension, written as {@code "postProcessingWalls": false}. A dimension without the key paints them. + */ +@Desc("Add painted walls in post processing") +@Feature(id = "iris:post/walls", name = "Post processing walls", key = "postProcessingWalls", root = "enabled", targets = Target.DIMENSION) +public final class PostProcessingWallsSettings implements IrisFeature { + public static final boolean DEFAULT_ENABLED = true; + + @Desc("Add painted walls in post processing") + private boolean enabled = DEFAULT_ENABLED; + + public PostProcessingWallsSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java b/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java index 9d2030c1d..c5686d1c6 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java @@ -23,7 +23,7 @@ import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; import com.volmit.config.Snippet; -/** The terrain slopes a placement or decorator may sit on, written as its {@code slopeCondition}. */ +/** The terrain slopes an object placement, a decorator or a terrain layer may sit on, written as its {@code slopeCondition}. */ @Snippet("slope-clip") @Desc("Limits placement to a minimum and maximum terrain slope") public final class SlopeClip { diff --git a/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java new file mode 100644 index 000000000..e8ce22b91 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The layers of material on the ceilings of caves in a biome, written as {@code "caveCeilingLayers": [...]}, the list of layers. + */ +@Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") +@Feature(id = "iris:terrain/cave-ceiling-layers", name = "Cave ceiling layers", key = "caveCeilingLayers", root = "layers", targets = Target.BIOME) +public final class CaveCeilingLayersSettings implements IrisFeature { + @Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") + private List layers = List.of(); + + public CaveCeilingLayersSettings() { + } + + public List layers() { + return layers == null ? List.of() : layers; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java new file mode 100644 index 000000000..3dbaef879 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The blocks that fill ocean columns and cave aquifers of a dimension, written as {@code "fluidPalette": {...}}, a palette. A dimension without the key is water. + */ +@Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") +@Feature(id = "iris:terrain/fluid-palette", name = "Fluid palette", key = "fluidPalette", root = "palette", targets = Target.DIMENSION) +public final class FluidPaletteSettings implements IrisFeature { + private static final String DEFAULT_BLOCK = "water"; + + @Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") + private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); + + public FluidPaletteSettings() { + } + + public PaletteSpec palette() { + return palette == null ? PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))) : palette; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java new file mode 100644 index 000000000..02f2ba399 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java @@ -0,0 +1,44 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The layers of material a biome is made of below its surface, written as {@code "layers": [...]}, the list of layers. A biome + * that declares none gets one layer of grass, so the settings class default is what a biome without the key has. + */ +@Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") +@Feature(id = "iris:terrain/layers", name = "Layers", key = "layers", root = "layers", targets = Target.BIOME) +public final class LayersSettings implements IrisFeature { + @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") + private List layers = List.of(new PaletteLayer()); + + public LayersSettings() { + } + + public List layers() { + return layers == null ? List.of() : layers; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java new file mode 100644 index 000000000..9b18cf7f1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java @@ -0,0 +1,41 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** How many layers a locked biome iterates below the surface, written as {@code "lockLayersMax": 7}. A biome without the key iterates seven. */ +@Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") +@Feature(id = "iris:terrain/lock-layers-max", name = "Lock layers max", key = "lockLayersMax", root = "layers", targets = Target.BIOME) +public final class LockLayersMaxSettings implements IrisFeature { + public static final int DEFAULT_LAYERS = 7; + + @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") + private int layers = DEFAULT_LAYERS; + + public LockLayersMaxSettings() { + } + + public int layers() { + return layers; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java new file mode 100644 index 000000000..a8a98063c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java @@ -0,0 +1,39 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a biome's layers are locked to its highest possible height, written as {@code "lockLayers": true}. A biome without the key is not locked. */ +@Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") +@Feature(id = "iris:terrain/lock-layers", name = "Lock layers", key = "lockLayers", root = "locked", targets = Target.BIOME) +public final class LockLayersSettings implements IrisFeature { + @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") + private boolean locked = false; + + public LockLayersSettings() { + } + + public boolean locked() { + return locked; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java b/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java new file mode 100644 index 000000000..a6d68d388 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java @@ -0,0 +1,103 @@ +/* + * 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.builtin.terrain; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.List; + +/** + * One layer of surface or subsurface material of a biome, as packs write it in the biome's layers, sea layers, cave + * ceiling layers, slab and wall, in a floating island's bottom palette or under {@code snippet/biome-palette/}. A value of + * IrisApi types only; the terrain module resolves the blocks and builds the noise. + */ +@Snippet("biome-palette") +@Desc("A layer of surface / subsurface material in biomes") +public final class PaletteLayer { + private static final String STATIC_NOISE = "STATIC"; + private static final String DEFAULT_BLOCK = "grass_block"; + + @Desc("The style of noise") + private NoiseStyle style = NoiseStyle.of(STATIC_NOISE); + + @MinNumber(0) + @MaxNumber(2032) + @Desc("The min thickness of this layer") + private int minHeight = 1; + + @MinNumber(1) + @MaxNumber(2032) + @Desc("The max thickness of this layer") + private int maxHeight = 1; + + @Desc("If set, this layer only shows where the terrain slope is within these bounds; outside them the layer is skipped entirely. Thickness is not scaled by slope.") + private SlopeClip slopeCondition = new SlopeClip(); + + @MinNumber(0.0001) + @Desc("The terrain zoom mostly for zooming in on a wispy palette") + private double zoom = 5; + + @Required + @MinItems(1) + @Desc("The palette of blocks to be used in this layer") + private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); + + /** A layer with every option at its default, as packs get it from {@code {}}. */ + public PaletteLayer() { + } + + /** A layer with the default options and no block to place, which is what a biome without a slab or wall has. */ + public static PaletteLayer withoutBlocks() { + PaletteLayer layer = new PaletteLayer(); + layer.palette = List.of(); + return layer; + } + + public NoiseStyle style() { + return style == null ? NoiseStyle.of(STATIC_NOISE) : style; + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public SlopeClip slopeCondition() { + return slopeCondition == null ? new SlopeClip() : slopeCondition; + } + + public double zoom() { + return zoom; + } + + public List palette() { + return palette == null ? List.of() : palette; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java new file mode 100644 index 000000000..786c25326 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The blocks that fill terrain below the layers of a dimension, written as {@code "rockPalette": {...}}, a palette. A dimension without the key is stone. + */ +@Desc("The palette of blocks for 'stone'") +@Feature(id = "iris:terrain/rock-palette", name = "Rock palette", key = "rockPalette", root = "palette", targets = Target.DIMENSION) +public final class RockPaletteSettings implements IrisFeature { + private static final String DEFAULT_BLOCK = "stone"; + + @Desc("The palette of blocks for 'stone'") + private PaletteSpec palette = PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))); + + public RockPaletteSettings() { + } + + public PaletteSpec palette() { + return palette == null ? PaletteSpec.of(List.of(BlockSpec.of(DEFAULT_BLOCK))) : palette; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java new file mode 100644 index 000000000..d6693e572 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +import java.util.List; + +/** + * The layers of material filling the water column of a sea biome, written as {@code "seaLayers": [...]}, the list of layers. + */ +@Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") +@Feature(id = "iris:terrain/sea-layers", name = "Sea layers", key = "seaLayers", root = "layers", targets = Target.BIOME) +public final class SeaLayersSettings implements IrisFeature { + @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") + private List layers = List.of(); + + public SeaLayersSettings() { + } + + public List layers() { + return layers == null ? List.of() : layers; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java new file mode 100644 index 000000000..a9f1d9f0d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java @@ -0,0 +1,41 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * The slab post processing places on steps in a biome, written as {@code "slab": {...}}, one layer. A biome without the key has no slab. + */ +@Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") +@Feature(id = "iris:terrain/slab", name = "Slab", key = "slab", root = "layer", targets = Target.BIOME) +public final class SlabSettings implements IrisFeature { + @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") + private PaletteLayer layer = PaletteLayer.withoutBlocks(); + + public SlabSettings() { + } + + public PaletteLayer layer() { + return layer == null ? PaletteLayer.withoutBlocks() : layer; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java new file mode 100644 index 000000000..4c700b1e4 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java @@ -0,0 +1,42 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** + * The wall post processing paints on steep faces, and caves paint on their walls, in a biome, written as {@code "wall": {...}}, one layer. + * A biome without the key has no wall. + */ +@Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") +@Feature(id = "iris:terrain/wall", name = "Wall", key = "wall", root = "layer", targets = Target.BIOME) +public final class WallSettings implements IrisFeature { + @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") + private PaletteLayer layer = PaletteLayer.withoutBlocks(); + + public WallSettings() { + } + + public PaletteLayer layer() { + return layer == null ? PaletteLayer.withoutBlocks() : layer; + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 7926c0357..e0068796d 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -19,6 +19,15 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.FluidPaletteSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; +import art.arcane.iris.builtin.terrain.LockLayersSettings; +import art.arcane.iris.builtin.terrain.RockPaletteSettings; +import art.arcane.iris.builtin.terrain.SeaLayersSettings; +import art.arcane.iris.builtin.terrain.SlabSettings; +import art.arcane.iris.builtin.terrain.WallSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisChunk; import art.arcane.iris.core.modules.IrisPackWorld; @@ -30,6 +39,8 @@ import art.arcane.iris.engine.object.terrain.deposit.IrisOreGeneratorBounds; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.TerrainPalettes; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.context.ChunkContext; @@ -51,7 +62,7 @@ import com.volmit.world.PackWorld; * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up * to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and * biome replacing blocks on the way and the upper dimension's ground filled in from the top. The ore generators' noise - * is built ahead of generation, in {@link #warmUp}. + * and the rock and fluid palettes' noise are built ahead of generation, in {@link #warmUp}. */ public final class TerrainModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @@ -63,12 +74,23 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { @Override public void register(FeatureRegistry registry) { + registry.registerSettings(LayersSettings.class); + registry.registerSettings(SeaLayersSettings.class); + registry.registerSettings(CaveCeilingLayersSettings.class); + registry.registerSettings(SlabSettings.class); + registry.registerSettings(WallSettings.class); + registry.registerSettings(LockLayersSettings.class); + registry.registerSettings(LockLayersMaxSettings.class); + registry.registerSettings(RockPaletteSettings.class); + registry.registerSettings(FluidPaletteSettings.class); registry.registerLifecycle(this); } @Override public void warmUp(PackWorld world) { - new OreWarmUp(IrisPackWorld.of(world).engine()).warm(); + Engine engine = IrisPackWorld.of(world).engine(); + TerrainPalettes.of(engine).warm(); + new OreWarmUp(engine).warm(); } @Override @@ -86,10 +108,18 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { private static final PlatformBlockState BEDROCK = B.getState("BEDROCK"); private final Engine engine; + private final TerrainPalettes palettes; + private final BiomeLayers layers; private final RNG rng; TerrainShaper(Engine engine) { + this(engine, TerrainPalettes.of(engine), BiomeLayers.of(engine)); + } + + TerrainShaper(Engine engine, TerrainPalettes palettes, BiomeLayers layers) { this.engine = engine; + this.palettes = palettes; + this.layers = layers; this.rng = new RNG(engine.getSeedManager().getTerrain()); } @@ -118,8 +148,6 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { boolean hideOres = dimension.isHideOresForHiddenOre(); ChunkedDataCache biomeCache = context.getBiome(); ChunkedDataCache regionCache = context.getRegion(); - ChunkedDataCache fluidCache = context.getFluid(); - ChunkedDataCache rockCache = context.getRock(); int realX = xf + x; UpperDimensionContext upperContext = engine.getUpperContext(); // Dimension-level ore lookups are chunk-invariant; resolving them per column paid @@ -140,8 +168,8 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { } int topY = Math.min(hf, chunkHeight - 1); - PlatformBlockState fluid = fluidCache.get(xf, zf); - PlatformBlockState rock = rockCache.get(xf, zf); + PlatformBlockState fluid = palettes.fluidAt(realX, realZ); + PlatformBlockState rock = palettes.rockAt(realX, realZ); PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ); KList biomeSurfaceOres = hideOres ? null : biome.getSurfaceOreGenerators(); KList regionSurfaceOres = hideOres ? null : region.getSurfaceOreGenerators(); @@ -182,7 +210,7 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { if (i > he && i <= hf) { int fdepth = hf - i; if (fblocks == null) { - fblocks = biome.generateSeaLayers(realX, realZ, localRng, hf - he, data); + fblocks = layers.generateSeaLayers(biome, realX, realZ, localRng, hf - he, data); } if (fblocks.hasIndex(fdepth)) { @@ -200,7 +228,7 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { continue; } if (blocks == null) { - blocks = biome.generateLayers(dimension, realX, realZ, localRng, he, he, data, complex); + blocks = layers.generateLayers(biome, dimension, realX, realZ, localRng, he, he, data, complex); } if (blocks.hasIndex(depth)) { @@ -235,11 +263,11 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { if (upperSurfaceY < chunkHeight - 1) { IrisBiome upperBiome = upperContext.getUpperBiome(realX, realZ); - PlatformBlockState upperRock = upperContext.getRockBlock(realX, realZ); + PlatformBlockState upperRock = palettes.upperRockAt(upperContext, realX, realZ); PlatformBlockState upperMappedSurface = upperContext.getSurfaceBlock(realX, realZ); int upperThickness = chunkHeight - 1 - upperSurfaceY; KList upperBlocks = upperBiome != null - ? upperBiome.generateLayers(upperContext.getDimension(), + ? layers.generateLayers(upperBiome, upperContext.getDimension(), realX, realZ, localRng, upperThickness, upperThickness, upperContext.getData(), complex) : null; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 2660dc3f2..9ece76776 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -23,6 +23,7 @@ import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.engine.terrain.TerrainPalettes; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; @@ -466,7 +467,7 @@ public class CaveCarving { private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights); - fillFieldFluidPresence(complex.getFluidStream(), startX, startZ, blendScratch.fieldHasFluid); + fillFieldFluidPresence(TerrainPalettes.of(engine), startX, startZ, blendScratch.fieldHasFluid); fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions); fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes); fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes); @@ -490,11 +491,11 @@ public class CaveCarving { } } - private void fillFieldFluidPresence(ProceduralStream stream, int startX, int startZ, boolean[] target) { + private void fillFieldFluidPresence(TerrainPalettes palettes, int startX, int startZ, boolean[] target) { for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { int worldX = startX + fieldX; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(stream.get(worldX, startZ + fieldZ)); + target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(palettes.fluidAt(worldX, startZ + fieldZ)); } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 15242fee5..9ecd42df6 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -21,6 +21,8 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.TerrainPalettes; import art.arcane.iris.engine.decorator.IrisCeilingDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; @@ -66,6 +68,8 @@ public class CaveApplying { private final PlatformBlockState AIR = B.getState("CAVE_AIR"); private final PlatformBlockState LAVA = B.getState("LAVA"); private final BiomeDecorators decorators; + private final BiomeLayers layers; + private final TerrainPalettes palettes; private final IrisSurfaceDecorator surfaceDecorator; private final IrisCeilingDecorator ceilingDecorator; @@ -73,6 +77,8 @@ public class CaveApplying { this.engine = engine; rng = new RNG(engine.getSeedManager().getCarve()); decorators = BiomeDecorators.of(engine); + layers = BiomeLayers.of(engine); + palettes = TerrainPalettes.of(engine); surfaceDecorator = new IrisSurfaceDecorator(engine); ceilingDecorator = new IrisCeilingDecorator(engine); } @@ -151,7 +157,7 @@ public class CaveApplying { if (explicitCarveIntent) { // Only a fluid cavern consumes the fluid sample, and on the maintenance path that // sample is a full procedural stream evaluation, so never take it per voxel. - PlatformBlockState fluid = isFluidIntent(cavern) ? context.getFluid().get(rx, rz) : null; + PlatformBlockState fluid = isFluidIntent(cavern) ? palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR)); } else if (usesDefaultLava(caveLavaHeight, yy)) { output.setRaw(rx, yy, rz, LAVA); @@ -178,7 +184,7 @@ public class CaveApplying { : resolveCustomBiome(customBiomeCache, customBiome); if (biome != null) { - PlatformBlockState data = biome.getWall().get(rng, worldX, yy, worldZ, engine.getData()); + PlatformBlockState data = layers.wall(biome, engine.getData()).get(rng, worldX, yy, worldZ); int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { @@ -516,7 +522,7 @@ public class CaveApplying { } if (floorBiome != null) { - KList floorLayers = floorBiome.generateLayers( + KList floorLayers = layers.generateLayers(floorBiome, engine.getDimension(), worldX, worldZ, rng, 3, zoneFloor, engine.getData(), engine.getComplex()); for (int i = 0; i < zoneFloor - 1; i++) { if (!floorLayers.hasIndex(i)) { @@ -541,7 +547,7 @@ public class CaveApplying { if (ceilingBiome != null) { int worldMaxY = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - KList ceilingLayers = ceilingBiome.generateCeilingLayers( + KList ceilingLayers = layers.generateCeilingLayers(ceilingBiome, engine.getDimension(), worldX, worldZ, rng, 3, zoneCeiling, engine.getData(), engine.getComplex()); for (int i = 0; i < ceilingLayers.size(); i++) { int ceilingY = zoneCeiling + i + 1; @@ -603,7 +609,7 @@ public class CaveApplying { } if (floorBiome != null) { - KList floorBlocks = floorBiome.generateLayers(engine.getDimension(), xx, zz, rng, 3, zone.floor, engine.getData(), engine.getComplex()); + KList floorBlocks = layers.generateLayers(floorBiome, engine.getDimension(), xx, zz, rng, 3, zone.floor, engine.getData(), engine.getComplex()); for (int i = 0; i < zone.floor - 1; i++) { if (!floorBlocks.hasIndex(i)) { break; @@ -623,7 +629,7 @@ public class CaveApplying { } if (ceilingBiome != null) { - KList ceilingBlocks = ceilingBiome.generateCeilingLayers(engine.getDimension(), xx, zz, rng, 3, zone.ceiling, engine.getData(), engine.getComplex()); + KList ceilingBlocks = layers.generateCeilingLayers(ceilingBiome, engine.getDimension(), xx, zz, rng, 3, zone.ceiling, engine.getData(), engine.getComplex()); for (int i = 0; i < ceilingBlocks.size(); i++) { int cy = zone.ceiling + i + 1; if (cy >= maxY) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 70ee4b567..90f51a6e0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -22,6 +22,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; @@ -32,7 +33,8 @@ import art.arcane.iris.engine.framework.EngineDecorator; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.ResolvedLayer; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.spi.IrisLogging; @@ -64,15 +66,16 @@ public class FloatingIslands { private final Engine engine; private final RNG rng; private final EngineDecorator seaSurfaceDecorator; + private final BiomeLayers biomeLayers; - private static KList generateBottomPaletteLayers(ResolvedFloatingChild entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { + private KList generateBottomPaletteLayers(ResolvedFloatingChild entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette() == null || entry.settings().bottomPalette().isEmpty()) { return null; } return generatePaletteLayers(dimension, new KList<>(entry.settings().bottomPalette()), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex); } - private static KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) { + private KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) { KList generated = new KList<>(); if (layers == null || layers.isEmpty() || maxDepth <= 0) { return generated; @@ -80,13 +83,13 @@ public class FloatingIslands { int generatorSeed = 7235; for (int i = 0; i < layers.size(); i++) { - IrisBiomePaletteLayer layer = layers.get(i); - CNG heightGenerator = layer.getHeightGenerator(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed), data); + ResolvedLayer layer = biomeLayers.resolve(layers.get(i), data); + CNG heightGenerator = layer.heightNoise(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed)); if (heightGenerator == null) { continue; } - double layerDepth = heightGenerator.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / layer.getZoom(), wz / layer.getZoom()); - SlopeClip slopeClip = layer.getSlopeCondition(); + double layerDepth = heightGenerator.fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); + SlopeClip slopeClip = layer.slopeCondition(); if (slopeClip != null && !slopeClip.isDefault() && complex != null && !slopeClip.isValid(complex.getSlopeStream().get(wx, wz))) { layerDepth = 0; @@ -102,7 +105,7 @@ public class FloatingIslands { } try { - generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.getZoom(), j, (wz - j) / layer.getZoom(), data)); + generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom())); } catch (Throwable e) { IrisLogging.reportError(e); } @@ -183,9 +186,9 @@ public class FloatingIslands { IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); int entrySeed = entry == null || entry.settings().biome() == null ? 0 : entry.settings().biome().hashCode(); RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed)); - KList topBlocks = target == null ? null : target.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); + KList topBlocks = target == null ? null : biomeLayers.generateLayers(target, dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); if (topBlocks == null || topBlocks.isEmpty()) { - topBlocks = parent.generateLayers(dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); + topBlocks = biomeLayers.generateLayers(parent, dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); } KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex); return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone")); @@ -207,6 +210,7 @@ public class FloatingIslands { this.engine = engine; rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); + biomeLayers = BiomeLayers.of(engine); } /** Fills the islands' solids into the chunk whose first block is {@code x}, {@code z}. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index a39f8546f..98b595594 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -19,7 +19,11 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.post.PostProcessingSettings; +import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; +import art.arcane.iris.builtin.post.PostProcessingWallsSettings; import art.arcane.iris.core.modules.IrisChunk; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.ChunkStageContext; @@ -37,6 +41,13 @@ public final class PostModule implements IrisModule { return ModuleInfo.of("iris:post", "Post-processing", VERSION); } + @Override + public void register(FeatureRegistry registry) { + registry.registerSettings(PostProcessingSettings.class); + registry.registerSettings(PostProcessingSlabsSettings.class); + registry.registerSettings(PostProcessingWallsSettings.class); + } + @Override public void install(StageGraph graph) { graph.define(IrisStages.Post.SMOOTH).requires(IrisStages.Carve.APPLY).run(PostModule::smooth); diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 6b15edda1..fad2f2b66 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -18,12 +18,16 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; +import art.arcane.iris.builtin.post.PostProcessingWallsSettings; import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.terrain.BiomeLayers; +import art.arcane.iris.engine.terrain.ResolvedLayer; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.hunk.Hunk; @@ -42,10 +46,12 @@ public class SurfaceSmoothing { } private final Engine engine; + private final BiomeLayers layers; private final RNG rng; public SurfaceSmoothing(Engine engine) { this.engine = engine; + layers = BiomeLayers.of(engine); rng = new RNG(engine.getSeedManager().getPost()); } @@ -60,8 +66,10 @@ public class SurfaceSmoothing { int planeWidth = width + 2; int[] heights = heightPlane(x, z, width, depth, planeWidth); IrisDimension dimension = engine.getDimension(); - boolean walls = dimension.isPostProcessingWalls(); - boolean slabs = dimension.isPostProcessingSlabs(); + boolean walls = dimension.getModuleSettings().find(PostProcessingWallsSettings.class) + .map(PostProcessingWallsSettings::enabled).orElse(PostProcessingWallsSettings.DEFAULT_ENABLED); + boolean slabs = dimension.getModuleSettings().find(PostProcessingSlabsSettings.class) + .map(PostProcessingSlabsSettings::enabled).orElse(PostProcessingSlabsSettings.DEFAULT_ENABLED); int fluidHeight = dimension.getFluidHeight(); for (int i = 0; i < width; i++) { for (int j = 0; j < depth; j++) { @@ -176,13 +184,14 @@ public class SurfaceSmoothing { IrisBiome biome = context.getBiome().get(currentPostX, currentPostZ); if (walls) { - if (!biome.getWall().getPalette().isEmpty()) { + ResolvedLayer wall = layers.wall(biome, engine.getData()); + if (wall.hasPalette()) { if (ha < h - 2 || hb < h - 2 || hc < h - 2 || hd < h - 2) { boolean brokeGround = false; int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); for (int i = h; i > h - max; i--) { - PlatformBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, engine.getData()); + PlatformBlockState d = wall.get(rng, x + i, i + h, z + i); if (d != null) { if (isAirOrWater(x, i, z, originX, originZ, currentData)) { @@ -210,8 +219,9 @@ public class SurfaceSmoothing { || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, originX, originZ, currentData))) //@done { - SlopeClip sc = biome.getSlab().getSlopeCondition(); - PlatformBlockState d = sc.isValid(engine.getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, engine.getData()) : null; + ResolvedLayer slab = layers.slab(biome, engine.getData()); + SlopeClip sc = slab.slopeCondition(); + PlatformBlockState d = sc.isValid(engine.getComplex().getSlopeStream().get(x, z)) ? slab.get(rng, x, h, z) : null; if (d != null) { boolean cancel = B.isAir(d); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index e3c199da8..35d1b7cb6 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -24,9 +24,9 @@ import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.terrain.TerrainPalettes; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.noise.SimplexNoise; @@ -82,7 +82,7 @@ public final class VacuumModule implements IrisModule { private final IrisPlacement placement; private final PreparedPlacement prepared; private final PlacementWorld world; - private final IrisComplex complex; + private final TerrainPalettes palettes; private final int radius; private final int step; private final double falloff; @@ -98,7 +98,7 @@ public final class VacuumModule implements IrisModule { this.placement = IrisPlacement.current(); this.prepared = prepared; this.world = new PlacementWorld(context.access(), placement.states()); - this.complex = engine.getComplex(); + this.palettes = engine.getComplex() == null ? null : TerrainPalettes.of(engine); VacuumSettings settings = prepared.config().getVacuumSettings(); this.radius = IrisObjectVacuum.resolveRadius(vacuum, settings); this.step = vacuum.columnStepBlocks(); @@ -161,7 +161,7 @@ public final class VacuumModule implements IrisModule { } private void raise(int x, int z, int fromY, int toY) { - PlatformBlockState fill = complex != null ? complex.getRockStream().get(x, z) : null; + PlatformBlockState fill = palettes != null ? palettes.rockAt(x, z) : null; if (B.isAir(fill)) { fill = IrisObject.States.STONE; } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java deleted file mode 100644 index e9b04809a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomeLayerGenerator.java +++ /dev/null @@ -1,360 +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.builtin.prepare.SlopeClip; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.biome.IrisBiomeGeneratorLink; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -/** - * Layer (block palette) generation for {@link IrisBiome}. IrisBiome is Gson deserialized from pack - * JSON, so its fields stay put and only the behavior lives here. - */ -public final class IrisBiomeLayerGenerator { - private static final class States { - private static final PlatformBlockState BARRIER = B.getState("BARRIER"); - } - - private IrisBiomeLayerGenerator() { - } - - public static KList generateLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - if (biome.isLockLayers()) { - return generateLockedLayers(biome, wx, wz, random, maxDepth, height, rdata, complex); - } - - KList data = new KList<>(); - - if (maxDepth <= 0) { - return data; - } - - KList layers = biome.getLayers(); - int layerCount = layers.size(); - - if (layerCount <= 0) { - return data; - } - - KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); - - for (int i = 0; i < layerCount; i++) { - IrisBiomePaletteLayer layer = layers.get(i); - double zoom = layer.getZoom(); - CNG hgen = heightGenerators.get(i); - double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); - - SlopeClip sc = layer.getSlopeCondition(); - - if (!sc.isDefault()) { - if (!sc.isValid(complex.getSlopeStream().get(wx, wz))) { - d = 0; - } - } - - if (d <= 0) { - continue; - } - - for (int j = 0; j < d; j++) { - if (data.size() >= maxDepth) { - break; - } - - try { - data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); - } catch (Throwable e) { - IrisLogging.reportError(e); - } - } - - if (data.size() >= maxDepth) { - break; - } - - if (dim.isExplodeBiomePalettes()) { - for (int j = 0; j < dim.getExplodeBiomePaletteSize(); j++) { - data.add(States.BARRIER); - - if (data.size() >= maxDepth) { - break; - } - } - } - } - - return data; - } - - public static KList generateCeilingLayers(IrisBiome biome, IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - KList data = new KList<>(); - - if (maxDepth <= 0) { - return data; - } - - KList ceilingLayers = biome.getCaveCeilingLayers(); - int layerCount = ceilingLayers.size(); - - if (layerCount <= 0) { - return data; - } - - KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); - // Ceiling layers reuse the surface-layer height generators, so entries beyond layers.size() have no generator; skip them. - int usableLayers = Math.min(layerCount, heightGenerators.size()); - - for (int i = 0; i < usableLayers; i++) { - IrisBiomePaletteLayer layer = ceilingLayers.get(i); - double zoom = layer.getZoom(); - CNG hgen = heightGenerators.get(i); - double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); - - if (d <= 0) { - continue; - } - - for (int j = 0; j < d; j++) { - if (data.size() >= maxDepth) { - break; - } - - try { - data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); - } catch (Throwable e) { - IrisLogging.reportError(e); - } - } - - if (data.size() >= maxDepth) { - break; - } - - if (dim.isExplodeBiomePalettes()) { - for (int j = 0; j < dim.getExplodeBiomePaletteSize(); j++) { - data.add(States.BARRIER); - - if (data.size() >= maxDepth) { - break; - } - } - } - } - - return data; - } - - public static KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { - KList data = new KList<>(); - KList real = new KList<>(); - int maxDepth = Math.min(maxDepthf, biome.getLockLayersMax()); - if (maxDepth <= 0) { - return data; - } - - KList layers = biome.getLayers(); - int layerCount = layers.size(); - - if (layerCount > 0) { - KList heightGenerators = getLayerHeightGenerators(biome, random, rdata); - - for (int i = 0; i < layerCount; i++) { - IrisBiomePaletteLayer layer = layers.get(i); - double zoom = layer.getZoom(); - CNG hgen = heightGenerators.get(i); - double d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); - - SlopeClip sc = layer.getSlopeCondition(); - - if (!sc.isDefault()) { - if (!sc.isValid(complex.getSlopeStream().get(wx, wz))) { - d = 0; - } - } - - if (d <= 0) { - continue; - } - - for (int j = 0; j < d; j++) { - try { - data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); - } catch (Throwable e) { - IrisLogging.reportError(e); - } - } - } - } - - if (data.isEmpty()) { - return real; - } - - for (int i = 0; i < maxDepth; i++) { - int offset = (512 - height) - i; - int index = offset % data.size(); - real.add(data.get(Math.max(index, 0))); - } - - return real; - } - - public static KList generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData rdata) { - KList data = new KList<>(); - - KList seaLayers = biome.getSeaLayers(); - int layerCount = seaLayers.size(); - - if (layerCount <= 0) { - return data; - } - - KList heightGenerators = getLayerSeaHeightGenerators(biome, random, rdata); - - for (int i = 0; i < layerCount; i++) { - IrisBiomePaletteLayer layer = seaLayers.get(i); - double zoom = layer.getZoom(); - CNG hgen = heightGenerators.get(i); - int d = hgen.fit(layer.getMinHeight(), layer.getMaxHeight(), wx / zoom, wz / zoom); - - if (d < 0) { - continue; - } - - for (int j = 0; j < d; j++) { - if (data.size() >= maxDepth) { - break; - } - - try { - data.add(layer.get(random, i + j, (wx + j) / zoom, j, (wz - j) / zoom, rdata)); - } catch (Throwable e) { - IrisLogging.reportError(e); - } - } - - if (data.size() >= maxDepth) { - break; - } - } - - return data; - } - - public static KList getLayerHeightGenerators(IrisBiome biome, RNG rng, IrisData rdata) { - AtomicCache> cache = biome.getLayerHeightGenerators(); - KList cached = cache.getIfPresent(); - - if (cached != null) { - return cached; - } - - return cache.aquire(() -> - { - KList layerHeightGenerators = new KList<>(); - - int m = 7235; - - for (IrisBiomePaletteLayer i : biome.getLayers()) { - layerHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), rdata)); - } - - return layerHeightGenerators; - }); - } - - public static KList getLayerSeaHeightGenerators(IrisBiome biome, RNG rng, IrisData data) { - AtomicCache> cache = biome.getLayerSeaHeightGenerators(); - KList cached = cache.getIfPresent(); - - if (cached != null) { - return cached; - } - - return cache.aquire(() -> - { - KList layerSeaHeightGenerators = new KList<>(); - - int m = 7735; - - for (IrisBiomePaletteLayer i : biome.getSeaLayers()) { - layerSeaHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), data)); - } - - return layerSeaHeightGenerators; - }); - } - - public static PlatformBlockState getSurfaceBlock(IrisBiome biome, int x, int z, RNG rng, IrisData idm) { - KList layers = biome.getLayers(); - - if (layers.isEmpty()) { - return B.getState("AIR"); - } - - return layers.get(0).get(rng, x, 0, z, idm); - } - - public static int getMaxHeight(IrisBiome biome, Engine engine) { - return biome.getMaxHeight().aquire(() -> - { - int maxHeight = 0; - - for (IrisBiomeGeneratorLink i : biome.getGenerators()) { - maxHeight += i.getMax(); - } - - return maxHeight; - }); - } - - public static int getMaxWithObjectHeight(IrisBiome biome, IrisData data, Engine engine) { - return biome.getMaxWithObjectHeight().aquire(() -> - { - int maxHeight = 0; - - for (IrisBiomeGeneratorLink i : biome.getGenerators()) { - maxHeight += i.getMax(); - } - - int gg = 0; - - for (IrisObjectPlacement i : biome.getObjects()) { - for (IrisObject j : data.getObjectLoader().loadAll(i.getPlace())) { - gg = Math.max(gg, j.getH()); - } - } - - return maxHeight + gg + 3; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java b/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java deleted file mode 100644 index 1825e7863..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/IrisBiomePaletteLayer.java +++ /dev/null @@ -1,165 +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.builtin.prepare.SlopeClip; -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -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.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.util.project.noise.CNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Snippet("biome-palette") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("A layer of surface / subsurface material in biomes") -@Data -public class IrisBiomePaletteLayer { - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); - @Desc("The style of noise") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @DependsOn({"minHeight", "maxHeight"}) - @MinNumber(0) - @MaxNumber(2032) - - @Desc("The min thickness of this layer") - private int minHeight = 1; - @DependsOn({"minHeight", "maxHeight"}) - @MinNumber(1) - @MaxNumber(2032) - - @Desc("The max thickness of this layer") - private int maxHeight = 1; - @Desc("If set, this layer only shows where the terrain slope is within these bounds; outside them the layer is skipped entirely. Thickness is not scaled by slope.") - private SlopeClip slopeCondition = new SlopeClip(); - @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("GRASS_BLOCK")); - - public CNG getHeightGenerator(RNG rng, IrisData data) { - CNG cached = heightGenerator.getIfPresent(); - - if (cached != null) { - return cached; - } - - return heightGenerator.aquire(() -> CNG.signature(rng.nextParallelRNG(minHeight * maxHeight + getBlockData(data).size()))); - } - - public PlatformBlockState get(RNG rng, double x, double y, double z, IrisData data) { - return get(rng, 0, x, y, z, data); - } - - /** - * Resolves a block for this layer without allocating a child RNG per call. The child RNG is - * only built inside the lazy layer generator initializer, using the exact same seed derivation - * as {@code parent.nextParallelRNG(signature)} followed by the generator signature. - */ - public PlatformBlockState get(RNG parent, int signature, double x, double y, double z, IrisData data) { - KList localBlockData = getBlockData(data); - - if (localBlockData.isEmpty()) { - return null; - } - - if (localBlockData.size() == 1) { - return localBlockData.get(0); - } - - double localZoom = zoom; - double scaledX = x / localZoom; - double scaledY = y / localZoom; - double scaledZ = z / localZoom; - return getLayerGenerator(parent, signature, data).fit(localBlockData, scaledX, scaledY, scaledZ); - } - - public CNG getLayerGenerator(RNG rng, IrisData data) { - return getLayerGenerator(rng, 0, data); - } - - public CNG getLayerGenerator(RNG parent, int signature, IrisData data) { - CNG cached = layerGenerator.getIfPresent(); - - if (cached != null) { - return cached; - } - - return layerGenerator.aquire(() -> - { - RNG rngx = parent.nextParallelRNG(signature).nextParallelRNG(minHeight + maxHeight + getBlockData(data).size()); - return style.create(rngx, data); - }); - } - - public KList add(String b) { - palette.add(new IrisBlockData(b)); - - return palette; - } - - public KList getBlockData(IrisData data) { - KList cached = blockData.getIfPresent(); - - if (cached != null) { - return cached; - } - - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for (IrisBlockData ix : palette) { - PlatformBlockState bx = ix.getBlockData(data); - if (bx != null) { - for (int i = 0; i < ix.getWeight(); i++) { - blockData.add(bx); - } - } - } - - return blockData; - }); - } - - public IrisBiomePaletteLayer zero() { - palette.clear(); - return this; - } -} 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 index 2be388ff5..aaca52db8 100644 --- 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 @@ -29,8 +29,6 @@ import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.terrain.IrisBiomeLayerGenerator; -import art.arcane.iris.engine.object.terrain.IrisBiomePaletteLayer; import art.arcane.iris.engine.object.terrain.deposit.IrisBiomeOres; import art.arcane.iris.engine.object.terrain.deposit.IrisDepositVariant; import art.arcane.iris.engine.object.terrain.deposit.IrisOreGenerator; @@ -78,7 +76,7 @@ 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 IrisBiomeLayerGenerator}, {@link IrisBiomeDerivatives}, {@link IrisBiomeOres}, + * {@link IrisBiomeDerivatives}, {@link IrisBiomeOres}, * {@link IrisBiomeColorRenderer} and {@link IrisBiomeGenLinks}. */ @Accessors(chain = true) @@ -106,12 +104,8 @@ public class IrisBiome extends IrisRegistrant implements IRare { @Getter(AccessLevel.NONE) @Setter(AccessLevel.NONE) private transient volatile SeededBiomeGenerator recentBiomeGenerator; - private final transient AtomicCache maxHeight = new AtomicCache<>(); - private final transient AtomicCache maxWithObjectHeight = new AtomicCache<>(); private final transient AtomicCache realCarveBiome = new AtomicCache<>(); private final transient AtomicCache> realChildren = new AtomicCache<>(); - private final transient AtomicCache> layerHeightGenerators = new AtomicCache<>(); - private final transient AtomicCache> layerSeaHeightGenerators = new AtomicCache<>(); private final transient AtomicCache> surfaceOreCache = new AtomicCache<>(); private final transient AtomicCache> undergroundOreCache = new AtomicCache<>(); private final transient AtomicCache surfaceOreBoundsCache = new AtomicCache<>(); @@ -142,10 +136,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { private KList blockDrops = new KList<>(); @Desc("Reference loot tables in this area") private IrisLootReference loot = new IrisLootReference(); - @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") - private boolean lockLayers = false; - @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") - private int lockLayersMax = 7; @Desc("Profile-driven 3D cave configuration") private CaveProfile caveProfile = new CaveProfile(); @MinNumber(1) @@ -187,20 +177,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @MaxNumber(256) @Desc("Minimum depth below terrain surface required before this cave biome can be selected.") private int caveMinDepthBelowSurface = 0; - @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") - private IrisBiomePaletteLayer slab = new IrisBiomePaletteLayer().zero(); - @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") - private IrisBiomePaletteLayer wall = new IrisBiomePaletteLayer().zero(); - @Required - @ArrayType(type = IrisBiomePaletteLayer.class) - @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") - private KList layers = new KList().qadd(new IrisBiomePaletteLayer()); - @ArrayType(type = IrisBiomePaletteLayer.class) - @Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") - private KList caveCeilingLayers = new KList<>(); - @ArrayType(type = IrisBiomePaletteLayer.class) - @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") - private KList seaLayers = new KList<>(); @ArrayType(min = 1, type = IrisObjectPlacement.class) @Desc("Objects define what schematics (iob files) iris will place in this biome") private KList objects = new KList<>(); @@ -292,6 +268,7 @@ public class IrisBiome extends IrisRegistrant implements IRare { variant.setLoader(data); variant.setLoadKey(getLoadKey()); variant.setLoadFile(getLoadFile()); + variant.setModuleSettings(getModuleSettings()); variant.inferredType = type; inferredVariants.put(type, variant); return variant; @@ -483,46 +460,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { return childrenCell.aquire(() -> getChildStyle().create(random.nextParallelRNG(sig * 2137), getLoader()).bake().scale(scale).bake()); } - public KList generateLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - return IrisBiomeLayerGenerator.generateLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex); - } - - public KList generateCeilingLayers(IrisDimension dim, double wx, double wz, RNG random, int maxDepth, int height, IrisData rdata, IrisComplex complex) { - return IrisBiomeLayerGenerator.generateCeilingLayers(this, dim, wx, wz, random, maxDepth, height, rdata, complex); - } - - public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisData rdata, IrisComplex complex) { - return IrisBiomeLayerGenerator.generateLockedLayers(this, wx, wz, random, maxDepthf, height, rdata, complex); - } - - public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisData rdata) { - return IrisBiomeLayerGenerator.generateSeaLayers(this, wx, wz, random, maxDepth, rdata); - } - - /** - * Note the arity split: {@code getMaxHeight()} is the Lombok getter for the height cache field, - * {@code getMaxHeight(Engine)} is the resolved biome height. - */ - public int getMaxHeight(Engine engine) { - return IrisBiomeLayerGenerator.getMaxHeight(this, engine); - } - - public int getMaxWithObjectHeight(IrisData data, Engine engine) { - return IrisBiomeLayerGenerator.getMaxWithObjectHeight(this, data, engine); - } - - public KList getLayerHeightGenerators(RNG rng, IrisData rdata) { - return IrisBiomeLayerGenerator.getLayerHeightGenerators(this, rng, rdata); - } - - public KList getLayerSeaHeightGenerators(RNG rng, IrisData data) { - return IrisBiomeLayerGenerator.getLayerSeaHeightGenerators(this, rng, data); - } - - public PlatformBlockState getSurfaceBlock(int x, int z, RNG rng, IrisData idm) { - return IrisBiomeLayerGenerator.getSurfaceBlock(this, x, z, rng, idm); - } - public boolean isLand() { if (inferredType == null) { return true; 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 index 44e9ce0fe..e99ff02aa 100644 --- 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 @@ -19,6 +19,7 @@ package art.arcane.iris.engine.object.world.biome; import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.terrain.BiomeLayers; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; @@ -81,7 +82,10 @@ final class IrisBiomeColorRenderer { }); } case LAYER_LOAD -> { - return biome.getCacheColorLayerLoad().aquire(() -> Color.getHSBColor(0.625f, (float) (biome.getLayers().size() / engine.getMaxBiomeLayerDensity()), 1f)); + return biome.getCacheColorLayerLoad().aquire(() -> { + BiomeLayers layers = BiomeLayers.of(engine); + return Color.getHSBColor(0.625f, (float) (BiomeLayers.layersOf(biome).size() / layers.busiestLayerCount(engine)), 1f); + }); } } 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 index 8f37e4768..591b46744 100644 --- 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 @@ -27,7 +27,6 @@ import art.arcane.iris.engine.object.image.IrisImageMapApplication; import art.arcane.iris.engine.object.image.IrisImageMapBinding; import art.arcane.iris.engine.object.loot.IrisBlockDrops; import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.IrisShapedGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; @@ -178,12 +177,6 @@ public class IrisDimension extends IrisRegistrant { private boolean decorate = true; @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") private boolean hideOresForHiddenOre = false; - @Desc("Use post processing or not") - private boolean postProcessing = true; - @Desc("Add slabs in post processing") - private boolean postProcessingSlabs = true; - @Desc("Add painted walls in post processing") - private boolean postProcessingWalls = true; @Desc("Enable or disable all carving for this dimension") private boolean carvingEnabled = true; @ArrayType(type = IrisDimensionCarvingEntry.class, min = 1) @@ -281,10 +274,6 @@ public class IrisDimension extends IrisRegistrant { @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) @Desc("Overlay additional noise on top of the interoplated terrain.") private KList overlayNoise = new KList<>(); - @Desc("The palette of blocks for 'stone'") - private IrisMaterialPalette rockPalette = new IrisMaterialPalette().qclear().qadd("stone"); - @Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") - private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("water"); @Desc("Collection of ores to be generated") @ArrayType(type = IrisOreGenerator.class, min = 1) private KList ores = new KList<>(); diff --git a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java new file mode 100644 index 000000000..7d38a6ca4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java @@ -0,0 +1,344 @@ +/* + * 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.terrain; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; +import art.arcane.iris.builtin.terrain.LockLayersSettings; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.iris.builtin.terrain.SeaLayersSettings; +import art.arcane.iris.builtin.terrain.SlabSettings; +import art.arcane.iris.builtin.terrain.WallSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisValues; +import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.noise.NoiseStyle; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the terrain module keeps for one world about the layers of its biomes: each layer made ready ({@link ResolvedLayer}) + * and the noise that sets the thickness of a biome's layers, and the blocks the layers of a biome stack up to at a column. + * A biome's layers are its {@link LayersSettings}, {@link SeaLayersSettings} and {@link CaveCeilingLayersSettings}; a biome + * that declares no layers has the one layer of grass the settings default to. + * + *

The noise of a biome's layers is built once, from the random of the first column asked for, as it always was. + */ +public final class BiomeLayers { + private static final int SURFACE_HEIGHT_SEED = 7235; + private static final int SEA_HEIGHT_SEED = 7735; + private static final int LOCKED_LAYERS_REFERENCE_HEIGHT = 512; + private static final LayersSettings DEFAULT_LAYERS = new LayersSettings(); + private static final PaletteLayer NO_LAYER = PaletteLayer.withoutBlocks(); + + private static final class States { + private static final PlatformBlockState BARRIER = B.getState("BARRIER"); + } + + private final Map resolved = new ConcurrentHashMap<>(); + private final Map>> surfaceHeights = new ConcurrentHashMap<>(); + private final Map>> seaHeights = new ConcurrentHashMap<>(); + private volatile Double busiestBiomeLayerCount; + + /** The layers of the world {@code engine} generates now. */ + public static BiomeLayers of(Engine engine) { + return engine.getGeneration().state(BiomeLayers.class, ignored -> new BiomeLayers()); + } + + /** {@code layer} ready for the pack of {@code data}; the pack of the first caller is the one kept. */ + public ResolvedLayer resolve(PaletteLayer layer, IrisData data) { + return resolved.computeIfAbsent(layer, declared -> ResolvedLayer.of(declared, data)); + } + + /** The biome's slab, which places no block when the biome declares none. */ + public ResolvedLayer slab(IrisBiome biome, IrisData data) { + PaletteLayer layer = biome.getModuleSettings().find(SlabSettings.class).map(SlabSettings::layer).orElse(NO_LAYER); + return resolve(layer, data); + } + + /** The biome's wall, which places no block when the biome declares none. */ + public ResolvedLayer wall(IrisBiome biome, IrisData data) { + PaletteLayer layer = biome.getModuleSettings().find(WallSettings.class).map(WallSettings::layer).orElse(NO_LAYER); + return resolve(layer, data); + } + + /** The layers of the biome's surface, top first. */ + public static List layersOf(IrisBiome biome) { + return surfaceSettings(biome).layers(); + } + + /** The noise style of each layer of the biome's surface, top first, as Iris's generators know them. */ + public static List layerStyles(IrisBiome biome) { + return layersOf(biome).stream().map(layer -> IrisValues.generatorStyle(layer.style()).getStyle()).toList(); + } + + /** The most layers any biome the dimension reaches has, which is what studio's layer load view compares a biome with. */ + public double busiestLayerCount(Engine engine) { + Double cached = busiestBiomeLayerCount; + if (cached != null) { + return cached; + } + + double busiest = 0D; + for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { + busiest = Math.max(busiest, layersOf(biome).size()); + } + busiestBiomeLayerCount = busiest; + return busiest; + } + + /** The blocks the biome's layers stack up to at the column, top first, at most {@code maxDepth} of them. */ + public KList generateLayers(IrisBiome biome, IrisDimension dimension, double wx, double wz, RNG random, int maxDepth, int height, IrisData data, IrisComplex complex) { + if (isLocked(biome)) { + return generateLockedLayers(biome, wx, wz, random, maxDepth, height, data, complex); + } + + KList blocks = new KList<>(); + if (maxDepth <= 0) { + return blocks; + } + + LayersSettings settings = surfaceSettings(biome); + List layers = settings.layers(); + if (layers.isEmpty()) { + return blocks; + } + + KList heightNoises = surfaceHeightNoises(settings, random, data); + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = resolve(layers.get(i), data); + double depth = layerDepth(layer, heightNoises.get(i), wx, wz, complex); + if (depth <= 0) { + continue; + } + + stackLayer(blocks, layer, i, depth, wx, wz, random, maxDepth); + if (blocks.size() >= maxDepth) { + break; + } + + separateLayers(blocks, dimension, maxDepth); + } + + return blocks; + } + + /** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code maxDepth} of them. */ + public KList generateCeilingLayers(IrisBiome biome, IrisDimension dimension, double wx, double wz, RNG random, int maxDepth, int height, IrisData data, IrisComplex complex) { + KList blocks = new KList<>(); + if (maxDepth <= 0) { + return blocks; + } + + List ceilingLayers = biome.getModuleSettings().find(CaveCeilingLayersSettings.class) + .map(CaveCeilingLayersSettings::layers).orElse(List.of()); + if (ceilingLayers.isEmpty()) { + return blocks; + } + + KList heightNoises = surfaceHeightNoises(surfaceSettings(biome), random, data); + // Ceiling layers reuse the surface-layer height noise, so entries beyond the surface layers have none; skip them. + int usableLayers = Math.min(ceilingLayers.size(), heightNoises.size()); + for (int i = 0; i < usableLayers; i++) { + ResolvedLayer layer = resolve(ceilingLayers.get(i), data); + double depth = layerThickness(layer, heightNoises.get(i), wx, wz); + if (depth <= 0) { + continue; + } + + stackLayer(blocks, layer, i, depth, wx, wz, random, maxDepth); + if (blocks.size() >= maxDepth) { + break; + } + + separateLayers(blocks, dimension, maxDepth); + } + + return blocks; + } + + /** The blocks of the biome's sea layers at the column, from the water surface down, at most {@code maxDepth} of them. */ + public KList generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData data) { + KList blocks = new KList<>(); + SeaLayersSettings settings = biome.getModuleSettings().find(SeaLayersSettings.class).orElse(null); + if (settings == null || settings.layers().isEmpty()) { + return blocks; + } + + List layers = settings.layers(); + KList heightNoises = seaHeightNoises(settings, random, data); + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = resolve(layers.get(i), data); + int depth = heightNoises.get(i).fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); + if (depth < 0) { + continue; + } + + stackLayer(blocks, layer, i, depth, wx, wz, random, maxDepth); + if (blocks.size() >= maxDepth) { + break; + } + } + + return blocks; + } + + private KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthLimit, int height, IrisData data, IrisComplex complex) { + KList stacked = new KList<>(); + KList locked = new KList<>(); + int maxDepth = Math.min(maxDepthLimit, lockedLayersMax(biome)); + if (maxDepth <= 0) { + return stacked; + } + + LayersSettings settings = surfaceSettings(biome); + List layers = settings.layers(); + if (!layers.isEmpty()) { + KList heightNoises = surfaceHeightNoises(settings, random, data); + for (int i = 0; i < layers.size(); i++) { + ResolvedLayer layer = resolve(layers.get(i), data); + double depth = layerDepth(layer, heightNoises.get(i), wx, wz, complex); + if (depth <= 0) { + continue; + } + + stackLayerUnlimited(stacked, layer, i, depth, wx, wz, random); + } + } + + if (stacked.isEmpty()) { + return locked; + } + + for (int i = 0; i < maxDepth; i++) { + int offset = (LOCKED_LAYERS_REFERENCE_HEIGHT - height) - i; + locked.add(stacked.get(Math.max(offset % stacked.size(), 0))); + } + + return locked; + } + + private void stackLayer(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random, int maxDepth) { + for (int j = 0; j < depth; j++) { + if (blocks.size() >= maxDepth) { + break; + } + + addBlock(blocks, layer, index, j, wx, wz, random); + } + } + + private void stackLayerUnlimited(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random) { + for (int j = 0; j < depth; j++) { + addBlock(blocks, layer, index, j, wx, wz, random); + } + } + + /** Adds the layer's block {@code j} blocks down; a layer that fails to pick adds nothing. */ + private void addBlock(KList blocks, ResolvedLayer layer, int index, int j, double wx, double wz, RNG random) { + double zoom = layer.zoom(); + try { + blocks.add(layer.get(random, index + j, (wx + j) / zoom, j, (wz - j) / zoom)); + } catch (Throwable e) { + IrisLogging.reportError(e); + } + } + + /** The barrier blocks a dimension puts between layers to show them apart. */ + private void separateLayers(KList blocks, IrisDimension dimension, int maxDepth) { + if (!dimension.isExplodeBiomePalettes()) { + return; + } + + for (int j = 0; j < dimension.getExplodeBiomePaletteSize(); j++) { + blocks.add(States.BARRIER); + if (blocks.size() >= maxDepth) { + break; + } + } + } + + /** How thick the layer is at the column: nothing where the slope is outside the layer's limits. */ + private double layerDepth(ResolvedLayer layer, CNG heightNoise, double wx, double wz, IrisComplex complex) { + double depth = layerThickness(layer, heightNoise, wx, wz); + SlopeClip slope = layer.slopeCondition(); + if (!slope.isDefault() && !slope.isValid(complex.getSlopeStream().get(wx, wz))) { + return 0; + } + + return depth; + } + + private double layerThickness(ResolvedLayer layer, CNG heightNoise, double wx, double wz) { + double zoom = layer.zoom(); + return heightNoise.fit(layer.minHeight(), layer.maxHeight(), wx / zoom, wz / zoom); + } + + private KList surfaceHeightNoises(LayersSettings settings, RNG rng, IrisData data) { + AtomicCache> cache = surfaceHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); + return heightNoises(cache, settings.layers(), SURFACE_HEIGHT_SEED, rng, data); + } + + private KList seaHeightNoises(SeaLayersSettings settings, RNG rng, IrisData data) { + AtomicCache> cache = seaHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); + return heightNoises(cache, settings.layers(), SEA_HEIGHT_SEED, rng, data); + } + + private KList heightNoises(AtomicCache> cache, List layers, int firstSeed, RNG rng, IrisData data) { + KList cached = cache.getIfPresent(); + if (cached != null) { + return cached; + } + + return cache.aquire(() -> { + KList noises = new KList<>(); + int seed = firstSeed; + for (PaletteLayer layer : layers) { + noises.add(resolve(layer, data).heightNoise(rng.nextParallelRNG((seed++) * seed * seed * seed))); + } + return noises; + }); + } + + private static LayersSettings surfaceSettings(IrisBiome biome) { + return biome.getModuleSettings().find(LayersSettings.class).orElse(DEFAULT_LAYERS); + } + + private static boolean isLocked(IrisBiome biome) { + return biome.getModuleSettings().find(LockLayersSettings.class).map(LockLayersSettings::locked).orElse(false); + } + + private static int lockedLayersMax(IrisBiome biome) { + return biome.getModuleSettings().find(LockLayersMaxSettings.class).map(LockLayersMaxSettings::layers).orElse(LockLayersMaxSettings.DEFAULT_LAYERS); + } +} diff --git a/src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java b/src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java new file mode 100644 index 000000000..3cedf3006 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java @@ -0,0 +1,48 @@ +/* + * 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.terrain; + +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; + +import java.util.ArrayList; +import java.util.List; + +/** A palette's blocks as the platform's, the way terrain layers and palettes always picked from them. */ +final class PaletteBlocks { + private PaletteBlocks() { + } + + /** The platform's block of each spec that has one, each repeated by its weight. */ + static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); + for (BlockSpec spec : palette) { + PlatformBlockState state = B.getState(registry.resolve(spec).key()); + if (state == null) { + continue; + } + for (int n = 0; n < spec.weight(); n++) { + weighted.add(state); + } + } + return List.copyOf(weighted); + } +} diff --git a/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java b/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java new file mode 100644 index 000000000..94d8fd5ef --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java @@ -0,0 +1,139 @@ +/* + * 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.terrain; + +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; + +import java.util.List; + +/** + * One {@link PaletteLayer} made ready for one pack: its palette resolved to the platform's blocks, and the noise that + * decides how thick it is here and which block of the palette it picks, built when first asked for. What the layer + * describes stays in the settings; everything that needs the platform, the pack or a seed is here. + * + *

Both noises are built once, from the random of whoever asks first, as the layers of a biome always were: a layer's + * noise is a function of that random, the signature it was first asked with and the layer's own size. + */ +public final class ResolvedLayer { + private final PaletteLayer settings; + private final IrisPackResources resources; + private final AtomicCache> blocks = new AtomicCache<>(); + private final AtomicCache blockNoise = new AtomicCache<>(); + private final AtomicCache heightNoise = new AtomicCache<>(); + + private ResolvedLayer(PaletteLayer settings, IrisPackResources resources) { + this.settings = settings; + this.resources = resources; + } + + /** {@code settings} ready for the blocks and noise of the pack of {@code data}. */ + static ResolvedLayer of(PaletteLayer settings, IrisData data) { + return new ResolvedLayer(settings, data.getPackResources()); + } + + public PaletteLayer settings() { + return settings; + } + + public int minHeight() { + return settings.minHeight(); + } + + public int maxHeight() { + return settings.maxHeight(); + } + + public double zoom() { + return settings.zoom(); + } + + public SlopeClip slopeCondition() { + return settings.slopeCondition(); + } + + /** Whether the layer lists any block, which is not the same as picking one: a listed block may have no weight. */ + public boolean hasPalette() { + return !settings.palette().isEmpty(); + } + + /** The noise that sets the layer's thickness, built from {@code rng} unless an earlier caller's is already kept. */ + public CNG heightNoise(RNG rng) { + CNG cached = heightNoise.getIfPresent(); + if (cached != null) { + return cached; + } + + return heightNoise.aquire(() -> CNG.signature(rng.nextParallelRNG(settings.minHeight() * settings.maxHeight() + blocks().size()))); + } + + /** The layer's block at the position, picked with the noise seeded from {@code parent} and {@code signature}, or null when the palette has no block. */ + public PlatformBlockState get(RNG parent, int signature, double x, double y, double z) { + List palette = blocks(); + if (palette.isEmpty()) { + return null; + } + if (palette.size() == 1) { + return palette.get(0); + } + + double zoom = settings.zoom(); + double noise = blockNoise(parent, signature, palette.size()).sample(x / zoom, y / zoom, z / zoom); + try { + return palette.get((int) Math.round(noise * (palette.size() - 1))); + } catch (IndexOutOfBoundsException outOfRange) { + IrisLogging.reportError(outOfRange); + return palette.get(0); + } + } + + /** {@link #get(RNG, int, double, double, double)} for a layer asked once per column, such as a slab or a wall. */ + public PlatformBlockState get(RNG rng, double x, double y, double z) { + return get(rng, 0, x, y, z); + } + + private List blocks() { + List cached = blocks.getIfPresent(); + if (cached != null) { + return cached; + } + + return blocks.aquire(() -> PaletteBlocks.weighted(resources.blocks(), settings.palette())); + } + + private NoiseSampler blockNoise(RNG parent, int signature, int paletteSize) { + NoiseSampler cached = blockNoise.getIfPresent(); + if (cached != null) { + return cached; + } + + NoiseFactory noise = resources.noise(); + long seed = parent.nextParallelRNG(signature).nextParallelRNG(settings.minHeight() + settings.maxHeight() + paletteSize).getSeed(); + return blockNoise.aquireOrThrow(() -> noise.sampler(settings.style(), seed)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java new file mode 100644 index 000000000..2046a38c6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java @@ -0,0 +1,137 @@ +/* + * 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.terrain; + +import art.arcane.iris.builtin.terrain.FluidPaletteSettings; +import art.arcane.iris.builtin.terrain.RockPaletteSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.PaletteSpec; +import com.volmit.noise.NoiseSampler; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the terrain module keeps for one world about the palettes that fill its terrain: the rock below the biomes' layers + * and the fluid of its oceans and aquifers, as a block for every column, and the rock of an upper dimension. They are the + * dimension's {@link RockPaletteSettings} and {@link FluidPaletteSettings}. + * + *

The noise of a palette is seeded from the world's complex seed and a signature of its own, as the complex always did, so + * a column's rock and fluid do not depend on who asks first. + */ +public final class TerrainPalettes { + private static final int ROCK_SIGNATURE = 45; + private static final int FLUID_SIGNATURE = 78; + /** The salt Iris's material palettes always added to the seed of the noise that picks their blocks. */ + private static final int PALETTE_NOISE_SALT = -23_498_896; + + /** A block for every column. */ + @FunctionalInterface + public interface ColumnBlocks { + /** The block at the column, or null when the palette has no block. */ + PlatformBlockState at(double x, double z); + } + + private final Engine engine; + private final AtomicCache rock = new AtomicCache<>(); + private final AtomicCache fluid = new AtomicCache<>(); + private final Map upperRocks = new ConcurrentHashMap<>(); + + TerrainPalettes(Engine engine) { + this.engine = engine; + } + + /** The palettes of the world {@code engine} generates now. */ + public static TerrainPalettes of(Engine engine) { + return engine.getGeneration().state(TerrainPalettes.class, TerrainPalettes::new); + } + + /** Builds the rock and fluid noise now instead of when first asked for. */ + public void warm() { + rock(); + fluid(); + } + + /** The rock at the column, below the biome's layers. */ + public PlatformBlockState rockAt(double x, double z) { + return rock().at(x, z); + } + + /** The fluid at the column, above the terrain up to the fluid height. */ + public PlatformBlockState fluidAt(double x, double z) { + return fluid().at(x, z); + } + + /** The rock at the column of the upper dimension: the world's own when the upper dimension is the dimension itself. */ + public PlatformBlockState upperRockAt(UpperDimensionContext upper, double x, double z) { + return upperRocks.computeIfAbsent(upper, this::upperRock).at(x, z); + } + + private ColumnBlocks rock() { + return rock.aquireOrThrow(() -> columns(rockPalette(engine.getDimension()), complexRng().nextParallelRNG(ROCK_SIGNATURE), engine.getData())); + } + + private ColumnBlocks fluid() { + return fluid.aquireOrThrow(() -> columns(fluidPalette(engine.getDimension()), complexRng().nextParallelRNG(FLUID_SIGNATURE), engine.getData())); + } + + private RNG complexRng() { + return new RNG(engine.getSeedManager().getComplex()); + } + + private ColumnBlocks upperRock(UpperDimensionContext upper) { + if (upper.isSelfReferencing()) { + return rock(); + } + + long seedOffset = upper.getDimension().getLoadKey().hashCode(); + RNG rng = new RNG(engine.getSeedManager().getComplex() ^ seedOffset); + return columns(rockPalette(upper.getDimension()), rng.nextParallelRNG(ROCK_SIGNATURE), upper.getData()); + } + + private static PaletteSpec rockPalette(IrisDimension dimension) { + return dimension.getModuleSettings().find(RockPaletteSettings.class).orElseGet(RockPaletteSettings::new).palette(); + } + + private static PaletteSpec fluidPalette(IrisDimension dimension) { + return dimension.getModuleSettings().find(FluidPaletteSettings.class).orElseGet(FluidPaletteSettings::new).palette(); + } + + /** The palette's blocks over the columns, picked by its noise: the noise at a column, from 0 to 1, is how far down the weighted list the block is. */ + private static ColumnBlocks columns(PaletteSpec palette, RNG rng, IrisData data) { + IrisPackResources resources = data.getPackResources(); + List blocks = PaletteBlocks.weighted(resources.blocks(), palette.palette()); + if (blocks.isEmpty()) { + return (x, z) -> null; + } + + long seed = rng.getSeed() + (PALETTE_NOISE_SALT + blocks.size()); + NoiseSampler noise = resources.noise().sampler(palette.style(), seed); + int last = blocks.size() - 1; + return (x, z) -> blocks.get((int) Math.round(noise.sample(x, z) * last)); + } +} From df88a4a0509a415225c0408385000ef9d70a07ea Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:46:32 +0200 Subject: [PATCH 051/139] Loot, block drops, entity spawners and effects become settings of iris:loot and iris:spawn; their classes become module types of IrisApi annotations --- .../arcane/iris/builtin/loot/BlockDrop.java | 73 +++++ .../iris/builtin/loot/BlockDropSettings.java | 48 +++ .../loot/ItemAttributeModifier.java} | 56 ++-- .../loot/LootEnchantment.java} | 55 ++-- .../arcane/iris/builtin/loot/LootEntry.java | 181 +++++++++++ .../loot/LootMode.java} | 10 +- .../iris/builtin/loot/LootSettings.java | 72 +++++ .../loot/LootSlot.java} | 10 +- .../loot/LootTable.java} | 68 +++-- .../iris/builtin/spawn/AmbientEffect.java | 247 +++++++++++++++ .../iris/builtin/spawn/EffectCommands.java | 100 ++++++ .../iris/builtin/spawn/EffectSettings.java | 47 +++ .../spawn/EntityDefinition.java} | 212 ++++++++++--- .../iris/builtin/spawn/EntitySpawn.java | 66 ++++ .../spawn/SpawnCommand.java} | 68 +++-- .../spawn/SpawnDuration.java} | 44 +-- .../spawn/SpawnGroup.java} | 10 +- .../spawn/SpawnMarker.java} | 60 ++-- .../spawn/SpawnRate.java} | 39 +-- .../spawn/SpawnSurface.java} | 12 +- .../spawn/SpawnTimeBlock.java} | 25 +- .../spawn/SpawnWeather.java} | 20 +- .../arcane/iris/builtin/spawn/Spawner.java | 98 ++++++ .../iris/builtin/spawn/SpawnerSettings.java | 49 +++ .../iris/engine/loot/BlockDropping.java | 59 +++- .../arcane/iris/engine/loot/LootGiving.java | 62 ++-- .../arcane/iris/engine/loot/LootItems.java | 83 ++--- .../arcane/iris/engine/loot/LootModule.java | 11 +- .../iris/engine/loot/LootResources.java | 19 +- .../arcane/iris/engine/loot/LootTables.java | 102 +++---- .../iris/engine/loot/LootValidator.java | 20 +- .../iris/engine/loot/PlacementLoot.java | 153 ++++++++++ .../iris/engine/loot/ResolvedBlockDrop.java | 72 +++++ .../annotations/RegistryListResource.java | 5 +- .../iris/engine/object/entity/IrisEffect.java | 288 ------------------ .../engine/object/entity/IrisEntitySpawn.java | 66 ---- .../object/entity/IrisPotionEffect.java | 102 ------- .../object/entity/PotionEffectTypes.java | 98 ------ .../spawn/IrisEngineSpawnerCooldown.java | 8 +- .../object/entity/spawn/IrisSpawner.java | 142 --------- .../entity/spawn/IrisSpawnerCooldowns.java | 9 +- .../engine/object/loot/IrisBlockDrops.java | 105 ------- .../iris/engine/object/loot/IrisLoot.java | 113 ------- .../engine/object/loot/IrisLootReference.java | 69 ----- .../engine/object/loot/IrisObjectLoot.java | 3 +- .../object/loot/IrisVanillaLootTable.java | 73 ----- .../object/marker/IrisCommandRegistry.java | 94 ------ .../object/marker/IrisObjectMarker.java | 3 +- .../engine/object/placement/BlocksModule.java | 6 +- .../object/placement/IrisObjectPlacement.java | 143 --------- .../object/structure/IrisStructure.java | 4 +- .../engine/object/world/biome/IrisBiome.java | 16 - .../object/world/dimension/IrisDimension.java | 12 - .../object/world/region/IrisRegion.java | 16 - .../iris/engine/spawn/AmbientEffecting.java | 135 ++++++++ .../iris/engine/spawn/EffectTimers.java | 40 +++ .../iris/engine/spawn/EntityResolution.java | 82 ++--- .../iris/engine/spawn/EntitySpawning.java | 114 ++++--- .../iris/engine/spawn/SpawnConditions.java | 42 +++ .../arcane/iris/engine/spawn/SpawnModule.java | 14 +- .../iris/engine/spawn/SpawnResources.java | 32 +- .../arcane/iris/engine/spawn/SpawnerGate.java | 97 ++++++ 62 files changed, 2278 insertions(+), 1904 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java create mode 100644 src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java rename src/main/java/art/arcane/iris/{engine/object/entity/IrisAttributeModifier.java => builtin/loot/ItemAttributeModifier.java} (74%) rename src/main/java/art/arcane/iris/{engine/object/loot/IrisEnchantment.java => builtin/loot/LootEnchantment.java} (52%) create mode 100644 src/main/java/art/arcane/iris/builtin/loot/LootEntry.java rename src/main/java/art/arcane/iris/{engine/object/loot/IrisLootMode.java => builtin/loot/LootMode.java} (84%) create mode 100644 src/main/java/art/arcane/iris/builtin/loot/LootSettings.java rename src/main/java/art/arcane/iris/{engine/object/loot/InventorySlotType.java => builtin/loot/LootSlot.java} (82%) rename src/main/java/art/arcane/iris/{engine/object/loot/IrisLootTable.java => builtin/loot/LootTable.java} (58%) create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java rename src/main/java/art/arcane/iris/{engine/object/entity/IrisEntity.java => builtin/spawn/EntityDefinition.java} (50%) create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java rename src/main/java/art/arcane/iris/{engine/object/marker/IrisCommand.java => builtin/spawn/SpawnCommand.java} (51%) rename src/main/java/art/arcane/iris/{engine/object/value/IrisDuration.java => builtin/spawn/SpawnDuration.java} (58%) rename src/main/java/art/arcane/iris/{engine/object/entity/spawn/IrisSpawnGroup.java => builtin/spawn/SpawnGroup.java} (79%) rename src/main/java/art/arcane/iris/{engine/object/marker/IrisMarker.java => builtin/spawn/SpawnMarker.java} (51%) rename src/main/java/art/arcane/iris/{engine/object/value/IrisRate.java => builtin/spawn/SpawnRate.java} (54%) rename src/main/java/art/arcane/iris/{engine/object/entity/spawn/IrisSurface.java => builtin/spawn/SpawnSurface.java} (79%) rename src/main/java/art/arcane/iris/{engine/object/world/IrisTimeBlock.java => builtin/spawn/SpawnTimeBlock.java} (71%) rename src/main/java/art/arcane/iris/{engine/object/world/IrisWeather.java => builtin/spawn/SpawnWeather.java} (65%) create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/Spawner.java create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java diff --git a/src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java b/src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java new file mode 100644 index 000000000..75151041e --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java @@ -0,0 +1,73 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("block-drops") +@Desc("Represents a block drop list") +public final class BlockDrop { + @Required + @MinItems(1) + @Desc("The blocks that drop loot") + private List blocks = List.of(); + + @Desc("If exact blocks is set to true, minecraft:barrel[axis=x] will only drop for that axis. When exact is false (default) any barrel will drop the defined drops.") + private boolean exactBlocks = false; + + @MinItems(1) + @Desc("Add in specific items to drop") + private List drops = List.of(); + + @Desc("If this is in a biome, setting skipParents to true will ignore the drops in the region and dimension for this block type. The default (false) will allow all three nodes to fire and add to a list of drops.") + private boolean skipParents = false; + + @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") + private boolean replaceVanillaDrops = false; + + public BlockDrop() { + } + + public List blocks() { + return blocks == null ? List.of() : Collections.unmodifiableList(blocks); + } + + public boolean exactBlocks() { + return exactBlocks; + } + + public List drops() { + return drops == null ? List.of() : Collections.unmodifiableList(drops); + } + + public boolean skipParents() { + return skipParents; + } + + public boolean replaceVanillaDrops() { + return replaceVanillaDrops; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java b/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java new file mode 100644 index 000000000..a58786622 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java @@ -0,0 +1,48 @@ +/* + * 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.builtin.loot; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The block drops one dimension, region or biome declares, written as {@code "blockDrops": [...]}, the list of + * {@link BlockDrop}s. A broken block drops those of its biome, then, unless one of them skips its parents, those of its + * region and dimension. + */ +@Desc("Define custom block drops for this area") +@Feature(id = "iris:loot/drops", name = "Block drops", key = "blockDrops", root = "drops", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class BlockDropSettings implements IrisFeature { + @MinItems(1) + @Desc("Define custom block drops for this area") + private List drops = List.of(); + + public BlockDropSettings() { + } + + public List drops() { + return drops == null ? List.of() : Collections.unmodifiableList(drops); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java b/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java similarity index 74% rename from src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java rename to src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java index 52e4d068c..f5a87fe35 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisAttributeModifier.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,32 +16,21 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.entity; - -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; +package art.arcane.iris.builtin.loot; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; @Snippet("attribute-modifier") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor @Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") -@Data -public class IrisAttributeModifier { +public final class ItemAttributeModifier { @Required @Desc("The Attribute type key such as max_health or minecraft:armor. This type is pulled from the game attributes. Zombie & Horse attributes will not work on non-zombie/horse entities.\nUsing an attribute on an item will have affects when held, or worn. There is no way to specify further granularity as the game picks this depending on the item type.") private String attribute = null; - @MinNumber(2) @Required @Desc("The Attribute Name is used internally only for the game. This value should be unique to all other attributes applied to this item/entity. It is not shown in game.") private String name = ""; @@ -60,7 +49,30 @@ public class IrisAttributeModifier { @Desc("The chance that this attribute is applied (0 to 1). If the chance is 0.5 (50%), then Iris will only apply this attribute 50% of the time.") private double chance = 1; - public double getAmount(RNG rng) { - return rng.d(getMinAmount(), getMaxAmount()); + public ItemAttributeModifier() { + } + + public String attribute() { + return attribute; + } + + public String name() { + return name; + } + + public String operation() { + return operation; + } + + public double minAmount() { + return minAmount; + } + + public double maxAmount() { + return maxAmount; + } + + public double chance() { + return chance; } } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java b/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java similarity index 52% rename from src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java rename to src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java index b3253cc09..0e8d2d405 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisEnchantment.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,33 +16,21 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.loot; - -import art.arcane.iris.engine.framework.LootResolver; -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.RegistryListEnchantment; -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.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - +package art.arcane.iris.builtin.loot; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; @Snippet("enchantment") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("Represents an enchantment & level") -@Data -public class IrisEnchantment { +public final class LootEnchantment { @Required - @RegistryListEnchantment + @Ref(Reference.ENCHANTMENT) @Desc("The enchantment") private String enchantment; @@ -59,7 +47,22 @@ public class IrisEnchantment { @Desc("The chance that this enchantment is applied (0 to 1)") private double chance = 1; - public int getLevel(RNG rng) { - return LootResolver.inclusive(rng, getMinLevel(), getMaxLevel()); + public LootEnchantment() { + } + + public String enchantment() { + return enchantment; + } + + public int minLevel() { + return minLevel; + } + + public int maxLevel() { + return maxLevel; + } + + public double chance() { + return chance; } } diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java b/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java new file mode 100644 index 000000000..b90fa6d8d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java @@ -0,0 +1,181 @@ +/* + * 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.builtin.loot; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +@Snippet("loot") +@Desc("Represents a loot entry") +public final class LootEntry { + public static final int MAX_AMOUNT = 64; + + @Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.") + private LootSlot slotTypes = LootSlot.STORAGE; + + @MinNumber(1) + @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") + private int rarity = 1; + + @MinNumber(1) + @MaxNumber(MAX_AMOUNT) + @Desc("Minimum amount of this loot, from 1 to 64") + private int minAmount = 1; + + @MinNumber(1) + @MaxNumber(MAX_AMOUNT) + @Desc("Maximum amount of this loot, from 1 to 64") + private int maxAmount = 1; + + @Desc("The display name of this item") + private String displayName = null; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Minimum durability percent") + private double minDurability = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Maximum durability percent") + private double maxDurability = 1; + + @Desc("Define a custom model identifier 1.14+ only") + private Integer customModel = null; + + @Desc("Set this to true to prevent it from being broken") + private boolean unbreakable = false; + + @MinItems(1) + @Desc("The item flags to add") + private List itemFlags = List.of(); + + @MinItems(1) + @Desc("Apply enchantments to this item") + private List enchantments = List.of(); + + @MinItems(1) + @Desc("Apply attribute modifiers to this item") + private List attributes = List.of(); + + @MinItems(1) + @Desc("Add lore to this item") + private List lore = List.of(); + + @Ref(Reference.ITEM) + @Required + @Desc("This is the item or block type. Does not accept minecraft:*, only materials such as DIAMOND_SWORD or DIRT. The exception are modded materials, as they require a namespace.") + private String type = ""; + + @Desc("The dye color") + private String dyeColor = null; + + @Desc("The leather armor color") + private String leatherColor = null; + + @Desc("Defines a custom NBT Tag for the item.") + private Map customNbt; + + public LootEntry() { + } + + public LootSlot slotTypes() { + return slotTypes == null ? LootSlot.STORAGE : slotTypes; + } + + public int rarity() { + return rarity; + } + + public int minAmount() { + return minAmount; + } + + public int maxAmount() { + return maxAmount; + } + + public String displayName() { + return displayName; + } + + public double minDurability() { + return minDurability; + } + + public double maxDurability() { + return maxDurability; + } + + public Integer customModel() { + return customModel; + } + + public boolean unbreakable() { + return unbreakable; + } + + public List itemFlags() { + return listOrEmpty(itemFlags); + } + + public List enchantments() { + return listOrEmpty(enchantments); + } + + public List attributes() { + return listOrEmpty(attributes); + } + + public List lore() { + return listOrEmpty(lore); + } + + /** The authored item key, exactly as written in the pack. Each platform resolves it against its own item registry. */ + public String type() { + return type; + } + + public String dyeColor() { + return dyeColor; + } + + public String leatherColor() { + return leatherColor; + } + + /** The custom data of the item; empty when unset. */ + public Map customNbt() { + return customNbt == null ? Map.of() : Collections.unmodifiableMap(customNbt); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java b/src/main/java/art/arcane/iris/builtin/loot/LootMode.java similarity index 84% rename from src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java rename to src/main/java/art/arcane/iris/builtin/loot/LootMode.java index 622d7f825..7fe817478 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootMode.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootMode.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.loot; +package art.arcane.iris.builtin.loot; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("A loot mode is used to describe what to do with the existing loot layers before adding this loot. ADD appends to the building list of tables (dimension tables, then region tables, then biome tables). REPLACE swaps the parent tables for this reference's tables. CLEAR suppresses loot entirely at this point.") -public enum IrisLootMode { +public enum LootMode { @Desc("Add to the existing parent loot tables") ADD, @Desc("Clear all parent loot tables and contribute nothing at this level. Any tables listed here are ignored.") diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java new file mode 100644 index 000000000..5d9b12ae7 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java @@ -0,0 +1,72 @@ +/* + * 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.builtin.loot; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** + * The loot tables one dimension, region or biome adds to the containers it covers, written as + * {@code "loot": {"mode": "ADD", "tables": [...], "multiplier": 1}}. Levels stack, dimension first, then region and + * biome; {@link LootMode} says what each does with the tables before it. An entity's {@code loot} has the same shape. + */ +@Snippet("loot-registry") +@Desc("Reference loot tables in this area") +@Feature(id = "iris:loot", name = "Loot", key = "loot", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class LootSettings implements IrisFeature { + public static final double MAX_MULTIPLIER = 16D; + + @Desc("ADD = add on top of parent tables. REPLACE = clear parent tables, then add these. CLEAR = clear parent tables and add nothing, even if tables are listed. FALLBACK = only used when nothing else defined a table.") + private LootMode mode = LootMode.ADD; + + @ResourceRef(LootTable.class) + @Desc("Add loot table registries here") + private List tables = List.of(); + + @MinNumber(0) + @MaxNumber(MAX_MULTIPLIER) + @Desc("Scale loot sources in this area from 0 to 16 times their normal count") + private double multiplier = 1D; + + /** Nothing added, nothing scaled: what a level without loot settings means. */ + public LootSettings() { + } + + public LootMode mode() { + return mode == null ? LootMode.ADD : mode; + } + + /** The keys of the loot tables, in order. */ + public List tables() { + return tables == null ? List.of() : Collections.unmodifiableList(tables); + } + + public double multiplier() { + return multiplier; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java b/src/main/java/art/arcane/iris/builtin/loot/LootSlot.java similarity index 82% rename from src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java rename to src/main/java/art/arcane/iris/builtin/loot/LootSlot.java index 574fc301f..6723d461a 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/InventorySlotType.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootSlot.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.loot; +package art.arcane.iris.builtin.loot; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("An inventory slot type is used to represent a type of slot for items to fit into in any given inventory.") -public enum InventorySlotType { +public enum LootSlot { @Desc("Typically the one you want to go with. Storage represnents most slots in inventories.") STORAGE, diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java b/src/main/java/art/arcane/iris/builtin/loot/LootTable.java similarity index 58% rename from src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java rename to src/main/java/art/arcane/iris/builtin/loot/LootTable.java index d92ff93ee..5c495b3db 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootTable.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootTable.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,34 +16,25 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.loot; +package art.arcane.iris.builtin.loot; -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.Required; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor +import java.util.Collections; +import java.util.List; + +/** A loot table of the pack, one file of {@code loot/}. */ @Desc("Represents a loot table. Biomes, Regions & Objects can add or replace the virtual table with these loot tables") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisLootTable extends IrisRegistrant { +public final class LootTable { public static final int MAX_PICKED = 64; public static final int MAX_TRIES = 256; @Required @Desc("The name of this loot table") - @MinNumber(2) private String name = ""; @MinNumber(1) @@ -65,17 +56,34 @@ public class IrisLootTable extends IrisRegistrant { @Desc("The maximum amount of tries to generate loot, from 1 to 256") private int maxTries = 10; + @MinItems(1) @Desc("The loot in this table") - @ArrayType(min = 1, type = IrisLoot.class) - private KList loot = new KList<>(); + private List loot = List.of(); - @Override - public String getFolderName() { - return "loot"; + public LootTable() { } - @Override - public String getTypeName() { - return "Loot"; + public String name() { + return name == null ? "" : name; + } + + public int rarity() { + return rarity; + } + + public int maxPicked() { + return maxPicked; + } + + public int minPicked() { + return minPicked; + } + + public int maxTries() { + return maxTries; + } + + public List loot() { + return loot == null ? List.of() : Collections.unmodifiableList(loot); } } diff --git a/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java b/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java new file mode 100644 index 000000000..090e3ee97 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java @@ -0,0 +1,247 @@ +/* + * 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.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** + * A sound, particles, potion effect or commands that play now and then around the players in an area. The same + * settings make the effect an entity shows when it appears ({@link EntityDefinition#spawnEffect()}). + */ +@Snippet("effect") +@Desc("An iris effect") +public final class AmbientEffect { + @Ref(Reference.POTION_EFFECT) + @Desc("The potion effect to apply in this area") + private String potionEffect = ""; + + @Desc("The particle effect to apply in the area") + private String particleEffect = null; + + @MinNumber(-32) + @MaxNumber(32) + @Desc("Randomly offset from the surface to this surface+value") + private int particleOffset = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltX = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltY = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltZ = 0; + + @Desc("Randomize the altX by -altX to altX") + private boolean randomAltX = true; + + @Desc("Randomize the altY by -altY to altY") + private boolean randomAltY = false; + + @Desc("Randomize the altZ by -altZ to altZ") + private boolean randomAltZ = true; + + @Desc("The sound to play") + private String sound = null; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The max distance from the player the sound will play") + private int soundDistance = 12; + + @MinNumber(0.01) + @MaxNumber(1.99) + @Desc("The minimum sound pitch") + private double minPitch = 0.5D; + + @MinNumber(0.01) + @MaxNumber(1.99) + @Desc("The max sound pitch") + private double maxPitch = 1.5D; + + @MinNumber(0.001) + @MaxNumber(512) + @Desc("The sound volume.") + private double volume = 1.5D; + + @MinNumber(0) + @MaxNumber(512) + @Desc("The particle count. Try setting to zero for using the alt xyz to a motion value instead of an offset") + private int particleCount = 0; + + @MinNumber(0) + @MaxNumber(64) + @Desc("How far away from the player particles can play") + private int particleDistance = 20; + + @MinNumber(0) + @MaxNumber(128) + @Desc("How wide the particles can play (player's view left and right) RADIUS") + private int particleDistanceWidth = 24; + + @Desc("An extra value for some particles... Which bukkit doesn't even document.") + private double extra = 0; + + @MinNumber(-1) + @MaxNumber(1024) + @Desc("The Potion Strength or -1 to disable") + private int potionStrength = -1; + + @MinNumber(1) + @Desc("The max time the potion will last for") + private int potionTicksMax = 155; + + @MinNumber(1) + @Desc("The min time the potion will last for") + private int potionTicksMin = 75; + + @Required + @MinNumber(0) + @Desc("The effect interval in milliseconds") + private int interval = 150; + + @MinNumber(0) + @MaxNumber(16) + @Desc("The effect distance start away") + private int particleAway = 5; + + @Required + @MinNumber(1) + @Desc("The chance is 1 in CHANCE per interval") + private int chance = 50; + + @Desc("Run commands, with configurable location parameters") + private EffectCommands commandRegistry = null; + + public AmbientEffect() { + } + + public String potionEffect() { + return potionEffect; + } + + public String particleEffect() { + return particleEffect; + } + + public int particleOffset() { + return particleOffset; + } + + public double particleAltX() { + return particleAltX; + } + + public double particleAltY() { + return particleAltY; + } + + public double particleAltZ() { + return particleAltZ; + } + + public boolean randomAltX() { + return randomAltX; + } + + public boolean randomAltY() { + return randomAltY; + } + + public boolean randomAltZ() { + return randomAltZ; + } + + public String sound() { + return sound; + } + + public int soundDistance() { + return soundDistance; + } + + public double minPitch() { + return minPitch; + } + + public double maxPitch() { + return maxPitch; + } + + public double volume() { + return volume; + } + + public int particleCount() { + return particleCount; + } + + public int particleDistance() { + return particleDistance; + } + + public int particleDistanceWidth() { + return particleDistanceWidth; + } + + public double extra() { + return extra; + } + + public int potionStrength() { + return potionStrength; + } + + public int potionTicksMax() { + return potionTicksMax; + } + + public int potionTicksMin() { + return potionTicksMin; + } + + public int interval() { + return interval; + } + + public int particleAway() { + return particleAway; + } + + public int chance() { + return chance; + } + + /** The commands the effect runs; null for none. */ + public EffectCommands commandRegistry() { + return commandRegistry; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java b/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java new file mode 100644 index 000000000..48ed35cc8 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java @@ -0,0 +1,100 @@ +/* + * 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.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("command-registry") +@Desc("Represents a casting location for a command") +public final class EffectCommands { + @Required + @MinItems(1) + @Desc("Run commands, at the exact location of the player") + private List rawCommands = List.of(); + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetX = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetY = 0; + + @MinNumber(-8) + @MaxNumber(8) + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double commandOffsetZ = 0; + + @Desc("Randomize the altX from -altX to altX") + private boolean commandRandomAltX = true; + + @Desc("Randomize the altY from -altY to altY") + private boolean commandRandomAltY = false; + + @Desc("Randomize the altZ from -altZ to altZ") + private boolean commandRandomAltZ = true; + + @Desc("Randomize location for all separate commands (true), or run all on the same location (false)") + private boolean commandAllRandomLocations = true; + + public EffectCommands() { + } + + public List rawCommands() { + return rawCommands == null ? List.of() : Collections.unmodifiableList(rawCommands); + } + + public double commandOffsetX() { + return commandOffsetX; + } + + public double commandOffsetY() { + return commandOffsetY; + } + + public double commandOffsetZ() { + return commandOffsetZ; + } + + public boolean commandRandomAltX() { + return commandRandomAltX; + } + + public boolean commandRandomAltY() { + return commandRandomAltY; + } + + public boolean commandRandomAltZ() { + return commandRandomAltZ; + } + + public boolean commandAllRandomLocations() { + return commandAllRandomLocations; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java b/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java new file mode 100644 index 000000000..49f90914c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.spawn; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The ambient effects one region or biome declares, written as {@code "effects": [...]}, the list of + * {@link AmbientEffect}s. They play around every player in the area. + */ +@Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") +@Feature(id = "iris:spawn/effects", name = "Effects", key = "effects", root = "effects", targets = {Target.REGION, Target.BIOME}) +public final class EffectSettings implements IrisFeature { + @MinItems(1) + @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player.") + private List effects = List.of(); + + public EffectSettings() { + } + + public List effects() { + return effects == null ? List.of() : Collections.unmodifiableList(effects); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java b/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java similarity index 50% rename from src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java rename to src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java index 709d4c2b1..a1258af7d 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntity.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,34 +16,25 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.entity; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.entity.spawn.IrisSurface; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.marker.IrisCommand; -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.RegistryListEntityType; -import art.arcane.iris.engine.object.annotations.RegistryListSpecialEntity; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.volmlib.util.collection.KList; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import art.arcane.iris.builtin.loot.ItemAttributeModifier; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootSettings; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; -@SuppressWarnings("ALL") -@Accessors(chain = true) -@NoArgsConstructor +import java.util.Collections; +import java.util.List; +/** An entity of the pack, one file of {@code entities/}: what spawners and markers spawn, with its equipment, attributes, passengers and loot. */ @Desc("Represents an iris entity.") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisEntity extends IrisRegistrant { +public final class EntityDefinition { @Required - @RegistryListEntityType + @Ref(Reference.ENTITY) @Desc("The namespaced key of the entity type to spawn, such as minecraft:zombie or alexsmobs:grizzly_bear. To spawn a mob from another plugin or provider, set this type to unknown and define the special type.") private String type = null; @@ -81,39 +72,39 @@ public class IrisEntity extends IrisRegistrant { private boolean removable = false; @Desc("Entity helmet equipment") - private IrisLoot helmet = null; + private LootEntry helmet = null; @Desc("Entity chestplate equipment") - private IrisLoot chestplate = null; + private LootEntry chestplate = null; @Desc("Entity boots equipment") - private IrisLoot boots = null; + private LootEntry boots = null; @Desc("Entity leggings equipment") - private IrisLoot leggings = null; + private LootEntry leggings = null; @Desc("Entity main hand equipment") - private IrisLoot mainHand = null; + private LootEntry mainHand = null; @Desc("Entity off hand equipment") - private IrisLoot offHand = null; + private LootEntry offHand = null; + @MinItems(1) @Desc("Make other entities ride this entity") - @ArrayType(min = 1, type = IrisEntity.class) - private KList passengers = new KList<>(); + private List passengers = List.of(); + @MinItems(1) @Desc("Attribute modifiers for this entity") - @ArrayType(min = 1, type = IrisAttributeModifier.class) - private KList attributes = new KList<>(); + private List attributes = List.of(); @Desc("Loot tables for drops. Only the tables list is honored for entities; mode and multiplier are ignored, and the tables replace vanilla drops entirely.") - private IrisLootReference loot = new IrisLootReference(); + private LootSettings loot = new LootSettings(); @Desc("If specified, this entity will be leashed by this entity. I.e. THIS ENTITY Leashed by SPECIFIED. This has no effect on EnderDragons, Withers, Players, or Bats.Non-living entities excluding leashes will not persist as leashholders.") - private IrisEntity leashHolder = null; + private EntityDefinition leashHolder = null; @Desc("If specified, this entity will spawn with an effect") - private IrisEffect spawnEffect = null; + private AmbientEffect spawnEffect = null; @Desc("Simply moves the entity from below the surface slowly out of the ground as a spawn-in effect") private boolean spawnEffectRiseOutOfGround = false; @@ -131,30 +122,153 @@ public class IrisEntity extends IrisRegistrant { private boolean keepEntity = false; @Desc("The surface type to spawn this mob on") - private IrisSurface surface = IrisSurface.LAND; + private SpawnSurface surface = SpawnSurface.LAND; - @RegistryListSpecialEntity + @Ref(Reference.SPECIAL_ENTITY) @Desc("Create a mob from another plugin, such as Mythic Mobs. Should be in the format of a namespace of PluginName:MobName") private String specialType = ""; @Desc("Set to true if you want to apply all of the settings here to the mob, even though an external plugin has already done so.") private boolean applySettingsToCustomMobAnyways = false; - @ArrayType(min = 1, type = IrisCommand.class) + @MinItems(1) @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") - private KList rawCommands = new KList<>(); + private List rawCommands = List.of(); + public EntityDefinition() { + } + + public String type() { + return type; + } + + public String reason() { + return reason; + } + + public String customName() { + return customName; + } + + public boolean customNameVisible() { + return customNameVisible; + } + + public boolean aware() { + return aware; + } + + public boolean ai() { + return ai; + } + + public boolean glowing() { + return glowing; + } + + public boolean gravity() { + return gravity; + } + + public boolean invulnerable() { + return invulnerable; + } + + public boolean silent() { + return silent; + } + + public boolean pickupItems() { + return pickupItems; + } + + public boolean removable() { + return removable; + } + + public LootEntry helmet() { + return helmet; + } + + public LootEntry chestplate() { + return chestplate; + } + + public LootEntry boots() { + return boots; + } + + public LootEntry leggings() { + return leggings; + } + + public LootEntry mainHand() { + return mainHand; + } + + public LootEntry offHand() { + return offHand; + } + + public List passengers() { + return passengers == null ? List.of() : Collections.unmodifiableList(passengers); + } + + public List attributes() { + return attributes == null ? List.of() : Collections.unmodifiableList(attributes); + } + + /** The loot the entity drops when it dies; only its tables count. */ + public LootSettings loot() { + return loot == null ? new LootSettings() : loot; + } + + public EntityDefinition leashHolder() { + return leashHolder; + } + + public AmbientEffect spawnEffect() { + return spawnEffect; + } + + public boolean spawnEffectRiseOutOfGround() { + return spawnEffectRiseOutOfGround; + } + + public String pandaMainGene() { + return pandaMainGene; + } + + public String pandaHiddenGene() { + return pandaHiddenGene; + } + + public boolean baby() { + return baby; + } + + public boolean keepEntity() { + return keepEntity; + } + + public SpawnSurface surface() { + return surface == null ? SpawnSurface.LAND : surface; + } + + public String specialType() { + return specialType; + } + + /** Whether the entity is a mob of another plugin. */ public boolean isSpecialType() { - return specialType != null && !specialType.equals(""); + return specialType != null && !specialType.isEmpty(); } - @Override - public String getFolderName() { - return "entities"; + public boolean applySettingsToCustomMobAnyways() { + return applySettingsToCustomMobAnyways; } - @Override - public String getTypeName() { - return "Entity"; + public List rawCommands() { + return rawCommands == null ? List.of() : Collections.unmodifiableList(rawCommands); } } diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java new file mode 100644 index 000000000..34acbcae5 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java @@ -0,0 +1,66 @@ +/* + * 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.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +@Snippet("entity-spawn") +@Desc("Represents an entity spawn during initial chunk generation") +public final class EntitySpawn { + @ResourceRef(EntityDefinition.class) + @Required + @Desc("The entity") + private String entity = ""; + + @MinNumber(1) + @Desc("The 1 in RARITY chance for this entity to spawn") + private int rarity = 1; + + @MinNumber(1) + @Desc("The minumum of this entity to spawn") + private int minSpawns = 1; + + @MinNumber(1) + @Desc("The max of this entity to spawn") + private int maxSpawns = 1; + + public EntitySpawn() { + } + + /** The key of the entity of the pack. */ + public String entity() { + return entity; + } + + public int rarity() { + return rarity; + } + + public int minSpawns() { + return minSpawns; + } + + public int maxSpawns() { + return maxSpawns; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java similarity index 51% rename from src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java index 5062b80b5..cfd8f5b64 100644 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommand.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,32 +16,23 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.marker; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.world.IrisTimeBlock; -import art.arcane.iris.engine.object.world.IrisWeather; -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.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.PlatformWorld; -import art.arcane.iris.util.common.scheduling.ConsoleCommands; -import art.arcane.volmlib.util.collection.KList; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; @Snippet("command") -@Accessors(chain = true) -@NoArgsConstructor @Desc("Represents a set of Iris commands") -@Data -public class IrisCommand { - +public final class SpawnCommand { @Required - @ArrayType(min = 1, type = String.class) + @MinItems(1) @Desc("List of commands. Iris replaces {x} {y} and {z} with the location of the entity spawn") - private KList commands = new KList<>(); + private List commands = List.of(); @Desc("The delay for running the command. Instant by default") private long delay = 0; @@ -53,20 +44,35 @@ public class IrisCommand { private long repeatDelay = 100; @Desc("The block of 24 hour time in which the command should execute.") - private IrisTimeBlock timeBlock = new IrisTimeBlock(); + private SpawnTimeBlock timeBlock = new SpawnTimeBlock(); @Desc("The weather that is required for the command to execute.") - private IrisWeather weather = IrisWeather.ANY; + private SpawnWeather weather = SpawnWeather.ANY; - public boolean isValid(PlatformWorld world) { - return timeBlock.isWithin(world) && weather.is(world); + public SpawnCommand() { } - public void run(PlatformWorld world, int x, int y, int z) { - if (!isValid(world)) { - return; - } + public List commands() { + return commands == null ? List.of() : Collections.unmodifiableList(commands); + } - ConsoleCommands.run(commands, delay, repeat, repeatDelay, x, y, z); + public long delay() { + return delay; + } + + public boolean repeat() { + return repeat; + } + + public long repeatDelay() { + return repeatDelay; + } + + public SpawnTimeBlock timeBlock() { + return timeBlock == null ? new SpawnTimeBlock() : timeBlock; + } + + public SpawnWeather weather() { + return weather == null ? SpawnWeather.ANY : weather; } } diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisDuration.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java similarity index 58% rename from src/main/java/art/arcane/iris/engine/object/value/IrisDuration.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java index 822bd6962..afe1263b5 100644 --- a/src/main/java/art/arcane/iris/engine/object/value/IrisDuration.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,19 +16,22 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.value; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.format.Form; -import lombok.Data; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; import java.util.concurrent.TimeUnit; @Snippet("duration") -@Data @Desc("Represents a combined duration. Fill each property to add time into a single duration") -public class IrisDuration { +public final class SpawnDuration { + private static final long MILLISECONDS_PER_MINECRAFT_TICK = 50L; + private static final long MILLISECONDS_PER_MINECRAFT_HOUR = 50_000L; + private static final long MILLISECONDS_PER_MINECRAFT_DAY = 1_200_000L; + private static final long MILLISECONDS_PER_MINECRAFT_WEEK = 8_400_000L; + private static final long MILLISECONDS_PER_MINECRAFT_LUNAR_CYCLE = 9_600_000L; + @Desc("Milliseconds (1000ms = 1 second)") private int milliseconds = 0; @@ -59,20 +62,19 @@ public class IrisDuration { @Desc("REAL (not minecraft) Days") private int days = 0; - public String toString() { - return Form.duration((double) toMilliseconds(), 2); + public SpawnDuration() { } public long toMilliseconds() { - return getMilliseconds() - + TimeUnit.SECONDS.toMillis(getSeconds()) - + TimeUnit.MINUTES.toMillis(getMinutes()) - + TimeUnit.HOURS.toMillis(getHours()) - + TimeUnit.DAYS.toMillis(getDays()) - + (getMinecraftTicks() * 50L) - + (getMinecraftHours() * 50000L) - + (getMinecraftDays() * 1_200_000L) - + (getMinecraftWeeks() * 8_400_000L) - + (getMinecraftLunarCycles() * 9_600_000L); + return milliseconds + + TimeUnit.SECONDS.toMillis(seconds) + + TimeUnit.MINUTES.toMillis(minutes) + + TimeUnit.HOURS.toMillis(hours) + + TimeUnit.DAYS.toMillis(days) + + (minecraftTicks * MILLISECONDS_PER_MINECRAFT_TICK) + + (minecraftHours * MILLISECONDS_PER_MINECRAFT_HOUR) + + (minecraftDays * MILLISECONDS_PER_MINECRAFT_DAY) + + (minecraftWeeks * MILLISECONDS_PER_MINECRAFT_WEEK) + + (minecraftLunarCycles * MILLISECONDS_PER_MINECRAFT_LUNAR_CYCLE); } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnGroup.java similarity index 79% rename from src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnGroup.java index 20f8b65f1..0e2b1abd8 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnGroup.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnGroup.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.entity.spawn; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Terrain modes are used to decide the generator type currently used") -public enum IrisSpawnGroup { +public enum SpawnGroup { @Desc("Spawns on the terrain surface") NORMAL, diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java similarity index 51% rename from src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java index 1cb419299..249b8fb5a 100644 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,32 +16,22 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.marker; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -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 art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.ResourceRef; -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor +import java.util.Collections; +import java.util.List; + +/** A marker of the pack, one file of {@code markers/}: object placements put markers in the world and a marker names the spawners that fire there. */ @Desc("Represents a marker") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisMarker extends IrisRegistrant { +public final class SpawnMarker { @Desc("A list of spawners to add to anywhere this marker is.") - @RegistryListResource(IrisSpawner.class) - @ArrayType(type = String.class, min = 1) - private KList spawners = new KList<>(); + @ResourceRef(Spawner.class) + @MinItems(1) + private List spawners = List.of(); @Desc("Remove this marker when the block it's assigned to is changed.") private boolean removeOnChange = true; @@ -52,17 +42,23 @@ public class IrisMarker extends IrisRegistrant { @Desc("If this marker is used, what is the chance it removes itself. For example 25% (0.25) would mean that on average 4 uses will remove a specific marker. Set this below 0 (-1) to never exhaust & set this to 1 or higher to always exhaust on first use.") private double exhaustionChance = 0; - public boolean shouldExhaust() { - return exhaustionChance > RNG.r.nextDouble(); + public SpawnMarker() { } - @Override - public String getFolderName() { - return "markers"; + /** The keys of the spawners that fire at the marker. */ + public List spawners() { + return spawners == null ? List.of() : Collections.unmodifiableList(spawners); } - @Override - public String getTypeName() { - return "Marker"; + public boolean removeOnChange() { + return removeOnChange; + } + + public boolean emptyAbove() { + return emptyAbove; + } + + public double exhaustionChance() { + return exhaustionChance; } } diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisRate.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java similarity index 54% rename from src/main/java/art/arcane/iris/engine/object/value/IrisRate.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java index f347b6085..05e226551 100644 --- a/src/main/java/art/arcane/iris/engine/object/value/IrisRate.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,42 +16,35 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.value; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.scheduling.ChronoLatch; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; @Snippet("rate") -@NoArgsConstructor -@AllArgsConstructor -@Data @Desc("Represents a count of something per time duration") -public class IrisRate { +public final class SpawnRate { @Desc("The amount of things. Leave 0 for infinite (meaning always spawn whenever)") private int amount = 0; @Desc("The time interval. Leave blank for infinite 0 (meaning always spawn all the time)") - private IrisDuration per = new IrisDuration(); + private SpawnDuration per = new SpawnDuration(); - public String toString() { - return Form.f(amount) + "/" + per; + public SpawnRate() { } - public long getInterval() { - long t = per.toMilliseconds() / (amount == 0 ? 1 : amount); + /** The milliseconds between two things: the interval divided by the amount, at least 1. */ + public long interval() { + long t = duration().toMilliseconds() / (amount == 0 ? 1 : amount); return Math.abs(t <= 0 ? 1 : t); } - public ChronoLatch toChronoLatch() { - return new ChronoLatch(getInterval()); + /** Whether there is no limit: no interval was given. */ + public boolean isInfinite() { + return duration().toMilliseconds() == 0; } - public boolean isInfinite() { - return per.toMilliseconds() == 0; + private SpawnDuration duration() { + return per == null ? new SpawnDuration() : per; } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnSurface.java similarity index 79% rename from src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnSurface.java index 8a7677d15..45a9ad3c8 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSurface.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnSurface.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,12 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.entity.spawn; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The type of surface entities should spawn on") -public enum IrisSurface { +public enum SpawnSurface { @Desc("Land surfaces") LAND, @@ -36,5 +36,5 @@ public enum IrisSurface { OVERWORLD, @Desc("Within lava") - LAVA; + LAVA } diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java similarity index 71% rename from src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java index b4035203c..5fc38b4b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/world/IrisTimeBlock.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,30 +16,29 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.world; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.PlatformWorld; -import lombok.Data; +import com.volmit.config.Desc; +import com.volmit.config.Snippet; @Snippet("time-block") -@Data @Desc("Represents a time of day (24h time, not 12h am/pm). Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") -public class IrisTimeBlock { +public final class SpawnTimeBlock { + private static final double NEVER = -1; + @Desc("The beginning hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") private double startHour = 0; @Desc("The ending hour. Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") private double endHour = 0; - public boolean isWithin(PlatformWorld world) { - return isWithin(((world.getTime() / 1000D) + 6) % 24); + public SpawnTimeBlock() { } - public boolean isWithin(double hour) { + /** Whether {@code hour}, a time of day from 0 to 24, lies in the block; a block that wraps past midnight includes both ends. */ + public boolean contains(double hour) { if (startHour == endHour) { - return endHour != -1; + return endHour != NEVER; } if (startHour > endHour) { diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnWeather.java similarity index 65% rename from src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java rename to src/main/java/art/arcane/iris/builtin/spawn/SpawnWeather.java index db242e502..a19bd6eda 100644 --- a/src/main/java/art/arcane/iris/engine/object/world/IrisWeather.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnWeather.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,13 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.world; +package art.arcane.iris.builtin.spawn; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.spi.PlatformWorld; +import com.volmit.config.Desc; @Desc("Represents a weather type") -public enum IrisWeather { +public enum SpawnWeather { @Desc("Represents when weather is not causing downfall") NONE, @@ -35,11 +34,12 @@ public enum IrisWeather { @Desc("Any weather") ANY; - public boolean is(PlatformWorld world) { + /** Whether the weather of a world, which is {@code storming} and {@code thundering} or neither, is this one. */ + public boolean matches(boolean storming, boolean thundering) { return switch (this) { - case NONE -> !world.isStorming() && !world.isThundering(); - case DOWNFALL -> world.isStorming(); - case DOWNFALL_WITH_THUNDER -> world.isStorming() && world.isThundering(); + case NONE -> !storming && !thundering; + case DOWNFALL -> storming; + case DOWNFALL_WITH_THUNDER -> storming && thundering; case ANY -> true; }; } diff --git a/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java b/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java new file mode 100644 index 000000000..e688df757 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java @@ -0,0 +1,98 @@ +/* + * 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.builtin.spawn; + +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.Range; + +import java.util.Collections; +import java.util.List; + +/** A spawner of the pack, one file of {@code spawners/}: which entities appear where, when and how often. */ +@Desc("Represents an entity spawn during initial chunk generation") +public final class Spawner { + @MinItems(1) + @Desc("The entity spawns to add") + private List spawns = List.of(); + + @MinItems(1) + @Desc("The entity spawns to add initially. EXECUTES PER CHUNK!") + private List initialSpawns = List.of(); + + @Desc("This spawner will not spawn in a given chunk if that chunk has more than the defined amount of living entities.") + private int maxEntitiesPerChunk = 1; + + @Desc("The block of 24 hour time to contain this spawn in.") + private SpawnTimeBlock timeBlock = new SpawnTimeBlock(); + + @Desc("The weather condition required for this spawner to fire.") + private SpawnWeather weather = SpawnWeather.ANY; + + @Desc("The maximum rate this spawner can fire") + private SpawnRate maximumRate = new SpawnRate(); + + @Desc("The maximum rate this spawner can fire on a specific chunk") + private SpawnRate maximumRatePerChunk = new SpawnRate(); + + @Desc("The light levels this spawn is allowed to run in (0-15 inclusive)") + private Range allowedLightLevels = Range.of(0, 15); + + @Desc("Where should these spawns be placed") + private SpawnGroup group = SpawnGroup.NORMAL; + + public Spawner() { + } + + public List spawns() { + return spawns == null ? List.of() : Collections.unmodifiableList(spawns); + } + + public List initialSpawns() { + return initialSpawns == null ? List.of() : Collections.unmodifiableList(initialSpawns); + } + + public int maxEntitiesPerChunk() { + return maxEntitiesPerChunk; + } + + public SpawnTimeBlock timeBlock() { + return timeBlock == null ? new SpawnTimeBlock() : timeBlock; + } + + public SpawnWeather weather() { + return weather == null ? SpawnWeather.ANY : weather; + } + + public SpawnRate maximumRate() { + return maximumRate == null ? new SpawnRate() : maximumRate; + } + + public SpawnRate maximumRatePerChunk() { + return maximumRatePerChunk == null ? new SpawnRate() : maximumRatePerChunk; + } + + public Range allowedLightLevels() { + return allowedLightLevels == null ? Range.of(0, 15) : allowedLightLevels; + } + + public SpawnGroup group() { + return group == null ? SpawnGroup.NORMAL : group; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java new file mode 100644 index 000000000..b4e976c52 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java @@ -0,0 +1,49 @@ +/* + * 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.builtin.spawn; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; +import com.volmit.config.ResourceRef; + +import java.util.Collections; +import java.util.List; + +/** + * The spawners one dimension, region or biome lists, written as {@code "entitySpawners": [...]}, the keys of the + * {@link Spawner}s. A chunk may fire the spawners of its dimension, region and biome. + */ +@Desc("Entity spawners that fire in this area") +@Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class SpawnerSettings implements IrisFeature { + @MinItems(1) + @ResourceRef(Spawner.class) + @Desc("Entity spawners to add to this area") + private List spawners = List.of(); + + public SpawnerSettings() { + } + + public List spawners() { + return spawners == null ? List.of() : Collections.unmodifiableList(spawners); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index e1ff26a61..55b501500 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -18,20 +18,25 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.loot.BlockDrop; +import art.arcane.iris.builtin.loot.BlockDropSettings; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.loot.IrisBlockDrops; +import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; import com.volmit.service.BlockDrops; import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * How {@code iris:loot} drops items for broken blocks: the block drops of the biome, the region and the dimension, the @@ -44,23 +49,53 @@ public final class BlockDropping implements BlockDrops { int x = broken.position().x(); int y = broken.position().y(); int z = broken.position().z(); - PlatformBlockState block = IrisPlatforms.get().registries().block(broken.block().key()); + String brokenKey = IrisPlatforms.get().registries().block(broken.block().key()).key(); + ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops()); IrisBiome biome = engine.getBiome(x, y, z); - List providers = dropsFor(biome.getBlockDrops(), block, engine); - if (providers.stream().noneMatch(IrisBlockDrops::isSkipParents)) { + List providers = dropsFor(biome, brokenKey, resolved, world); + if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) { IrisRegion region = engine.getRegion(x, z); - providers.addAll(dropsFor(region.getBlockDrops(), block, engine)); - providers.addAll(dropsFor(engine.getDimension().getBlockDrops(), block, engine)); + providers.addAll(dropsFor(region, brokenKey, resolved, world)); + providers.addAll(dropsFor(engine.getDimension(), brokenKey, resolved, world)); } LootItems items = new LootItems(world.resources().items(), false); List drops = new ArrayList<>(); - providers.forEach(provider -> provider.fillDrops(items, drops)); - return new Result(drops, providers.stream().anyMatch(IrisBlockDrops::isReplaceVanillaDrops)); + providers.forEach(provider -> fillDrops(provider.drop(), items, drops)); + return new Result(drops, providers.stream().anyMatch(provider -> provider.drop().replaceVanillaDrops())); } - private static List dropsFor(KList candidates, PlatformBlockState block, Engine engine) { - return new KList<>(candidates.stream().filter(drops -> drops.shouldDropFor(block, engine.getData())).toList()); + /** Adds the items of the drops that pass their rarity to {@code into}. */ + private static void fillDrops(BlockDrop drop, LootItems items, List into) { + for (LootEntry entry : drop.drops()) { + if (!LootResolver.oneIn(RNG.r, entry.rarity())) { + continue; + } + ItemDrop given = items.give(entry, RNG.r); + if (given != null) { + into.add(given); + } + } + } + + private static List dropsFor(IrisRegistrant owner, String brokenKey, ResolvedDrops resolved, PackWorld world) { + List matching = new ArrayList<>(); + for (BlockDrop drop : owner.getModuleSettings().find(BlockDropSettings.class).map(BlockDropSettings::drops).orElse(List.of())) { + ResolvedBlockDrop candidate = resolved.of(drop, world); + if (candidate.dropsFor(brokenKey)) { + matching.add(candidate); + } + } + return matching; + } + + /** The drops of the world with their blocks resolved, once per drop. */ + private static final class ResolvedDrops { + private final ConcurrentMap byDrop = new ConcurrentHashMap<>(); + + private ResolvedBlockDrop of(BlockDrop drop, PackWorld world) { + return byDrop.computeIfAbsent(drop, key -> ResolvedBlockDrop.of(key, world.resources().blocks())); + } } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 3613ff1cb..94af45f91 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -18,22 +18,22 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.framework.PlacedObject; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.iris.engine.object.loot.IrisVanillaLootTable; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; import com.volmit.service.Loot; import com.volmit.world.PackWorld; +import java.util.ArrayList; import java.util.List; +import java.util.Set; /** * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the @@ -47,36 +47,42 @@ public final class LootGiving implements Loot { int x = site.position().x(); int z = site.position().z(); int relativeY = site.position().y(); - RNG rng = LootResolver.containerRng(lootSeed(engine), x, relativeY + engine.getMinHeight(), z); + int worldY = relativeY + engine.getMinHeight(); + RNG rng = LootResolver.containerRng(lootSeed(engine), x, worldY, z); - List tables = new KList<>(); + List sources = new ArrayList<>(); boolean objectLootDefined = site.nativeLootDefined(); IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z); if (placement != null) { objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty(); - IrisLootTable table = placement.getTable(platformState(site), engine.getData(), rng); - if (table != null) { - tables.add(table); + Source picked = placementLoot(world, engine).pick(placement, platformState(site), rng, x, worldY, z); + if (picked != null) { + sources.add(picked); if (placement.isOverrideGlobalLoot()) { - return sourcesOf(engine, site, List.of(table)); + return sources; } } } - LootTables.resolveEnvironmentSources(tables, engine, rng, x, relativeY, z, objectLootDefined, table -> table); - return sourcesOf(engine, site, tables); + LootTables.resolveEnvironmentSources(sources, engine, rng, x, relativeY, z, objectLootDefined, Table::new); + return sources; } @Override public List items(PackWorld world, Site site, String key) { Engine engine = engine(world); - IrisLootTable table = LootResources.table(engine.getData(), key); + LootTable table = LootResources.table(engine.getData(), key); if (table == null) { return List.of(); } int worldY = site.position().y() + engine.getMinHeight(); return new LootItems(world.resources().items(), site.debug()) - .draw(table, lootSeed(engine), site.position().x(), worldY, site.position().z()); + .draw(key, table, lootSeed(engine), site.position().x(), worldY, site.position().z()); + } + + private static PlacementLoot placementLoot(PackWorld world, Engine engine) { + PlatformLootTables platformTables = world.state(PlatformLootTables.class, ignored -> new PlatformLootTables()); + return new PlacementLoot(engine.getData(), platformTables::keys, lootSeed(engine)); } private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) { @@ -84,22 +90,6 @@ public final class LootGiving implements Loot { return placed == null ? null : placed.getPlacement(); } - private static List sourcesOf(Engine engine, Site site, List tables) { - int worldY = site.position().y() + engine.getMinHeight(); - List sources = new KList<>(); - for (IrisLootTable table : tables) { - if (table instanceof IrisVanillaLootTable vanilla) { - long seed = LootTables.seed(lootSeed(engine), vanilla, site.position().x(), worldY, site.position().z()); - sources.add(new PlatformTable(vanilla.getLootTableKey(), seed)); - continue; - } - if (table != null && table.getLoadKey() != null) { - sources.add(new Table(table.getLoadKey())); - } - } - return sources; - } - private static PlatformBlockState platformState(Site site) { return IrisPlatforms.get().registries().block(site.container().key()); } @@ -111,4 +101,18 @@ public final class LootGiving implements Loot { private static Engine engine(PackWorld world) { return IrisPackWorld.of(world).engine(); } + + /** The loot table keys of the platform, which do not change while a world runs. */ + private static final class PlatformLootTables { + private volatile Set keys; + + private Set keys() { + Set known = keys; + if (known == null) { + known = PlacementLoot.platformTableKeys(); + keys = known; + } + return known; + } + } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java index d1b3247d5..1c2300261 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootItems.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.loot.ItemAttributeModifier; +import art.arcane.iris.builtin.loot.LootEnchantment; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootSlot; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.engine.object.loot.IrisEnchantment; -import art.arcane.iris.engine.object.loot.InventorySlotType; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; @@ -54,26 +54,28 @@ public final class LootItems { } /** - * The items {@code table} gives at the spot {@code x}, {@code y}, {@code z} (world coordinates): picks entries - * from the table's own random stream until it has the number of items the table asks for or runs out of tries. + * The items {@code table}, which the pack names {@code tableKey}, gives at the spot {@code x}, {@code y}, {@code z} + * (world coordinates): picks entries from the table's own random stream until it has the number of items the table + * asks for or runs out of tries. */ - public List draw(IrisLootTable table, long lootSeed, int x, int y, int z) { + public List draw(String tableKey, LootTable table, long lootSeed, int x, int y, int z) { List drops = new ArrayList<>(); - List entries = table.getLoot(); - if (entries.isEmpty() || table.getMaxTries() <= 0) { + List entries = table.loot(); + if (entries.isEmpty() || table.maxTries() <= 0) { return drops; } - RNG rng = LootTables.rng(lootSeed, table, x, y, z); - int wanted = Math.max(0, LootResolver.inclusive(rng, table.getMinPicked(), table.getMaxPicked())); + String identity = LootTables.identity(tableKey); + RNG rng = LootTables.rng(lootSeed, identity, x, y, z); + int wanted = Math.max(0, LootResolver.inclusive(rng, table.minPicked(), table.maxPicked())); int tries = 0; - while (drops.size() < wanted && tries++ < table.getMaxTries()) { + while (drops.size() < wanted && tries++ < table.maxTries()) { int index = rng.nextInt(entries.size()); - IrisLoot entry = entries.get(index); - if (entry == null || entry.getSlotTypes() != InventorySlotType.STORAGE) { + LootEntry entry = entries.get(index); + if (entry == null || entry.slotTypes() != LootSlot.STORAGE) { continue; } - ItemDrop drop = drawEntry(entry, table, rng, lootSeed, index, x, y, z); + ItemDrop drop = drawEntry(entry, table, identity, rng, lootSeed, index, x, y, z); if (drop != null) { drops.add(drop); } @@ -82,66 +84,67 @@ public final class LootItems { } /** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */ - public ItemDrop give(IrisLoot entry, RNG rng) { + public ItemDrop give(LootEntry entry, RNG rng) { return resolve(entry, rng, null); } - private ItemDrop drawEntry(IrisLoot entry, IrisLootTable table, RNG rng, long lootSeed, int index, int x, int y, int z) { - long combinedRarity = LootResolver.combinedRarity(entry.getRarity(), table.getRarity()); - if (!LootTables.spatialOneIn(lootSeed, table, index, x, y, z, combinedRarity)) { + private ItemDrop drawEntry(LootEntry entry, LootTable table, String identity, RNG rng, long lootSeed, int index, int x, int y, int z) { + long combinedRarity = LootResolver.combinedRarity(entry.rarity(), table.rarity()); + if (!LootTables.spatialOneIn(lootSeed, identity, index, x, y, z, combinedRarity)) { return null; } return resolve(entry, rng, table); } - private ItemDrop resolve(IrisLoot entry, RNG rng, IrisLootTable table) { - String type = entry.getTypeKey(); + private ItemDrop resolve(LootEntry entry, RNG rng, LootTable table) { + String type = entry.type(); OptionalInt maxDurability = items.maxDurability(type); if (maxDurability.isEmpty() || isAir(type)) { return null; } - int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.getMinAmount(), entry.getMaxAmount())); + int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.minAmount(), entry.maxAmount())); List enchantments = drawEnchantments(entry, rng); List attributes = drawAttributes(entry, rng); - Double damage = maxDurability.getAsInt() > 0 ? 1D - rng.d(entry.getMinDurability(), entry.getMaxDurability()) : null; - return new ItemDrop(type, amount, entry.getDisplayName(), entry.getLore(), enchantments, attributes, - entry.isUnbreakable(), entry.getItemFlags(), entry.getCustomModel(), damage, entry.getLeatherColor(), - entry.getDyeColorKey(), entry.getCustomNbt(), debug ? sourceOf(entry, table) : null); + Double damage = maxDurability.getAsInt() > 0 ? 1D - rng.d(entry.minDurability(), entry.maxDurability()) : null; + return new ItemDrop(type, amount, entry.displayName(), entry.lore(), enchantments, attributes, + entry.unbreakable(), entry.itemFlags(), entry.customModel(), damage, entry.leatherColor(), + entry.dyeColor(), entry.customNbt(), debug ? sourceOf(entry, table) : null); } - private static List drawEnchantments(IrisLoot entry, RNG rng) { + private static List drawEnchantments(LootEntry entry, RNG rng) { List enchantments = new ArrayList<>(); - for (IrisEnchantment enchantment : entry.getEnchantments()) { - String key = enchantment.getEnchantment(); - if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.getChance()) { + for (LootEnchantment enchantment : entry.enchantments()) { + String key = enchantment.enchantment(); + if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.chance()) { continue; } - enchantments.add(new ItemEnchantment(key, Math.max(1, enchantment.getLevel(rng)))); + int level = LootResolver.inclusive(rng, enchantment.minLevel(), enchantment.maxLevel()); + enchantments.add(new ItemEnchantment(key, Math.max(1, level))); } return enchantments; } - private static List drawAttributes(IrisLoot entry, RNG rng) { + private static List drawAttributes(LootEntry entry, RNG rng) { List attributes = new ArrayList<>(); - for (IrisAttributeModifier modifier : entry.getAttributes()) { - if (rng.nextDouble() >= modifier.getChance()) { + for (ItemAttributeModifier modifier : entry.attributes()) { + if (rng.nextDouble() >= modifier.chance()) { continue; } - String attribute = modifier.getAttribute(); + String attribute = modifier.attribute(); if (attribute == null || attribute.isBlank()) { continue; } - attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng))); + attributes.add(new ItemAttribute(attribute, modifier.name(), modifier.operation(), rng.d(modifier.minAmount(), modifier.maxAmount()))); } return attributes; } - private static ItemDrop.Source sourceOf(IrisLoot entry, IrisLootTable table) { + private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table) { if (table == null) { - return new ItemDrop.Source(null, 0, entry.getRarity()); + return new ItemDrop.Source(null, 0, entry.rarity()); } - return new ItemDrop.Source(table.getName(), table.getRarity(), entry.getRarity()); + return new ItemDrop.Source(table.name(), table.rarity(), entry.rarity()); } private static boolean isAir(String type) { diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index 939bcccb7..aa2041db9 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.loot.BlockDropSettings; +import art.arcane.iris.builtin.loot.LootSettings; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -26,9 +28,10 @@ import com.volmit.service.Loot; import com.volmit.stage.StageGraph; /** - * Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}) and the items they and the block drops - * of the dimension, regions and biomes give. It checks the tables and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when a container is filled and through - * {@link BlockDrops} when a player breaks a block. + * Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}), the {@link LootSettings} and + * {@link BlockDropSettings} that dimensions, regions and biomes declare, and the items they give. It checks the tables + * and the references to them ({@link LootValidator}). It has no generation stage; Iris asks it through {@link Loot} when + * a container is filled and through {@link BlockDrops} when a player breaks a block. */ public final class LootModule implements IrisModule { private static final String VERSION = "built-in"; @@ -44,6 +47,8 @@ public final class LootModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + registry.registerSettings(LootSettings.class); + registry.registerSettings(BlockDropSettings.class); LootResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new LootValidator()); registry.registerService(Loot.class, new LootGiving()); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootResources.java b/src/main/java/art/arcane/iris/engine/loot/LootResources.java index 3c0a8faa1..b21985205 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootResources.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootResources.java @@ -18,10 +18,9 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisPackResources; -import art.arcane.iris.engine.object.loot.IrisLootTable; -import art.arcane.volmlib.util.collection.KList; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; @@ -37,7 +36,7 @@ import java.util.List; */ public final class LootResources { /** Loot tables, in {@code loot/}. */ - public static final ResourceKind TABLES = ResourceKind.of("iris:loot/table", "loot", IrisLootTable.class); + public static final ResourceKind TABLES = ResourceKind.of("iris:loot/table", "loot", LootTable.class); private LootResources() { } @@ -47,7 +46,7 @@ public final class LootResources { return List.of(TABLES); } - public static IrisLootTable table(IrisData data, String key) { + public static LootTable table(IrisData data, String key) { if (key == null || key.isBlank()) { return null; } @@ -59,18 +58,6 @@ public final class LootResources { } } - /** The tables of the pack named by {@code keys}, in order, without the ones the pack lacks. */ - public static KList tables(IrisData data, List keys) { - KList tables = new KList<>(); - for (String key : keys) { - IrisLootTable table = table(data, key); - if (table != null) { - tables.add(table); - } - } - return tables; - } - /** The key of every loot table of the pack, in key order. */ public static List tableKeys(IrisData data) { return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList(); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java index 021c3c2b1..c1d0cb067 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootTables.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -18,14 +18,13 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.loot.LootMode; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.object.loot.IrisLootMode; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; 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 art.arcane.volmlib.util.math.RNG; import java.util.List; @@ -34,42 +33,46 @@ import java.util.function.Function; /** * Which loot tables a place in the world draws from, and the random streams that draw from them: the part of loot - * that reads the pack's tables, loot references and layout. The streams themselves are - * {@link LootResolver}'s; here a table is named by its {@linkplain #identity identity}. + * that reads the pack's tables, loot settings and layout. The streams themselves are {@link LootResolver}'s; here a + * table is named by its {@linkplain #identity identity}, the key the pack names it by. */ public final class LootTables { + private static final String VANILLA_IDENTITY_PREFIX = "Vanilla "; + private LootTables() { } - /** What names a table in the random streams: its key, else its name. */ - public static String identity(IrisLootTable table) { - if (table == null) { - return ""; - } - String loadKey = table.getLoadKey(); - if (loadKey != null && !loadKey.isBlank()) { - return loadKey; - } - String name = table.getName(); - return name == null ? "" : name; + /** What names a table in the random streams: the key a pack table is named by. */ + public static String identity(String tableKey) { + return tableKey; } - public static RNG rng(long lootSeed, IrisLootTable table, int x, int y, int z) { - return LootResolver.tableRng(lootSeed, identity(table), x, y, z); + /** What names a table of the platform in the random streams. */ + public static String platformIdentity(String platformKey) { + return VANILLA_IDENTITY_PREFIX + platformKey; } - public static long seed(long lootSeed, IrisLootTable table, int x, int y, int z) { - return LootResolver.tableSeed(lootSeed, identity(table), x, y, z); + public static RNG rng(long lootSeed, String identity, int x, int y, int z) { + return LootResolver.tableRng(lootSeed, identity, x, y, z); } - public static boolean spatialOneIn(long lootSeed, IrisLootTable table, int entryIndex, int x, int y, int z, long rarity) { - return LootResolver.spatialOneIn(lootSeed, identity(table), entryIndex, x, y, z, rarity); + public static long seed(long lootSeed, String identity, int x, int y, int z) { + return LootResolver.tableSeed(lootSeed, identity, x, y, z); + } + + public static boolean spatialOneIn(long lootSeed, String identity, int entryIndex, int x, int y, int z, long rarity) { + return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity); + } + + /** The loot settings a dimension, region or biome declares; the defaults, which add nothing, when it declares none. */ + public static LootSettings settingsOf(IrisRegistrant owner) { + return owner.getModuleSettings().find(LootSettings.class).orElseGet(LootSettings::new); } /** * Adds the tables of the dimension, the region, the surface biome and (below the surface) the cave biome at a - * column to {@code sources}, as their loot references say, then scales their number by the areas' multipliers. - * {@code mapper} turns a table into the caller's own source; a null result skips it. + * column to {@code sources}, as their loot settings say, then scales their number by the areas' multipliers. + * {@code mapper} turns the key of a table into the caller's own source; a null result skips it. */ public static void resolveEnvironmentSources( List sources, @@ -79,7 +82,7 @@ public final class LootTables { int relativeY, int z, boolean objectLootDefined, - Function mapper + Function mapper ) { IrisRegion region = engine.getComplex().getRegionStream().get(x, z); IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z); @@ -91,20 +94,21 @@ public final class LootTables { contextualBiome = surfaceBiome; } + LootSettings dimensionLoot = settingsOf(engine.getDimension()); + LootSettings regionLoot = settingsOf(region); + LootSettings surfaceLoot = settingsOf(surfaceBiome); boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome); - double multiplier = engine.getDimension().getLoot().getMultiplier() - * region.getLoot().getMultiplier() - * surfaceBiome.getLoot().getMultiplier(); + double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier(); if (distinctContextualBiome) { - multiplier *= contextualBiome.getLoot().getMultiplier(); + multiplier *= settingsOf(contextualBiome).multiplier(); } boolean fallback = !objectLootDefined; - injectReference(sources, engine.getDimension().getLoot(), engine, mapper, fallback); - injectReference(sources, region.getLoot(), engine, mapper, fallback); - injectReference(sources, surfaceBiome.getLoot(), engine, mapper, fallback); + injectReference(sources, dimensionLoot, engine, mapper, fallback); + injectReference(sources, regionLoot, engine, mapper, fallback); + injectReference(sources, surfaceLoot, engine, mapper, fallback); if (distinctContextualBiome) { - injectReference(sources, contextualBiome.getLoot(), engine, mapper, fallback); + injectReference(sources, settingsOf(contextualBiome), engine, mapper, fallback); } LootResolver.scaleSources(sources, multiplier, rng); } @@ -113,17 +117,17 @@ public final class LootTables { public static void injectSources( List sources, List additions, - IrisLootMode mode, + LootMode mode, boolean fallback ) { - if (mode == IrisLootMode.FALLBACK && !fallback) { + if (mode == LootMode.FALLBACK && !fallback) { return; } - if (mode == IrisLootMode.CLEAR) { + if (mode == LootMode.CLEAR) { sources.clear(); return; } - if (mode == IrisLootMode.REPLACE) { + if (mode == LootMode.REPLACE) { sources.clear(); } sources.addAll(additions); @@ -141,22 +145,16 @@ public final class LootTables { private static void injectReference( List sources, - IrisLootReference reference, + LootSettings loot, Engine engine, - Function mapper, + Function mapper, boolean fallback ) { - KList tables = reference.getLootTables(engine.getComplex()); - KList additions = new KList<>(); - for (IrisLootTable table : tables) { - if (table == null) { - continue; - } - T source = mapper.apply(table); - if (source != null) { - additions.add(source); - } - } - injectSources(sources, additions, reference.getMode(), fallback); + List additions = loot.tables().stream() + .filter(key -> LootResources.table(engine.getData(), key) != null) + .map(mapper) + .filter(Objects::nonNull) + .toList(); + injectSources(sources, additions, loot.mode(), fallback); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java index e5f256fcb..cb4fef3d0 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -21,9 +21,9 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.core.modules.IrisValidationContext; import art.arcane.iris.core.pack.PackIntegerChecks; import art.arcane.iris.core.pack.PackValidationIo; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.loot.IrisLootReference; -import art.arcane.iris.engine.object.loot.IrisLootTable; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; import com.volmit.validation.Problem; @@ -162,9 +162,9 @@ public final class LootValidator implements Validator { PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors); PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors); PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors); - PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, IrisLootTable.MAX_PICKED, blockingErrors); - PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, IrisLootTable.MAX_PICKED, blockingErrors); - PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, IrisLootTable.MAX_TRIES, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, LootTable.MAX_PICKED, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, LootTable.MAX_PICKED, blockingErrors); + PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, LootTable.MAX_TRIES, blockingErrors); PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors); JSONArray entries = table.optJSONArray("loot"); @@ -189,8 +189,8 @@ public final class LootValidator implements Validator { PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors); PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors); PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors); - PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); - PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, IrisLoot.MAX_AMOUNT, blockingErrors); + PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, LootEntry.MAX_AMOUNT, blockingErrors); + PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, LootEntry.MAX_AMOUNT, blockingErrors); PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount, entryPath + ".maxAmount", maximumAmount, blockingErrors); validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors); @@ -256,9 +256,9 @@ public final class LootValidator implements Validator { if (!(rawMultiplier instanceof Number multiplier) || !Double.isFinite(multiplier.doubleValue()) || multiplier.doubleValue() < 0D - || multiplier.doubleValue() > IrisLootReference.MAX_MULTIPLIER) { + || multiplier.doubleValue() > LootSettings.MAX_MULTIPLIER) { blockingErrors.add(path + ".multiplier must be a finite number from 0 to " - + (int) IrisLootReference.MAX_MULTIPLIER + "."); + + (int) LootSettings.MAX_MULTIPLIER + "."); } } if (!reference.has("tables")) { diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java new file mode 100644 index 000000000..18ef3d37f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -0,0 +1,153 @@ +/* + * 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.loot; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.engine.object.loot.IObjectLoot; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.service.Loot; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * The loot table an object placement gives to one of its containers: the placement's tables and the platform's own, + * each with the blocks it applies to and a weight. A table that names the container's exact block wins over one that + * names the container's kind of block, which wins over one that names no blocks; among equals the weights pick. + */ +final class PlacementLoot { + private static final String VANILLA_NAMESPACE = "minecraft:"; + private static final char NAMESPACE_SEPARATOR = ':'; + private static final char PROPERTIES_START = '['; + + private final IrisData data; + private final Supplier> platformTables; + private final long lootSeed; + + /** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */ + PlacementLoot(IrisData data, Supplier> platformTables, long lootSeed) { + this.data = data; + this.platformTables = platformTables; + this.lootSeed = lootSeed; + } + + /** The platform's loot table keys, which a placement may name, in the form a placement names them. */ + static Set platformTableKeys() { + return Set.copyOf(IrisPlatforms.get().registries().lootTableKeys()); + } + + /** + * The table the placement gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, + * {@code z}; null when it gives it none. + */ + Loot.Source pick(IrisObjectPlacement placement, PlatformBlockState container, RNG rng, int x, int worldY, int z) { + Candidates candidates = new Candidates(container); + add(candidates, placement.getVanillaLoot(), name -> platformSource(name, x, worldY, z)); + add(candidates, placement.getLoot(), this::packSource); + List pool = candidates.pool(); + Candidate picked = LootResolver.pickWeighted(pool, Candidate::weight, rng); + return picked == null ? null : picked.source(); + } + + private void add(Candidates candidates, List entries, Function sourceOf) { + for (IObjectLoot entry : entries) { + if (entry == null || entry.getWeight() <= 0) { + continue; + } + Loot.Source source = sourceOf.apply(entry.getName()); + if (source == null) { + IrisLogging.warn("Couldn't find loot table " + entry.getName()); + continue; + } + candidates.add(entry, data, new Candidate(source, entry.getWeight())); + } + } + + private Loot.Source packSource(String key) { + return LootResources.table(data, key) == null ? null : new Loot.Table(key); + } + + private Loot.Source platformSource(String name, int x, int worldY, int z) { + String key = platformKey(name); + if (key == null || !platformTables.get().contains(key)) { + return null; + } + return new Loot.PlatformTable(key, LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z)); + } + + /** A placement's name for a platform table as the platform's key for it, or null for a name that cannot be one. */ + static String platformKey(String name) { + if (name == null || name.isBlank()) { + return null; + } + return name.indexOf(NAMESPACE_SEPARATOR) < 0 ? VANILLA_NAMESPACE + name : name; + } + + private record Candidate(Loot.Source source, int weight) { + } + + /** The candidates for one container, in the groups the placement gives them. */ + private static final class Candidates { + private final String containerKey; + private final String containerMaterial; + private final List exact = new ArrayList<>(); + private final List basic = new ArrayList<>(); + private final List global = new ArrayList<>(); + + private Candidates(PlatformBlockState container) { + this.containerKey = container.key(); + this.containerMaterial = materialOf(containerKey); + } + + void add(IObjectLoot entry, IrisData data, Candidate candidate) { + List filter = entry.getFilter(data); + if (filter.isEmpty()) { + global.add(candidate); + return; + } + for (PlatformBlockState filterState : filter) { + if (entry.isExact() && filterState.key().equals(containerKey)) { + exact.add(candidate); + } else if (!entry.isExact() && materialOf(filterState.key()).equals(containerMaterial)) { + basic.add(candidate); + } + } + } + + List pool() { + if (!exact.isEmpty()) { + return exact; + } + return basic.isEmpty() ? global : basic; + } + + private static String materialOf(String blockKey) { + int properties = blockKey.indexOf(PROPERTIES_START); + return properties < 0 ? blockKey : blockKey.substring(0, properties); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java b/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java new file mode 100644 index 000000000..d42367c31 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java @@ -0,0 +1,72 @@ +/* + * 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.loot; + +import art.arcane.iris.builtin.loot.BlockDrop; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockSpec; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** A {@link BlockDrop} with the blocks it names resolved to the platform's: which broken blocks it drops for. */ +final class ResolvedBlockDrop { + private static final char PROPERTIES_START = '['; + + private final BlockDrop drop; + private final boolean exact; + private final Set blocks; + + private ResolvedBlockDrop(BlockDrop drop, Set blocks) { + this.drop = drop; + this.exact = drop.exactBlocks(); + this.blocks = blocks; + } + + /** @param blocks the pack's blocks, which the drop's block specs resolve against */ + static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) { + Set keys = new LinkedHashSet<>(); + for (BlockSpec spec : drop.blocks()) { + PlatformBlockState state = IrisPlatforms.get().registries().block(blocks.resolve(spec).key()); + if (state != null) { + keys.add(comparable(state.key(), drop.exactBlocks())); + } + } + return new ResolvedBlockDrop(drop, keys); + } + + BlockDrop drop() { + return drop; + } + + /** Whether the drop applies to {@code brokenKey}, the platform's key for the broken block: its exact state, or just its kind of block. */ + boolean dropsFor(String brokenKey) { + return blocks.contains(comparable(brokenKey, exact)); + } + + private static String comparable(String key, boolean exact) { + if (exact) { + return key; + } + int properties = key.indexOf(PROPERTIES_START); + return properties < 0 ? key : key.substring(0, properties); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java index 7f8e40b19..24f1568b0 100644 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java +++ b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListResource.java @@ -18,8 +18,6 @@ package art.arcane.iris.engine.object.annotations; -import art.arcane.iris.core.loader.IrisRegistrant; - import java.lang.annotation.Retention; import java.lang.annotation.Target; @@ -31,5 +29,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) public @interface RegistryListResource { - Class value(); + /** The class pack resources of the kind are read into: an Iris resource or the class of a module resource kind. */ + Class value(); } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java deleted file mode 100644 index b07f836ad..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEffect.java +++ /dev/null @@ -1,288 +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.entity; - -import art.arcane.iris.engine.object.marker.IrisCommandRegistry; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -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.RegistryListPotionEffect; -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.math.RNG; -import art.arcane.volmlib.util.scheduling.ChronoLatch; -import art.arcane.iris.util.common.data.registry.RegistryUtil; -import art.arcane.iris.util.common.scheduling.J; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.Particle; -import org.bukkit.Sound; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.util.Vector; - -@Snippet("effect") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("An iris effect") -@Data -public class IrisEffect { - private final transient AtomicCache pt = new AtomicCache<>(); - private final transient AtomicCache latch = new AtomicCache<>(); - private final transient AtomicCache particleEffectResolved = new AtomicCache<>(); - private final transient AtomicCache soundResolved = new AtomicCache<>(); - @RegistryListPotionEffect - @Desc("The potion effect to apply in this area") - private String potionEffect = ""; - @Desc("The particle effect to apply in the area") - private String particleEffect = null; - @DependsOn({"particleEffect"}) - @MinNumber(-32) - @MaxNumber(32) - @Desc("Randomly offset from the surface to this surface+value") - private int particleOffset = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltX = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltY = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltZ = 0; - @DependsOn({"particleEffect"}) - @Desc("Randomize the altX by -altX to altX") - private boolean randomAltX = true; - @DependsOn({"particleEffect"}) - @Desc("Randomize the altY by -altY to altY") - private boolean randomAltY = false; - @DependsOn({"particleEffect"}) - @Desc("Randomize the altZ by -altZ to altZ") - private boolean randomAltZ = true; - @Desc("The sound to play") - private String sound = null; - @DependsOn({"sound"}) - @MinNumber(0) - @MaxNumber(512) - @Desc("The max distance from the player the sound will play") - private int soundDistance = 12; - @DependsOn({"sound", "maxPitch"}) - @MinNumber(0.01) - @MaxNumber(1.99) - @Desc("The minimum sound pitch") - private double minPitch = 0.5D; - @DependsOn({"sound", "minVolume"}) - @MinNumber(0.01) - @MaxNumber(1.99) - @Desc("The max sound pitch") - private double maxPitch = 1.5D; - @DependsOn({"sound"}) - @MinNumber(0.001) - @MaxNumber(512) - @Desc("The sound volume.") - private double volume = 1.5D; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(512) - @Desc("The particle count. Try setting to zero for using the alt xyz to a motion value instead of an offset") - private int particleCount = 0; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(64) - @Desc("How far away from the player particles can play") - private int particleDistance = 20; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(128) - @Desc("How wide the particles can play (player's view left and right) RADIUS") - private int particleDistanceWidth = 24; - @DependsOn({"particleEffect"}) - @Desc("An extra value for some particles... Which bukkit doesn't even document.") - private double extra = 0; - @DependsOn({"potionEffect"}) - @MinNumber(-1) - @MaxNumber(1024) - @Desc("The Potion Strength or -1 to disable") - private int potionStrength = -1; - @DependsOn({"potionEffect", "potionTicksMin"}) - @MinNumber(1) - @Desc("The max time the potion will last for") - private int potionTicksMax = 155; - @DependsOn({"potionEffect", "potionTicksMax"}) - @MinNumber(1) - @Desc("The min time the potion will last for") - private int potionTicksMin = 75; - @Required - @MinNumber(0) - @Desc("The effect interval in milliseconds") - private int interval = 150; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(16) - @Desc("The effect distance start away") - private int particleAway = 5; - @Required - @MinNumber(1) - @Desc("The chance is 1 in CHANCE per interval") - private int chance = 50; - @Desc("Run commands, with configurable location parameters") - private IrisCommandRegistry commandRegistry = null; - - - public boolean canTick() { - return latch.aquire(() -> new ChronoLatch(interval)).flip(); - } - - public boolean shouldApplyNow() { - return canTick() && RNG.r.nextInt(chance) == 0; - } - - public String getParticleEffectKey() { - return particleEffect; - } - - public String getSoundKey() { - return sound; - } - - public Particle getParticleEffect() { - if (particleEffect == null) { - return null; - } - return particleEffectResolved.aquire(() -> resolveKeyed(Particle.class, particleEffect)); - } - - public Sound getSound() { - if (sound == null) { - return null; - } - return soundResolved.aquire(() -> resolveKeyed(Sound.class, sound)); - } - - private static T resolveKeyed(Class type, String key) { - NamespacedKey namespacedKey = NamespacedKey.fromString(key); - return namespacedKey == null ? null : RegistryUtil.lookup(type).get(namespacedKey); - } - - public PotionEffectType getRealType() { - return pt.aquire(() -> - { - if (getPotionEffect() == null || getPotionEffect().isEmpty()) { - return PotionEffectType.LUCK; - } - - try { - PotionEffectType resolved = PotionEffectTypes.resolve(getPotionEffect()); - if (resolved != null) { - return resolved; - } - } catch (Throwable e) { - IrisLogging.reportError(e); - } - - if (PotionEffectTypes.shouldWarn(getPotionEffect())) { - IrisLogging.warn("Unknown Potion Effect Type: \"" + getPotionEffect() + "\". Valid types: " + PotionEffectTypes.knownTypesList()); - } - - return PotionEffectType.LUCK; - }); - } - - private static final class BukkitFx { - private static void run(Player p, Runnable r) { - J.runEntity(p, r); - } - } - - public void apply(Player p, Engine g) { - if (!shouldApplyNow()) { - return; - } - - BukkitFx.run(p, () -> { - Sound soundType = getSound(); - Particle particleType = getParticleEffect(); - if (soundType != null) { - Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); - p.playSound(part, soundType, (float) volume, (float) RNG.r.d(minPitch, maxPitch)); - } - - if (particleType != null) { - Location part = p.getLocation().clone().add(p.getLocation().getDirection().clone().multiply(RNG.r.i(particleDistance) + particleAway)).clone().add(p.getLocation().getDirection().clone().rotateAroundY(Math.toRadians(90)).multiply(RNG.r.d(-particleDistanceWidth, particleDistanceWidth))); - - part.setY(Math.round(g.getHeight(part.getBlockX(), part.getBlockZ())) + 1); - part.add(RNG.r.d(), 0, RNG.r.d()); - int offset = p.getWorld().getMinHeight(); - if (extra != 0) { - p.spawnParticle(particleType, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), - part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ, - extra); - } else { - p.spawnParticle(particleType, part.getX(), part.getY() + offset + RNG.r.i(particleOffset), part.getZ(), - particleCount, - randomAltX ? RNG.r.d(-particleAltX, particleAltX) : particleAltX, - randomAltY ? RNG.r.d(-particleAltY, particleAltY) : particleAltY, - randomAltZ ? RNG.r.d(-particleAltZ, particleAltZ) : particleAltZ); - } - } - - if (commandRegistry != null) { - commandRegistry.run(p); - } - - if (potionStrength > -1) { - if (p.hasPotionEffect(getRealType())) { - PotionEffect e = p.getPotionEffect(getRealType()); - if (e != null && e.getAmplifier() > getPotionStrength()) { - return; - } - - p.removePotionEffect(getRealType()); - } - - p.addPotionEffect(new PotionEffect(getRealType(), - RNG.r.i(Math.min(potionTicksMax, potionTicksMin), - Math.max(potionTicksMax, potionTicksMin)), - getPotionStrength(), - true, false, false)); - } - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.java deleted file mode 100644 index 1332e3bf0..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisEntitySpawn.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.entity; - -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.marker.IrisMarker; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.annotations.Desc; -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.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("entity-spawn") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an entity spawn during initial chunk generation") -@Data -public class IrisEntitySpawn implements IRare { - private final transient AtomicCache rng = new AtomicCache<>(); - private final transient AtomicCache ent = new AtomicCache<>(); - @RegistryListResource(IrisEntity.class) - @Required - @Desc("The entity") - private String entity = ""; - @MinNumber(1) - @Desc("The 1 in RARITY chance for this entity to spawn") - private int rarity = 1; - @MinNumber(1) - @Desc("The minumum of this entity to spawn") - private int minSpawns = 1; - @MinNumber(1) - @Desc("The max of this entity to spawn") - private int maxSpawns = 1; - private transient IrisSpawner referenceSpawner; - private transient IrisMarker referenceMarker; - - public IrisEntity getRealEntity(Engine g) { - return ent.aquire(() -> SpawnResources.entity(g.getData(), getEntity())); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java b/src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java deleted file mode 100644 index f837f5cfd..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/IrisPotionEffect.java +++ /dev/null @@ -1,102 +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.entity; - -import art.arcane.iris.engine.data.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.RegistryListPotionEffect; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.spi.IrisLogging; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor - -@Snippet("potion-effect") -@Desc("An iris potion effect") -@Data -public class IrisPotionEffect { - private final transient AtomicCache pt = new AtomicCache<>(); - @Required - @RegistryListPotionEffect - @Desc("The potion effect to apply in this area") - private String potionEffect = ""; - @Required - @MinNumber(-1) - @MaxNumber(1024) - @Desc("The Potion Strength or -1 to disable") - private int strength = -1; - @Required - @MinNumber(1) - @Desc("The time the potion will last for") - private int ticks = 200; - @Desc("Is the effect ambient") - private boolean ambient = false; - @Desc("Is the effect showing particles") - private boolean particles = true; - - public PotionEffectType getRealType() { - return pt.aquire(() -> - { - if (getPotionEffect() == null || getPotionEffect().isEmpty()) { - return PotionEffectType.LUCK; - } - - try { - PotionEffectType resolved = PotionEffectTypes.resolve(getPotionEffect()); - if (resolved != null) { - return resolved; - } - } catch (Throwable e) { - IrisLogging.reportError(e); - } - - if (PotionEffectTypes.shouldWarn(getPotionEffect())) { - IrisLogging.warn("Unknown Potion Effect Type: \"" + getPotionEffect() + "\". Valid types: " + PotionEffectTypes.knownTypesList()); - } - - return PotionEffectType.LUCK; - }); - } - - public void apply(LivingEntity p) { - if (strength > -1) { - if (p.hasPotionEffect(getRealType())) { - PotionEffect e = p.getPotionEffect(getRealType()); - if (e.getAmplifier() > strength) { - return; - } - - p.removePotionEffect(getRealType()); - } - - p.addPotionEffect(new PotionEffect(getRealType(), ticks, strength, ambient, particles, false)); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java b/src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java deleted file mode 100644 index 7d2a55222..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/PotionEffectTypes.java +++ /dev/null @@ -1,98 +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.entity; - -import art.arcane.iris.util.common.reflect.KeyedType; -import org.bukkit.NamespacedKey; -import org.bukkit.Registry; -import org.bukkit.potion.PotionEffectType; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; - -public final class PotionEffectTypes { - private static final Map LEGACY_ALIASES; - private static final Set MISSING_WARNED = ConcurrentHashMap.newKeySet(); - - static { - Map m = new HashMap<>(); - m.put("SLOW", "SLOWNESS"); - m.put("FAST_DIGGING", "HASTE"); - m.put("SLOW_DIGGING", "MINING_FATIGUE"); - m.put("INCREASE_DAMAGE", "STRENGTH"); - m.put("HEAL", "INSTANT_HEALTH"); - m.put("HARM", "INSTANT_DAMAGE"); - m.put("JUMP", "JUMP_BOOST"); - m.put("CONFUSION", "NAUSEA"); - m.put("DAMAGE_RESISTANCE", "RESISTANCE"); - LEGACY_ALIASES = Collections.unmodifiableMap(m); - } - - private PotionEffectTypes() { - } - - public static String normalize(String input) { - if (input == null) { - return ""; - } - String upper = input.trim().toUpperCase(Locale.ROOT).replace(' ', '_'); - if (upper.contains(":")) { - upper = upper.substring(upper.indexOf(':') + 1); - } - return LEGACY_ALIASES.getOrDefault(upper, upper); - } - - public static PotionEffectType resolve(String rawName) { - if (rawName == null || rawName.trim().isEmpty()) { - return null; - } - String wanted = normalize(rawName); - for (PotionEffectType i : Registry.EFFECT) { - NamespacedKey key = KeyedType.getKey(i); - if (key == null) { - continue; - } - String candidate = key.getKey().toUpperCase(Locale.ROOT).replace(' ', '_'); - if (candidate.equals(wanted)) { - return i; - } - } - return null; - } - - public static String knownTypesList() { - TreeSet names = new TreeSet<>(); - for (PotionEffectType i : Registry.EFFECT) { - NamespacedKey key = KeyedType.getKey(i); - if (key != null) { - names.add(key.getKey().toUpperCase(Locale.ROOT).replace(' ', '_')); - } - } - return String.join(", ", names); - } - - public static boolean shouldWarn(String rawName) { - return MISSING_WARNED.add(normalize(rawName)); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java index 2f1049b29..0a1db5c1b 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java @@ -18,8 +18,6 @@ package art.arcane.iris.engine.object.entity.spawn; -import art.arcane.iris.engine.object.value.IrisRate; -import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.math.M; import lombok.Data; @@ -28,11 +26,11 @@ public class IrisEngineSpawnerCooldown { private long lastSpawn = 0; private String spawner; - public void spawn(Engine engine) { + public void spawn() { lastSpawn = M.ms(); } - public boolean canSpawn(IrisRate s) { - return M.ms() - lastSpawn > s.getInterval(); + public boolean canSpawn(long intervalMilliseconds) { + return M.ms() - lastSpawn > intervalMilliseconds; } } diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java deleted file mode 100644 index fdaad9401..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawner.java +++ /dev/null @@ -1,142 +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.entity.spawn; - -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.iris.engine.object.marker.IrisMarker; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.engine.object.value.IrisRate; -import art.arcane.iris.engine.object.world.IrisTimeBlock; -import art.arcane.iris.engine.object.world.IrisWeather; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisRegistrant; -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.spi.PlatformWorld; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@EqualsAndHashCode(callSuper = true) -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents an entity spawn during initial chunk generation") -@Data -public class IrisSpawner extends IrisRegistrant { - - private transient IrisMarker referenceMarker; - - @ArrayType(min = 1, type = IrisEntitySpawn.class) - @Desc("The entity spawns to add") - private KList spawns = new KList<>(); - - @ArrayType(min = 1, type = IrisEntitySpawn.class) - @Desc("The entity spawns to add initially. EXECUTES PER CHUNK!") - private KList initialSpawns = new KList<>(); - - @Desc("This spawner will not spawn in a given chunk if that chunk has more than the defined amount of living entities.") - private int maxEntitiesPerChunk = 1; - - @Desc("The block of 24 hour time to contain this spawn in.") - private IrisTimeBlock timeBlock = new IrisTimeBlock(); - - @Desc("The weather condition required for this spawner to fire.") - private IrisWeather weather = IrisWeather.ANY; - - @Desc("The maximum rate this spawner can fire") - private IrisRate maximumRate = new IrisRate(); - - @Desc("The maximum rate this spawner can fire on a specific chunk") - private IrisRate maximumRatePerChunk = new IrisRate(); - - @Desc("The light levels this spawn is allowed to run in (0-15 inclusive)") - private IrisRange allowedLightLevels = new IrisRange(0, 15); - - @Desc("Where should these spawns be placed") - private IrisSpawnGroup group = IrisSpawnGroup.NORMAL; - - public boolean isValid(IrisBiome biome) { - return switch (group) { - case NORMAL -> switch (biome.getInferredType()) { - case SHORE, SEA, CAVE -> false; - case LAND -> true; - }; - case CAVE -> true; - case UNDERWATER -> switch (biome.getInferredType()) { - case SHORE, LAND, CAVE -> false; - case SEA -> true; - }; - case BEACH -> switch (biome.getInferredType()) { - case SHORE -> true; - case LAND, CAVE, SEA -> false; - }; - }; - } - - public boolean isValid(PlatformWorld world) { - return timeBlock.isWithin(world) && weather.is(world); - } - - public boolean canSpawn(Engine engine) { - PlatformWorld world = engine.getWorld().platformWorld(); - if (world == null || !isValid(world)) - return false; - - IrisRate rate = getMaximumRate(); - return rate.isInfinite() || engine.getEngineData().getCooldown(this).canSpawn(rate); - } - - public boolean canSpawn(Engine engine, int x, int z) { - if (!canSpawn(engine)) - return false; - - IrisRate rate = getMaximumRatePerChunk(); - return rate.isInfinite() || engine.getEngineData().getChunk(x, z).getCooldown(this).canSpawn(rate); - } - - public void spawn(Engine engine) { - if (getMaximumRate().isInfinite()) - return; - - engine.getEngineData().getCooldown(this).spawn(engine); - } - - public void spawn(Engine engine, int x, int z) { - spawn(engine); - if (getMaximumRatePerChunk().isInfinite()) - return; - - engine.getEngineData().getChunk(x, z).getCooldown(this).spawn(engine); - } - - @Override - public String getFolderName() { - return "spawners"; - } - - @Override - public String getTypeName() { - return "Spawner"; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java index 7fdcb744a..7b12a24b6 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java @@ -1,5 +1,6 @@ package art.arcane.iris.engine.object.entity.spawn; +import art.arcane.iris.builtin.spawn.Spawner; import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; @@ -10,10 +11,6 @@ import lombok.NonNull; public class IrisSpawnerCooldowns { private final KMap cooldowns = new KMap<>(); - public IrisEngineSpawnerCooldown getCooldown(@NonNull IrisSpawner spawner) { - return getCooldown(spawner.getLoadKey()); - } - public IrisEngineSpawnerCooldown getCooldown(@NonNull String loadKey) { return cooldowns.computeIfAbsent(loadKey, k -> { IrisEngineSpawnerCooldown cd = new IrisEngineSpawnerCooldown(); @@ -24,8 +21,8 @@ public class IrisSpawnerCooldowns { public void cleanup(Engine engine) { cooldowns.values().removeIf(cd -> { - IrisSpawner sp = SpawnResources.spawner(engine.getData(), cd.getSpawner()); - return sp == null || cd.canSpawn(sp.getMaximumRate()); + Spawner spawner = SpawnResources.spawner(engine.getData(), cd.getSpawner()); + return spawner == null || cd.canSpawn(spawner.maximumRate().interval()); }); } diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java deleted file mode 100644 index c3c26608c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisBlockDrops.java +++ /dev/null @@ -1,105 +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.loot; - -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.framework.LootResolver; -import art.arcane.iris.engine.loot.LootItems; -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.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; -import com.volmit.item.ItemDrop; - -import java.util.List; - -@Snippet("block-drops") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a block drop list") -@Data -public class IrisBlockDrops { - private final transient AtomicCache> data = new AtomicCache<>(); - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The blocks that drop loot") - private KList blocks = new KList<>(); - @Desc("If exact blocks is set to true, minecraft:barrel[axis=x] will only drop for that axis. When exact is false (default) any barrel will drop the defined drops.") - private boolean exactBlocks = false; - @Desc("Add in specific items to drop") - @ArrayType(min = 1, type = IrisLoot.class) - private KList drops = new KList<>(); - @Desc("If this is in a biome, setting skipParents to true will ignore the drops in the region and dimension for this block type. The default (false) will allow all three nodes to fire and add to a list of drops.") - private boolean skipParents = false; - @Desc("Removes the default vanilla block drops and only drops the given items & any parent loot tables specified for this block type.") - private boolean replaceVanillaDrops = false; - - public boolean shouldDropFor(PlatformBlockState broken, IrisData rdata) { - KList list = this.data.aquire(() -> { - KList b = new KList<>(); - - for (IrisBlockData i : getBlocks()) { - PlatformBlockState state = i.getBlockData(rdata); - - if (state != null) { - b.add(state); - } - } - - return b.removeDuplicates(); - }); - - for (PlatformBlockState i : list) { - if (exactBlocks ? i.key().equals(broken.key()) : materialOf(i).equals(materialOf(broken))) { - return true; - } - } - - return false; - } - - /** Adds the items of the drops that pass their rarity to {@code d}. */ - public void fillDrops(LootItems items, List d) { - for (IrisLoot i : getDrops()) { - if (!LootResolver.oneIn(RNG.r, i.getRarity())) { - continue; - } - ItemDrop drop = items.give(i, RNG.r); - if (drop != null) { - d.add(drop); - } - } - } - - private static String materialOf(PlatformBlockState state) { - String key = state.key(); - int properties = key.indexOf('['); - return properties < 0 ? key : key.substring(0, properties); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java deleted file mode 100644 index 57f699664..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLoot.java +++ /dev/null @@ -1,113 +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.loot; - -import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -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.RegistryListItemType; -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.collection.KMap; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.ToString; -import lombok.experimental.Accessors; - -@Snippet("loot") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a loot entry") -@Data -@EqualsAndHashCode(doNotUseGetters = true) -@ToString(doNotUseGetters = true) -public class IrisLoot { - public static final int MAX_AMOUNT = 64; - - @Desc("The target inventory slot types to fill this loot with. World generation only ever fills STORAGE; the other values are inert during worldgen.") - private InventorySlotType slotTypes = InventorySlotType.STORAGE; - @MinNumber(1) - @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") - private int rarity = 1; - @MinNumber(1) - @MaxNumber(MAX_AMOUNT) - @Desc("Minimum amount of this loot, from 1 to 64") - private int minAmount = 1; - @MinNumber(1) - @MaxNumber(MAX_AMOUNT) - @Desc("Maximum amount of this loot, from 1 to 64") - private int maxAmount = 1; - @MinNumber(1) - @Desc("The display name of this item") - private String displayName = null; - @MinNumber(0) - @MaxNumber(1) - @Desc("Minimum durability percent") - private double minDurability = 0; - @MinNumber(0) - @MaxNumber(1) - @Desc("Maximum durability percent") - private double maxDurability = 1; - @Desc("Define a custom model identifier 1.14+ only") - private Integer customModel = null; - @Desc("Set this to true to prevent it from being broken") - private boolean unbreakable = false; - @ArrayType(min = 1, type = String.class) - @Desc("The item flags to add") - private KList itemFlags = new KList<>(); - @Desc("Apply enchantments to this item") - @ArrayType(min = 1, type = IrisEnchantment.class) - private KList enchantments = new KList<>(); - @Desc("Apply attribute modifiers to this item") - @ArrayType(min = 1, type = IrisAttributeModifier.class) - private KList attributes = new KList<>(); - @ArrayType(min = 1, type = String.class) - @Desc("Add lore to this item") - private KList lore = new KList<>(); - @RegistryListItemType - @Required - @Desc("This is the item or block type. Does not accept minecraft:*, only materials such as DIAMOND_SWORD or DIRT. The exception are modded materials, as they require a namespace.") - private String type = ""; - @Desc("The dye color") - private String dyeColor = null; - @Desc("The leather armor color") - private String leatherColor = null; - @Desc("Defines a custom NBT Tag for the item.") - private KMap customNbt; - - /** - * The authored item key, exactly as written in the pack. Each platform resolves it against its own item registry. - */ - public String getTypeKey() { - return type; - } - - /** - * The authored dye colour name, or null when unset. - */ - public String getDyeColorKey() { - return dyeColor; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.java deleted file mode 100644 index 598555154..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisLootReference.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.loot; - -import art.arcane.iris.engine.loot.LootResources; -import art.arcane.iris.engine.data.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.Snippet; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.common.data.DataProvider; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("loot-registry") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a loot entry") -@Data -public class IrisLootReference { - public static final double MAX_MULTIPLIER = 16D; - - private final transient AtomicCache> tt = new AtomicCache<>(); - @Desc("ADD = add on top of parent tables. REPLACE = clear parent tables, then add these. CLEAR = clear parent tables and add nothing, even if tables are listed. FALLBACK = only used when nothing else defined a table.") - private IrisLootMode mode = IrisLootMode.ADD; - @RegistryListResource(IrisLootTable.class) - @ArrayType(min = 1, type = String.class) - @Desc("Add loot table registries here") - private KList tables = new KList<>(); - @MinNumber(0) - @MaxNumber(MAX_MULTIPLIER) - @Desc("Scale loot sources in this area from 0 to 16 times their normal count") - private double multiplier = 1D; - - public KList getLootTables(DataProvider g) { - return tt.aquire(() -> - { - KList t = new KList<>(); - - for (String i : tables) { - t.add(LootResources.table(g.getData(), i)); - } - - return t; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java index ec5b70e77..076519f06 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.loot; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; @@ -50,7 +51,7 @@ public class IrisObjectLoot implements IObjectLoot { private boolean exact = false; @Desc("The loot table name") @Required - @RegistryListResource(IrisLootTable.class) + @RegistryListResource(LootTable.class) private String name; @Desc("The weight of this loot table being chosen") @MinNumber(1) diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java deleted file mode 100644 index d4a207804..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisVanillaLootTable.java +++ /dev/null @@ -1,73 +0,0 @@ -package art.arcane.iris.engine.object.loot; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.collection.KList; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.io.File; - -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisVanillaLootTable extends IrisLootTable { - /** - * The vanilla loot table key ("minecraft:chests/simple_dungeon"), not the LootTable itself. A - * raw org.bukkit.loot.LootTable field - and the constructor lombok would generate for it - makes - * every reflective walk over the IrisLootTable hierarchy (Gson, schema generation, the purity - * gate) resolve a Bukkit class. The host resolves the table when it pulls loot from it. The key text is - * identical to what {@code LootTable.getKey().toString()} produced before, so - * {@code LootTables.identity} (which falls back to - * {@link #getName()}) yields the same loot seed. - */ - private final String lootTableKey; - - @Override - public String getName() { - return "Vanilla " + lootTableKey; - } - - @Override - public int getRarity() { - return 0; - } - - @Override - public int getMaxPicked() { - return 0; - } - - @Override - public int getMinPicked() { - return 0; - } - - @Override - public int getMaxTries() { - return 0; - } - - @Override - public KList getLoot() { - return new KList<>(); - } - - @Override - public String getFolderName() { - throw new UnsupportedOperationException("VanillaLootTables do not have a folder name"); - } - - @Override - public String getTypeName() { - throw new UnsupportedOperationException("VanillaLootTables do not have a type name"); - } - - @Override - public File getLoadFile() { - throw new UnsupportedOperationException("VanillaLootTables do not have a load file"); - } - - @Override - public IrisData getLoader() { - throw new UnsupportedOperationException("VanillaLootTables do not have a loader"); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.java deleted file mode 100644 index 1d5ed6e25..000000000 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisCommandRegistry.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.marker; - -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.platform.bukkit.BukkitWorld; -import art.arcane.iris.spi.PlatformWorld; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -@Snippet("command-registry") -@Accessors(chain = true) -@NoArgsConstructor -@Desc("Represents a casting location for a command") -@Data -public class IrisCommandRegistry { - @Required - @ArrayType(min = 1, type = IrisCommand.class) - @Desc("Run commands, at the exact location of the player") - private KList rawCommands = new KList<>(); - @DependsOn({"rawCommands"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt x, usually represents motion if the particle count is zero. Otherwise an offset.") - private double commandOffsetX = 0; - @DependsOn({"rawCommands"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt y, usually represents motion if the particle count is zero. Otherwise an offset.") - private double commandOffsetY = 0; - @DependsOn({"rawCommands"}) - @MinNumber(-8) - @MaxNumber(8) - @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") - private double commandOffsetZ = 0; - @DependsOn({"rawCommands"}) - @Desc("Randomize the altX from -altX to altX") - private boolean commandRandomAltX = true; - @DependsOn({"rawCommands"}) - @Desc("Randomize the altY from -altY to altY") - private boolean commandRandomAltY = false; - @DependsOn({"rawCommands"}) - @Desc("Randomize the altZ from -altZ to altZ") - private boolean commandRandomAltZ = true; - @DependsOn({"rawCommands"}) - @Desc("Randomize location for all separate commands (true), or run all on the same location (false)") - private boolean commandAllRandomLocations = true; - - public void run(Player p) { - if (rawCommands.isNotEmpty()) { - PlatformWorld world = new BukkitWorld(p.getWorld()); - Location part = p.getLocation().clone().add( - commandRandomAltX ? RNG.r.d(-commandOffsetX, commandOffsetX) : commandOffsetX, - commandRandomAltY ? RNG.r.d(-commandOffsetY, commandOffsetY) : commandOffsetY, - commandRandomAltZ ? RNG.r.d(-commandOffsetZ, commandOffsetZ) : commandOffsetZ); - for (IrisCommand rawCommand : rawCommands) { - rawCommand.run(world, part.getBlockX(), part.getBlockY(), part.getBlockZ()); - if (commandAllRandomLocations) { - part = p.getLocation().clone().add( - commandRandomAltX ? RNG.r.d(-commandOffsetX, commandOffsetX) : commandOffsetX, - commandRandomAltY ? RNG.r.d(-commandOffsetY, commandOffsetY) : commandOffsetY, - commandRandomAltZ ? RNG.r.d(-commandOffsetZ, commandOffsetZ) : commandOffsetZ); - } - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java index 580ce1212..f61e8b998 100644 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.marker; +import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; @@ -54,7 +55,7 @@ public class IrisObjectMarker { @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") private boolean exact = false; @Required - @RegistryListResource(IrisMarker.class) + @RegistryListResource(SpawnMarker.class) @Desc("The marker to add") private String marker; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 169edfde5..d04debcb6 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -28,7 +28,7 @@ import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.core.modules.BlockEntities; import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.object.marker.IrisMarker; +import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.engine.object.marker.IrisObjectMarker; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectShaping; @@ -205,7 +205,7 @@ public final class BlocksModule implements IrisModule { RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; for (IrisObjectMarker markerConfig : config.getMarkers()) { - IrisMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker()); + SpawnMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker()); int markerSalt = salt++; if (marker == null) { continue; @@ -216,7 +216,7 @@ public final class BlocksModule implements IrisModule { if (remaining <= 0) { break; } - if (!marker.isEmptyAbove() || hasAirAbove(world, position)) { + if (!marker.emptyAbove() || hasAirAbove(world, position)) { context.access().marker(ObjectMarkers.of(position, markerConfig.getMarker())); remaining--; } 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 index ee0075335..bfb28ac4a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.engine.loot.LootResources; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; @@ -28,11 +27,8 @@ 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.engine.object.loot.IObjectLoot; -import art.arcane.iris.engine.object.loot.IrisLootTable; import art.arcane.iris.engine.object.loot.IrisObjectLoot; import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; -import art.arcane.iris.engine.object.loot.IrisVanillaLootTable; import art.arcane.iris.engine.object.marker.IrisObjectMarker; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.IrisNoiseGenerator; @@ -42,13 +38,10 @@ 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.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.data.cache.LazyBoundedCache; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.ArrayType; import art.arcane.iris.engine.object.annotations.Desc; import art.arcane.iris.engine.object.annotations.MaxNumber; @@ -56,10 +49,7 @@ 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.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.DataProvider; import art.arcane.volmlib.util.math.RNG; import art.arcane.iris.util.project.noise.CNG; @@ -73,14 +63,9 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; import org.bukkit.TreeType; -import org.bukkit.block.data.BlockData; import org.jetbrains.annotations.Nullable; -import java.util.Optional; -import java.util.function.Function; @Snippet("object-placer") @EqualsAndHashCode() @@ -204,7 +189,6 @@ public class IrisObjectPlacement { @Desc("Ignore any placement restrictions for this object") @SerializedName(value = "forcePlace", alternate = {"force"}) private boolean forcePlace = false; - private transient AtomicCache cache = new AtomicCache<>(); /** The pack modules' settings this placement declares, decoded with it. */ private transient ModuleSettings moduleSettings = ModuleSettings.NONE; @@ -313,96 +297,6 @@ public class IrisObjectPlacement { return (int) Math.round(densityStyle.get(rng, x, z, data)); } - private TableCache getCache(IrisData manager) { - return cache.aquire(() -> { - TableCache cache = new TableCache(); - - cache.merge(getCache(manager, getVanillaLoot(), IrisObjectPlacement::getVanillaTable)); - cache.merge(getCache(manager, getLoot(), key -> LootResources.table(manager, key))); - - return cache; - }); - } - - private TableCache getCache(IrisData manager, KList list, Function loader) { - TableCache tc = new TableCache(); - - for (IObjectLoot loot : list) { - if (loot == null || loot.getWeight() <= 0) - continue; - IrisLootTable table = loader.apply(loot.getName()); - if (table == null) { - IrisLogging.warn("Couldn't find loot table " + loot.getName()); - continue; - } - - if (loot.getFilter().isEmpty()) //Table applies to all containers - { - tc.global.put(table, loot.getWeight()); - } else if (!loot.isExact()) //Table is meant to be by type - { - for (PlatformBlockState filterState : loot.getFilter(manager)) { - BlockData filterData = (BlockData) filterState.nativeHandle(); - if (!tc.basic.containsKey(filterData.getMaterial())) { - tc.basic.put(filterData.getMaterial(), new WeightedTables()); - } - - tc.basic.get(filterData.getMaterial()).put(table, loot.getWeight()); - } - } else //Filter is exact - { - for (PlatformBlockState filterState : loot.getFilter(manager)) { - BlockData filterData = (BlockData) filterState.nativeHandle(); - if (!tc.exact.containsKey(filterData.getMaterial())) { - tc.exact.put(filterData.getMaterial(), new KMap<>()); - } - - if (!tc.exact.get(filterData.getMaterial()).containsKey(filterData)) { - tc.exact.get(filterData.getMaterial()).put(filterData, new WeightedTables()); - } - - tc.exact.get(filterData.getMaterial()).get(filterData).put(table, loot.getWeight()); - } - } - } - return tc; - } - - @Nullable - private static IrisVanillaLootTable getVanillaTable(String name) { - return Optional.ofNullable(NamespacedKey.fromString(name)) - .map(Bukkit::getLootTable) - // Hand over the key, not the LootTable: IrisVanillaLootTable holds no Bukkit fields. - .map(table -> new IrisVanillaLootTable(String.valueOf(table.getKey()))) - .orElse(null); - } - - /** - * Gets the loot table that should be used for the block - * - * @param state The block state of the block - * @param dataManager Iris Data Manager - * @return The loot table it should use. - */ - public IrisLootTable getTable(PlatformBlockState state, IrisData dataManager, RNG rng) { - TableCache cache = getCache(dataManager); - BlockData data = (BlockData) state.nativeHandle(); - if (BukkitBlockResolution.isStorageChest(data)) { - IrisLootTable picked = null; - if (cache.exact.containsKey(data.getMaterial()) && cache.exact.get(data.getMaterial()).containsKey(data)) { - picked = cache.exact.get(data.getMaterial()).get(data).pullRandom(rng); - } else if (cache.basic.containsKey(data.getMaterial())) { - picked = cache.basic.get(data.getMaterial()).pullRandom(rng); - } else if (!cache.global.isEmpty()) { - picked = cache.global.pullRandom(rng); - } - - return picked; - } - - return null; - } - private static final class SurfaceWarpCacheKey { private final IrisData data; private final Engine engine; @@ -432,41 +326,4 @@ public class IrisObjectPlacement { return 31 * result + Long.hashCode(seed); } } - - private static class TableCache { - final transient WeightedTables global = new WeightedTables(); - final transient KMap basic = new KMap<>(); - final transient KMap> exact = new KMap<>(); - - private void merge(TableCache other) { - global.merge(other.global); - basic.merge(other.basic, WeightedTables::merge); - exact.merge(other.exact, (a, b) -> a.merge(b, WeightedTables::merge)); - } - } - - private static final class WeightedTables { - private final KList tables = new KList<>(); - - private void put(IrisLootTable table, int weight) { - tables.add(new WeightedTable(table, weight)); - } - - private IrisLootTable pullRandom(RNG rng) { - WeightedTable picked = LootResolver.pickWeighted(tables, WeightedTable::weight, rng); - return picked == null ? null : picked.table(); - } - - private boolean isEmpty() { - return tables.isEmpty(); - } - - private WeightedTables merge(WeightedTables other) { - tables.addAll(other.tables); - return this; - } - } - - private record WeightedTable(IrisLootTable table, int weight) { - } } 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 index 5e7d3de5f..77865a878 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -21,7 +21,7 @@ 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.engine.object.loot.IrisLootTable; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.engine.object.loot.IrisObjectLoot; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; @@ -102,7 +102,7 @@ public class IrisStructure extends IrisRegistrant { private KList edit = new KList<>(); @ArrayType(type = String.class, min = 1) - @RegistryListResource(IrisLootTable.class) + @RegistryListResource(LootTable.class) @Desc("Loot tables applied to containers placed by this structure's pieces.") private KList loot = new KList<>(); 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 index 2be388ff5..fd1a30c8c 100644 --- 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 @@ -20,10 +20,6 @@ package art.arcane.iris.engine.object.world.biome; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.loot.IrisBlockDrops; -import art.arcane.iris.engine.object.loot.IrisLootReference; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; @@ -127,21 +123,9 @@ public class IrisBiome extends IrisRegistrant implements IRare { @ArrayType(min = 1, type = IrisBiomeCustom.class) @Desc("If the biome type custom is defined, specify this") private KList customDerivitives; - @Desc("Spawn Entities in this area over time. Iris will continually replenish these mobs just like vanilla does.") - @ArrayType(min = 1, type = String.class) - @RegistryListResource(IrisSpawner.class) - private KList entitySpawners = new KList<>(); - @ArrayType(min = 1, type = IrisEffect.class) - @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play around the player even if where the effect was played is no longer in the biome the player is in.") - private KList effects = new KList<>(); @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) @Desc("This changes the dispersion of the biome colors if multiple derivatives are chosen.") private IrisGeneratorStyle biomeStyle = NoiseStyle.SIMPLEX.style(); - @ArrayType(min = 1, type = IrisBlockDrops.class) - @Desc("Define custom block drops for this biome") - private KList blockDrops = new KList<>(); - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") private boolean lockLayers = false; @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") 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 index 8f37e4768..4f1646a55 100644 --- 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 @@ -21,12 +21,9 @@ package art.arcane.iris.engine.object.world.dimension; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; 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.loot.IrisBlockDrops; -import art.arcane.iris.engine.object.loot.IrisLootReference; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.IrisShapedGeneratorStyle; @@ -142,18 +139,9 @@ public class IrisDimension extends IrisRegistrant { private int debugCrossSectionsMod = 3; @Desc("Tree growth override settings") private IrisTreeSettings treeSettings = new IrisTreeSettings(); - @Desc("Spawn Entities in this dimension over time. Iris will continually replenish these mobs just like vanilla does.") - @ArrayType(min = 1, type = String.class) - @RegistryListResource(IrisSpawner.class) - private KList entitySpawners = new KList<>(); - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); @MinNumber(0) @Desc("The version of this dimension. Changing this will stop users from accidentally upgrading (and breaking their worlds).") private int version = 1; - @ArrayType(min = 1, type = IrisBlockDrops.class) - @Desc("Define custom block drops for this dimension") - private KList blockDrops = new KList<>(); @Desc("Should bedrock be generated or not.") private boolean bedrock = true; @MinNumber(0) 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 index 8c03c3310..104c3032f 100644 --- 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 @@ -19,10 +19,6 @@ package art.arcane.iris.engine.object.world.region; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.loot.IrisBlockDrops; -import art.arcane.iris.engine.object.loot.IrisLootReference; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; @@ -85,20 +81,10 @@ public class IrisRegion extends IrisRegistrant implements IRare { @Required @Desc("The name of the region") private String name = "A Region"; - @ArrayType(min = 1, type = IrisEffect.class) - @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") - private KList effects = new KList<>(); - @Desc("Spawn Entities in this region over time. Iris will continually replenish these mobs just like vanilla does.") - @ArrayType(min = 1, type = String.class) - @RegistryListResource(IrisSpawner.class) - private KList entitySpawners = new KList<>(); @MinNumber(1) @MaxNumber(128) @Desc("The rarity of the region") private int rarity = 1; - @ArrayType(min = 1, type = IrisBlockDrops.class) - @Desc("Define custom block drops for this region") - private KList blockDrops = new KList<>(); @ArrayType(min = 1, type = IrisObjectPlacement.class) @Desc("Objects define what schematics (iob files) iris will place in this region") private KList objects = new KList<>(); @@ -110,8 +96,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { @MinNumber(0) @Desc("The min shore height") private double shoreHeightMin = 1.2; - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); @MinNumber(0) @Desc("The the max shore height") private double shoreHeightMax = 3.2; diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java new file mode 100644 index 000000000..f1af6b1c4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -0,0 +1,135 @@ +/* + * 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.spawn; + +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.iris.builtin.spawn.EffectCommands; +import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.builtin.spawn.SpawnCommand; +import art.arcane.iris.core.loader.IrisRegistrant; +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.spi.PlatformWorld; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.entity.EntitySpec; +import com.volmit.service.AmbientEffects; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; + +/** + * How {@code iris:spawn} plays the ambient effects of regions and biomes: the region's effects, then the biome's, each + * when its interval and chance say, with every random choice made here so the host only carries them out. + */ +public final class AmbientEffecting implements AmbientEffects { + @Override + public List due(PackWorld world, BlockPosition at) { + Engine engine = IrisPackWorld.of(world).engine(); + EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers()); + PlatformWorld platformWorld = engine.getWorld().platformWorld(); + + List due = new ArrayList<>(); + addDue(due, effectsOf(engine.getRegion(at.x(), at.z())), timers, platformWorld); + addDue(due, effectsOf(engine.getBiome(at.x(), at.y(), at.z())), timers, platformWorld); + return due; + } + + private static List effectsOf(IrisRegistrant owner) { + return owner.getModuleSettings().find(EffectSettings.class).map(EffectSettings::effects).orElse(List.of()); + } + + private static void addDue(List due, List effects, EffectTimers timers, PlatformWorld world) { + for (AmbientEffect effect : effects) { + if (timers.shouldPlayNow(effect)) { + due.add(play(effect, world)); + } + } + } + + private static Effect play(AmbientEffect effect, PlatformWorld world) { + Sound sound = effect.sound() == null ? null : soundOf(effect); + Particles particles = effect.particleEffect() == null ? null : particlesOf(effect); + return new Effect(sound, particles, commandsOf(effect.commandRegistry(), world), potionOf(effect)); + } + + private static Sound soundOf(AmbientEffect effect) { + int distance = effect.soundDistance(); + int offsetX = RNG.r.i(-distance, distance); + int offsetY = RNG.r.i(-distance, distance); + int offsetZ = RNG.r.i(-distance, distance); + float pitch = (float) RNG.r.d(effect.minPitch(), effect.maxPitch()); + return new Sound(effect.sound(), offsetX, offsetY, offsetZ, (float) effect.volume(), pitch); + } + + private static Particles particlesOf(AmbientEffect effect) { + double forward = RNG.r.i(effect.particleDistance()) + effect.particleAway(); + double sideways = RNG.r.d(-effect.particleDistanceWidth(), effect.particleDistanceWidth()); + double jitterX = RNG.r.d(); + double jitterZ = RNG.r.d(); + int lift = RNG.r.i(effect.particleOffset()); + double altX = randomized(effect.particleAltX(), effect.randomAltX()); + double altY = randomized(effect.particleAltY(), effect.randomAltY()); + double altZ = randomized(effect.particleAltZ(), effect.randomAltZ()); + return new Particles(effect.particleEffect(), forward, sideways, jitterX, jitterZ, lift, effect.particleCount(), + altX, altY, altZ, effect.extra()); + } + + private static List commandsOf(EffectCommands registry, PlatformWorld world) { + List commands = new ArrayList<>(); + if (registry == null) { + return commands; + } + + double offsetX = commandOffset(registry.commandOffsetX(), registry.commandRandomAltX()); + double offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY()); + double offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ()); + for (SpawnCommand command : registry.rawCommands()) { + if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) { + commands.add(new Command(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), + command.repeatDelay()), offsetX, offsetY, offsetZ)); + } + if (registry.commandAllRandomLocations()) { + offsetX = commandOffset(registry.commandOffsetX(), registry.commandRandomAltX()); + offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY()); + offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ()); + } + } + return commands; + } + + private static Potion potionOf(AmbientEffect effect) { + if (effect.potionStrength() <= -1) { + return null; + } + + int shortest = Math.min(effect.potionTicksMax(), effect.potionTicksMin()); + int longest = Math.max(effect.potionTicksMax(), effect.potionTicksMin()); + return new Potion(effect.potionEffect(), effect.potionStrength(), RNG.r.i(shortest, longest)); + } + + private static double commandOffset(double offset, boolean random) { + return randomized(offset, random); + } + + private static double randomized(double value, boolean random) { + return random ? RNG.r.d(-value, value) : value; + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java b/src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java new file mode 100644 index 000000000..e3aac1bcb --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/EffectTimers.java @@ -0,0 +1,40 @@ +/* + * 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.spawn; + +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.scheduling.ChronoLatch; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * When the effects of a world play: an effect plays at most once per interval, and then only with its chance. The timers + * are the world's, shared by every player, like the effects themselves. + */ +final class EffectTimers { + private final ConcurrentMap latches = new ConcurrentHashMap<>(); + + /** Whether {@code effect} plays now; asking starts its interval over when it has elapsed. */ + boolean shouldPlayNow(AmbientEffect effect) { + ChronoLatch latch = latches.computeIfAbsent(effect, key -> new ChronoLatch(key.interval())); + return latch.flip() && RNG.r.nextInt(effect.chance()) == 0; + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index a5277349e..f0b72ae42 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.loot.ItemAttributeModifier; +import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.spawn.AmbientEffect; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.loot.LootItems; -import art.arcane.iris.engine.object.entity.IrisAttributeModifier; -import art.arcane.iris.engine.object.entity.IrisEffect; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.loot.IrisLoot; -import art.arcane.iris.engine.object.marker.IrisCommand; import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.math.RNG; import com.volmit.entity.EntitySpec; @@ -44,83 +44,85 @@ final class EntityResolution { private final LootItems items; private final PlatformWorld world; + private final EffectTimers timers; /** @param world the world the entity appears in, whose time and weather decide which of its commands run */ - EntityResolution(LootItems items, PlatformWorld world) { + EntityResolution(LootItems items, PlatformWorld world, EffectTimers timers) { this.items = items; this.world = world; + this.timers = timers; } - EntitySpec resolve(IrisEntity entity, RNG rng) { + EntitySpec resolve(EntityDefinition entity, RNG rng) { List passengers = new ArrayList<>(); long passengerIndex = 0; - for (IrisEntity passenger : entity.getPassengers()) { + for (EntityDefinition passenger : entity.passengers()) { passengers.add(resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++))); } List attributes = drawAttributes(entity, rng); - List lootTables = List.copyOf(entity.getLoot().getTables()); + List lootTables = List.copyOf(entity.loot().tables()); long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong(); - EntitySpec leashHolder = entity.getLeashHolder() == null ? null : resolve(entity.getLeashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); + EntitySpec leashHolder = entity.leashHolder() == null ? null : resolve(entity.leashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); EntitySpec.Equipment equipment = new EntitySpec.Equipment( - equip(entity.getHelmet(), rng), equip(entity.getChestplate(), rng), equip(entity.getLeggings(), rng), - equip(entity.getBoots(), rng), equip(entity.getMainHand(), rng), equip(entity.getOffHand(), rng)); + equip(entity.helmet(), rng), equip(entity.chestplate(), rng), equip(entity.leggings(), rng), + equip(entity.boots(), rng), equip(entity.mainHand(), rng), equip(entity.offHand(), rng)); return new EntitySpec( - entity.getType() == null ? "" : entity.getType(), - entity.getSpecialType() == null ? "" : entity.getSpecialType(), - entity.getReason(), - entity.getCustomName() == null ? "" : entity.getCustomName(), + entity.type() == null ? "" : entity.type(), + entity.specialType() == null ? "" : entity.specialType(), + entity.reason(), + entity.customName() == null ? "" : entity.customName(), flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, leashHolder, - spawnEffectOf(entity), entity.isSpawnEffectRiseOutOfGround(), entity.getPandaMainGene(), - entity.getPandaHiddenGene(), entity.isApplySettingsToCustomMobAnyways(), commandsOf(entity)); + spawnEffectOf(entity), entity.spawnEffectRiseOutOfGround(), entity.pandaMainGene(), + entity.pandaHiddenGene(), entity.applySettingsToCustomMobAnyways(), commandsOf(entity)); } - private static EntitySpec.Flags flagsOf(IrisEntity entity) { - return new EntitySpec.Flags(entity.isCustomNameVisible(), entity.isAware(), entity.isAi(), entity.isGlowing(), - entity.isGravity(), entity.isInvulnerable(), entity.isSilent(), entity.isPickupItems(), entity.isRemovable(), - entity.isKeepEntity(), entity.isBaby()); + private static EntitySpec.Flags flagsOf(EntityDefinition entity) { + return new EntitySpec.Flags(entity.customNameVisible(), entity.aware(), entity.ai(), entity.glowing(), + entity.gravity(), entity.invulnerable(), entity.silent(), entity.pickupItems(), entity.removable(), + entity.keepEntity(), entity.baby()); } - private static List drawAttributes(IrisEntity entity, RNG rng) { + private static List drawAttributes(EntityDefinition entity, RNG rng) { List attributes = new ArrayList<>(); - for (IrisAttributeModifier modifier : entity.getAttributes()) { - if (rng.nextDouble() >= modifier.getChance()) { + for (ItemAttributeModifier modifier : entity.attributes()) { + if (rng.nextDouble() >= modifier.chance()) { continue; } - String attribute = modifier.getAttribute(); + String attribute = modifier.attribute(); if (attribute == null || attribute.isBlank()) { continue; } - attributes.add(new ItemAttribute(attribute, modifier.getName(), modifier.getOperation(), modifier.getAmount(rng))); + attributes.add(new ItemAttribute(attribute, modifier.name(), modifier.operation(), rng.d(modifier.minAmount(), modifier.maxAmount()))); } return attributes; } - private ItemDrop equip(IrisLoot piece, RNG rng) { - if (piece == null || !LootResolver.oneIn(rng, piece.getRarity())) { + private ItemDrop equip(LootEntry piece, RNG rng) { + if (piece == null || !LootResolver.oneIn(rng, piece.rarity())) { return null; } return items.give(piece, rng); } /** The entity's spawn effect when it shows this time: an effect only shows now and then, as its interval and chance say. */ - private static EntitySpec.SpawnEffect spawnEffectOf(IrisEntity entity) { - IrisEffect effect = entity.getSpawnEffect(); - if (effect == null || !effect.shouldApplyNow()) { + private EntitySpec.SpawnEffect spawnEffectOf(EntityDefinition entity) { + AmbientEffect effect = entity.spawnEffect(); + if (effect == null || !timers.shouldPlayNow(effect)) { return null; } - return new EntitySpec.SpawnEffect(effect.getSoundKey(), effect.getSoundDistance(), effect.getMinPitch(), - effect.getMaxPitch(), effect.getVolume(), effect.getParticleEffectKey(), effect.getParticleOffset(), - effect.getParticleCount(), effect.getParticleAltX(), effect.getParticleAltY(), effect.getParticleAltZ(), - effect.isRandomAltX(), effect.isRandomAltY(), effect.isRandomAltZ(), effect.getExtra()); + return new EntitySpec.SpawnEffect(effect.sound(), effect.soundDistance(), effect.minPitch(), + effect.maxPitch(), effect.volume(), effect.particleEffect(), effect.particleOffset(), + effect.particleCount(), effect.particleAltX(), effect.particleAltY(), effect.particleAltZ(), + effect.randomAltX(), effect.randomAltY(), effect.randomAltZ(), effect.extra()); } - private List commandsOf(IrisEntity entity) { + private List commandsOf(EntityDefinition entity) { List commands = new ArrayList<>(); - for (IrisCommand command : entity.getRawCommands()) { - if (command.isValid(world)) { - commands.add(new EntitySpec.Command(command.getCommands(), command.getDelay(), command.isRepeat(), command.getRepeatDelay())); + for (SpawnCommand command : entity.rawCommands()) { + if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) { + commands.add(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay())); } } return commands; diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index e4aea6f93..afe14ae5e 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -18,26 +18,29 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.EntitySpawn; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.SpawnSurface; +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.builtin.spawn.SpawnerSettings; +import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.loot.LootItems; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.IrisEntitySpawn; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.entity.spawn.IrisSurface; -import art.arcane.iris.engine.object.marker.IrisMarker; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.slices.MarkerMatter; +import com.volmit.config.Range; import com.volmit.entity.EntitySpec; import com.volmit.service.EntitySpawns; import com.volmit.world.BlockPosition; @@ -76,15 +79,15 @@ public final class EntitySpawning implements EntitySpawns { if (count <= 0) { return; } - IrisSpawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner()); + Spawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner()); if (spawner != null) { - spawner.spawn(engine(world), plan.chunkX(), plan.chunkZ()); + SpawnerGate.spawned(plan.spawner(), spawner, engine(world), plan.chunkX(), plan.chunkZ()); } } @Override public Optional entity(PackWorld world, String key) { - IrisEntity entity = SpawnResources.entity(engine(world).getData(), key); + EntityDefinition entity = SpawnResources.entity(engine(world).getData(), key); if (entity == null) { return Optional.empty(); } @@ -97,40 +100,40 @@ public final class EntitySpawning implements EntitySpawns { return Optional.empty(); } Engine engine = engine(world); - IrisMarker marker = SpawnResources.marker(engine.getData(), tag); + SpawnMarker marker = SpawnResources.marker(engine.getData(), tag); if (marker == null) { return Optional.empty(); } List spawners = new ArrayList<>(); - for (String key : marker.getSpawners()) { + for (String key : marker.spawners()) { if (SpawnResources.spawner(engine.getData(), key) == null) { IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag); continue; } spawners.add(key); } - return Optional.of(new MarkerRule(spawners, marker.isEmptyAbove(), marker.isRemoveOnChange())); + return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange())); } private Optional planChunk(PackWorld world, Engine engine, Chunk chunk) { - Predicate canSpawn = spawner -> spawner.canSpawn(engine, chunk.chunkX(), chunk.chunkZ()); + Predicate canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), engine, chunk.chunkX(), chunk.chunkZ()); int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); IrisRegion region = engine.getRegion(blockX, blockZ); IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ); - List candidates = Stream.concat( - shuffled(engine, engine.getDimension().getEntitySpawners()).stream() - .filter(canSpawn).filter(spawner -> spawner.isValid(centreBiome)), + List candidates = Stream.concat( + shuffled(engine, engine.getDimension()).stream() + .filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreBiome)), Stream.concat( - shuffled(engine, region.getEntitySpawners()).stream().filter(canSpawn), - shuffled(engine, biome.getEntitySpawners()).stream().filter(canSpawn))) - .filter(spawner -> chunk.livingEntities() < spawner.getMaxEntitiesPerChunk()) + shuffled(engine, region).stream().filter(canSpawn), + shuffled(engine, biome).stream().filter(canSpawn))) + .filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk()) .toList(); - List spawns = candidates.stream().flatMap(spawner -> spawnsOf(spawner, chunk.initial())).collect(Collectors.toList()); + List spawns = candidates.stream().flatMap(keyed -> spawnsOf(keyed, chunk.initial())).collect(Collectors.toList()); Candidate chosen = IRare.expandWeighted(spawns).getRandom(); if (chosen == null) { return Optional.empty(); @@ -139,26 +142,25 @@ public final class EntitySpawning implements EntitySpawns { } private Optional planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) { - IrisSpawner spawner = chosen.spawner(); - IrisEntitySpawn spawn = chosen.spawn(); - int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns()); + EntitySpawn spawn = chosen.spawn(); + int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); List attempts = new ArrayList<>(); for (int i = 0; i < count; i++) { int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); - BlockPosition at = spawnPosition(engine, spawner, chunk.chunkX(), chunk.chunkZ(), x, z); + BlockPosition at = spawnPosition(engine, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); if (at != null) { addAttempt(attempts, world, engine, chosen, at, true); } } - return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(chosen.key(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); } /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ - private static BlockPosition spawnPosition(Engine engine, IrisSpawner spawner, int chunkX, int chunkZ, int x, int z) { + private static BlockPosition spawnPosition(Engine engine, Spawner spawner, int chunkX, int chunkZ, int x, int z) { int height = engine.getHeight(x, z, true); int heightWithFluid = engine.getHeight(x, z, false); - return switch (spawner.getGroup()) { + return switch (spawner.group()) { case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ); case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); @@ -175,78 +177,92 @@ public final class EntitySpawning implements EntitySpawns { } private Optional planMarker(PackWorld world, Engine engine, Marker marker) { - IrisSpawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner()); - IrisMarker irisMarker = SpawnResources.marker(engine.getData(), marker.marker()); + Spawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner()); + SpawnMarker spawnMarker = SpawnResources.marker(engine.getData(), marker.marker()); if (spawner == null) { return Optional.empty(); } - KList candidates = marker.initial() ? spawner.getInitialSpawns() : spawner.getSpawns(); + List candidates = marker.initial() ? spawner.initialSpawns() : spawner.spawns(); if (candidates.isEmpty()) { return Optional.empty(); } - IrisEntitySpawn spawn = IRare.expandWeighted(candidates).getRandom(); + EntitySpawn spawn = IRare.expandWeighted(candidates.stream().map(RareSpawn::new).toList()).getRandom().spawn(); BlockPosition position = marker.position(); int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); - if (!spawner.canSpawn(engine, chunkX, chunkZ)) { + if (!SpawnerGate.canSpawn(marker.spawner(), spawner, engine, chunkX, chunkZ)) { return Optional.empty(); } - int count = LootResolver.inclusive(RNG.r, spawn.getMinSpawns(), spawn.getMaxSpawns()); + int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); if (count <= 0) { return Optional.empty(); } - boolean exhaustsMarker = irisMarker != null && irisMarker.shouldExhaust(); + boolean exhaustsMarker = spawnMarker != null && shouldExhaust(spawnMarker); List attempts = new ArrayList<>(); BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); for (int i = 0; i < count; i++) { - addAttempt(attempts, world, engine, new Candidate(spawner, spawn), above, false); + addAttempt(attempts, world, engine, new Candidate(marker.spawner(), spawner, spawn), above, false); } - return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(spawner.getLoadKey(), chunkX, chunkZ, exhaustsMarker, attempts)); + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts)); + } + + private static boolean shouldExhaust(SpawnMarker marker) { + return marker.exhaustionChance() > RNG.r.nextDouble(); } private void addAttempt(List attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) { - IrisEntity entity = candidate.spawn().getRealEntity(engine); + EntityDefinition entity = SpawnResources.entity(engine.getData(), candidate.spawn().entity()); if (entity == null) { IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); return; } - IrisRange light = candidate.spawner().getAllowedLightLevels(); + Range light = candidate.spawner().allowedLightLevels(); EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng()); - attempts.add(new Attempt(at, spec, surfaceOf(entity.getSurface()), - (int) Math.ceil(light.getMin()), (int) Math.floor(light.getMax()), checkSurface)); + attempts.add(new Attempt(at, spec, surfaceOf(entity.surface()), + (int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface)); } private static EntityResolution resolution(PackWorld world, Engine engine) { LootItems items = new LootItems(world.resources().items(), engine.isStudio()); - return new EntityResolution(items, engine.getWorld().platformWorld()); + return new EntityResolution(items, engine.getWorld().platformWorld(), world.state(EffectTimers.class, ignored -> new EffectTimers())); } private static EntityRandom entityRandom(PackWorld world) { return world.state(EntityRandom.class, EntityRandom::new); } - private static Surface surfaceOf(IrisSurface surface) { + private static Surface surfaceOf(SpawnSurface surface) { return Surface.valueOf(surface.name()); } - private static KList shuffled(Engine engine, KList keys) { - return SpawnResources.spawners(engine.getData(), keys).shuffleCopy(RNG.r); + /** The spawners an area lists, in a random order. */ + private static List shuffled(Engine engine, IrisRegistrant owner) { + List keys = owner.getModuleSettings().find(SpawnerSettings.class).map(SpawnerSettings::spawners).orElse(List.of()); + return new KList<>(SpawnResources.spawners(engine.getData(), keys)).shuffleCopy(RNG.r); } - private static Stream spawnsOf(IrisSpawner spawner, boolean initial) { - KList spawns = initial ? spawner.getInitialSpawns() : spawner.getSpawns(); - return spawns.stream().map(spawn -> new Candidate(spawner, spawn)); + private static Stream spawnsOf(KeyedSpawner keyed, boolean initial) { + List spawns = initial ? keyed.spawner().initialSpawns() : keyed.spawner().spawns(); + return spawns.stream().map(spawn -> new Candidate(keyed.key(), keyed.spawner(), spawn)); } /** A spawn of a spawner, which picks as often as the spawn's rarity says. */ - private record Candidate(IrisSpawner spawner, IrisEntitySpawn spawn) implements IRare { + private record Candidate(String key, Spawner spawner, EntitySpawn spawn) implements IRare { @Override public int getRarity() { - return spawn.getRarity(); + return spawn.rarity(); + } + } + + /** A spawn that picks as often as its rarity says. */ + private record RareSpawn(EntitySpawn spawn) implements IRare { + @Override + public int getRarity() { + return spawn.rarity(); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java new file mode 100644 index 000000000..f7616adef --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java @@ -0,0 +1,42 @@ +/* + * 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.spawn; + +import art.arcane.iris.builtin.spawn.SpawnTimeBlock; +import art.arcane.iris.builtin.spawn.SpawnWeather; +import art.arcane.iris.spi.PlatformWorld; + +/** The time of day and the weather a command or spawner of the pack asks for, checked against a world. */ +final class SpawnConditions { + private static final double TICKS_PER_HOUR = 1000D; + private static final double HOURS_AT_TIME_ZERO = 6; + private static final double HOURS_PER_DAY = 24; + + private SpawnConditions() { + } + + static boolean allow(SpawnTimeBlock time, SpawnWeather weather, PlatformWorld world) { + return time.contains(hourOf(world)) && weather.matches(world.isStorming(), world.isThundering()); + } + + /** The world's time of day as a clock hour: tick 0 is 6 in the morning. */ + static double hourOf(PlatformWorld world) { + return ((world.getTime() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY; + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index c941d7702..e219c7b2f 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -18,16 +18,21 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.builtin.spawn.SpawnerSettings; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.service.AmbientEffects; import com.volmit.service.EntitySpawns; import com.volmit.stage.StageGraph; /** - * Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), and the entities that appear in the world - * over time because of them. It has no generation stage; Iris asks it through {@link EntitySpawns} when it looks for - * something to spawn in a chunk or at a marker. + * Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), the + * {@link SpawnerSettings} that dimensions, regions and biomes list, the entities that appear in the world over time + * because of them, and the ambient effects ({@link EffectSettings}) that play around players. It has no generation + * stage; Iris asks it through {@link EntitySpawns} when it looks for something to spawn in a chunk or at a marker, and + * through {@link AmbientEffects} for the effects due around a player. */ public final class SpawnModule implements IrisModule { private static final String VERSION = "built-in"; @@ -43,7 +48,10 @@ public final class SpawnModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + registry.registerSettings(SpawnerSettings.class); + registry.registerSettings(EffectSettings.class); SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); + registry.registerService(AmbientEffects.class, new AmbientEffecting()); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java index b5c25a6b2..fa12eefd2 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java @@ -18,15 +18,15 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.builtin.spawn.Spawner; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisPackResources; -import art.arcane.iris.engine.object.entity.IrisEntity; -import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; -import art.arcane.iris.engine.object.marker.IrisMarker; -import art.arcane.volmlib.util.collection.KList; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; +import java.util.ArrayList; import java.util.List; /** @@ -39,39 +39,43 @@ import java.util.List; */ public final class SpawnResources { /** Spawners, in {@code spawners/}. */ - public static final ResourceKind SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", IrisSpawner.class); + public static final ResourceKind SPAWNERS = ResourceKind.of("iris:spawn/spawner", "spawners", Spawner.class); /** Entities, in {@code entities/}. */ - public static final ResourceKind ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", IrisEntity.class); + public static final ResourceKind ENTITIES = ResourceKind.of("iris:spawn/entity", "entities", EntityDefinition.class); /** Markers, in {@code markers/}. */ - public static final ResourceKind MARKERS = ResourceKind.of("iris:spawn/marker", "markers", IrisMarker.class); + public static final ResourceKind MARKERS = ResourceKind.of("iris:spawn/marker", "markers", SpawnMarker.class); private SpawnResources() { } + /** A spawner and the key the pack names it by. */ + public record KeyedSpawner(String key, Spawner spawner) { + } + /** Every resource kind of the spawn module. */ public static List> kinds() { return List.of(SPAWNERS, ENTITIES, MARKERS); } - public static IrisSpawner spawner(IrisData data, String key) { + public static Spawner spawner(IrisData data, String key) { return find(data, SPAWNERS, key); } - public static IrisEntity entity(IrisData data, String key) { + public static EntityDefinition entity(IrisData data, String key) { return find(data, ENTITIES, key); } - public static IrisMarker marker(IrisData data, String key) { + public static SpawnMarker marker(IrisData data, String key) { return find(data, MARKERS, key); } /** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */ - public static KList spawners(IrisData data, List keys) { - KList spawners = new KList<>(); + public static List spawners(IrisData data, List keys) { + List spawners = new ArrayList<>(); for (String key : keys) { - IrisSpawner spawner = spawner(data, key); + Spawner spawner = spawner(data, key); if (spawner != null) { - spawners.add(spawner); + spawners.add(new KeyedSpawner(key, spawner)); } } return spawners; diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java new file mode 100644 index 000000000..74bbfb95b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java @@ -0,0 +1,97 @@ +/* + * 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.spawn; + +import art.arcane.iris.builtin.spawn.SpawnRate; +import art.arcane.iris.builtin.spawn.Spawner; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.spi.PlatformWorld; + +/** + * Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not + * more often than its rates allow. The rates count in the engine's persisted data, by the key the pack names the + * spawner by. + */ +final class SpawnerGate { + private SpawnerGate() { + } + + /** Whether a spawner of this group fires in {@code biome}. */ + static boolean suits(Spawner spawner, IrisBiome biome) { + return switch (spawner.group()) { + case NORMAL -> switch (biome.getInferredType()) { + case SHORE, SEA, CAVE -> false; + case LAND -> true; + }; + case CAVE -> true; + case UNDERWATER -> switch (biome.getInferredType()) { + case SHORE, LAND, CAVE -> false; + case SEA -> true; + }; + case BEACH -> switch (biome.getInferredType()) { + case SHORE -> true; + case LAND, CAVE, SEA -> false; + }; + }; + } + + /** Whether the world is in the time and weather the spawner asks for. */ + static boolean suits(Spawner spawner, PlatformWorld world) { + return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), world); + } + + /** Whether the spawner may fire in the chunk now. */ + static boolean canSpawn(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) { + if (!canSpawn(key, spawner, engine)) { + return false; + } + + SpawnRate rate = spawner.maximumRatePerChunk(); + return rate.isInfinite() || engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).canSpawn(rate.interval()); + } + + /** Counts a spawn of the spawner in the chunk against its rates. */ + static void spawned(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) { + spawned(key, spawner, engine); + if (spawner.maximumRatePerChunk().isInfinite()) { + return; + } + + engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).spawn(); + } + + private static boolean canSpawn(String key, Spawner spawner, Engine engine) { + PlatformWorld world = engine.getWorld().platformWorld(); + if (world == null || !suits(spawner, world)) { + return false; + } + + SpawnRate rate = spawner.maximumRate(); + return rate.isInfinite() || engine.getEngineData().getCooldown(key).canSpawn(rate.interval()); + } + + private static void spawned(String key, Spawner spawner, Engine engine) { + if (spawner.maximumRate().isInfinite()) { + return; + } + + engine.getEngineData().getCooldown(key).spawn(); + } +} From cff492ada8ff440fb5ff3d42fe89c733a50e8cfd Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:51:28 +0200 Subject: [PATCH 052/139] Caves and floating islands are settings of iris:carve and iris:floating caveProfile (CaveProfile is the feature, held by dimension, region and biome), carving (CarvingSettings of CarvingEntry), carvingEnabled, carvingBiome and caveMinDepthBelowSurface are iris:carve settings; floatingChildBiomes and mergeFloatingChildBiomes are iris:floating settings, all under the keys and shapes packs always wrote. CarvingEntry is IrisApi-typed; ResolvedCarvingEntry, CarvingBands (the world's bands) and CarvingResolver (was IrisDimensionCarvingResolver) hold the behaviour, CaveProfiles and FloatingChildren read the settings. iris:carve provides CaveBiomes (CaveBiomeBands). CarvingBiomeSettings, CarvingSettings and FloatingChildSettings implement LinkedBiomes, so the biome tree and the biomes a dimension reaches learn of the biomes they name without reading the classes. IrisBiome, IrisRegion and IrisDimension lose the fields, the carving entry index and getRealCarvingBiome; IrisDimensionCarvingEntry is deleted. CaveApplying and DepositPlacer no longer thread a resolver state through the cave biome lookup. --- README.md | 16 ++- .../builtin/carve/CarvingBiomeSettings.java | 54 ++++++++ .../builtin/carve/CarvingEnabledSettings.java | 43 ++++++ .../iris/builtin/carve/CarvingEntry.java | 103 ++++++++++++++ .../iris/builtin/carve/CarvingSettings.java | 80 +++++++++++ .../iris/builtin/carve/CaveDepthSettings.java | 47 +++++++ .../iris/builtin/carve/CaveProfile.java | 9 +- .../floating/FloatingChildSettings.java | 70 ++++++++++ .../MergeFloatingChildrenSettings.java | 43 ++++++ .../iris/engine/actuator/ResolvedOre.java | 12 +- .../iris/engine/actuator/TerrainOres.java | 9 +- .../engine/mantle/components/CaveCarving.java | 62 +++++---- .../FloatingIslandSampleResolver.java | 3 +- .../components/FloatingObjectPlacing.java | 4 +- .../mantle/components/ObjectPlacing.java | 13 +- .../iris/engine/modifier/CarveModule.java | 16 ++- .../iris/engine/modifier/CaveApplying.java | 53 ++++---- .../iris/engine/modifier/CaveBiomeBands.java | 61 +++++++++ .../iris/engine/modifier/DepositPlacer.java | 11 +- .../iris/engine/modifier/FloatingIslands.java | 5 +- .../iris/engine/modifier/FloatingModule.java | 6 +- .../object/terrain/carving/CarvingBands.java | 71 ++++++++++ ...vingResolver.java => CarvingResolver.java} | 126 ++++++++---------- .../object/terrain/carving/CaveProfiles.java | 33 +++++ .../carving/IrisDimensionCarvingEntry.java | 84 ------------ .../terrain/carving/ResolvedCarvingEntry.java | 101 ++++++++++++++ .../terrain/floating/FloatingChildren.java | 13 ++ .../floating/FloatingIslandSample.java | 6 +- .../floating/ResolvedFloatingChild.java | 22 +-- .../engine/object/world/biome/IrisBiome.java | 30 ----- .../object/world/dimension/IrisDimension.java | 69 +--------- .../object/world/region/IrisRegion.java | 8 +- 32 files changed, 927 insertions(+), 356 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java rename src/main/java/art/arcane/iris/engine/object/terrain/carving/{IrisDimensionCarvingResolver.java => CarvingResolver.java} (69%) create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java diff --git a/README.md b/README.md index 4bf62dc47..84c19c521 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,8 @@ only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its en `art.arcane.iris.builtin.deposit`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. -Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition, -a cave profile, a floating child biome or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, +Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition +or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, `.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). The module registers each with `registry.registerHeldType(...)` so studio describes it from the module's own annotations; packs write the same JSON as before. Behaviour that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the @@ -64,6 +64,18 @@ seed is the world's decorator seed, its biome's key and its place in the biome's them ahead of generation; `iris:terrain` and `iris:objects` warm their ore generators, placements and procedural objects the same way. +Caves, floating islands and ores are settings of their modules too, written under the keys they always had. `iris:carve` owns +`caveProfile` (dimension, region, biome; an object, or a `snippet/cave-profile/...` reference), `carving` (dimension; a list of bands) and +`carvingEnabled` (dimension; a boolean), `carvingBiome` (biome; a biome key) and `caveMinDepthBelowSurface` (biome; a number). `iris:floating` +owns `floatingChildBiomes` (biome; a list) and `mergeFloatingChildBiomes` (biome; a boolean). `iris:terrain` owns `ores` (dimension, region, +biome; a list of generators) and `hideOresForHiddenOre` (dimension; a boolean); `iris:deposit` owns `depositVariants` (dimension, region, biome; a list) +and `oreDepositFrequencyMultiplier` and `oreDepositSizeMultiplier` (biome; numbers). Behaviour that needs Iris lives in the `Resolved*` classes beside the +workers: `ResolvedOre`/`ResolvedOres` (blocks and chance noise per world, `TerrainOres` the world's state), `ResolvedDepositVariant`, +`ResolvedCarvingEntry`/`CarvingBands`/`CarvingResolver` (the band for a position) and `ResolvedFloatingChild`. The settings that name biomes +(`carvingBiome`, a band's biome, a floating child's target and carving) implement `LinkedBiomes`, which is how Iris's biome tree and the biomes a +dimension reaches learn of them without reading the settings classes; and `iris:carve` provides the `CaveBiomes` service +(`CaveBiomeBands`), which Iris asks for the dimension's carving band at a position and for a biome's minimum cave depth. + Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` (biome; a list) and `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest). The feature ids (`iris:deposit`, `iris:decorant`, `iris:structure`) stay the modules' identity in the stage graph and logs. A key is unique diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java new file mode 100644 index 000000000..e2942aecb --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java @@ -0,0 +1,54 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.LinkedBiomes; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +import java.util.Set; + +/** A biome's {@code carvingBiome}, written as the biome key: it registers that biome with the pack's layout and is not applied as a substitute under carvings. */ +@Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") +@Feature(id = "iris:carve/biome", name = "Carving biome", key = "carvingBiome", root = "biome", targets = Target.BIOME) +public final class CarvingBiomeSettings implements IrisFeature, LinkedBiomes { + @Ref(Reference.PACK_BIOME) + @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") + private String biome = ""; + + public CarvingBiomeSettings() { + } + + public CarvingBiomeSettings(String biome) { + this.biome = biome; + } + + public String biome() { + return biome == null ? "" : biome; + } + + @Override + public Set treeBiomes() { + return Set.of(biome()); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java new file mode 100644 index 000000000..d09f7e7ac --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A dimension's {@code carvingEnabled}, written as the bare boolean. */ +@Desc("Enable or disable all carving for this dimension") +@Feature(id = "iris:carve/enabled", name = "Carving enabled", key = "carvingEnabled", root = "enabled", targets = Target.DIMENSION) +public final class CarvingEnabledSettings implements IrisFeature { + @Desc("Enable or disable all carving for this dimension") + private boolean enabled = true; + + public CarvingEnabledSettings() { + } + + public CarvingEnabledSettings(boolean enabled) { + this.enabled = enabled; + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java new file mode 100644 index 000000000..7508832a7 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java @@ -0,0 +1,103 @@ +/* + * 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.builtin.carve; + +import com.volmit.config.Desc; +import com.volmit.config.Range; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; + +/** + * One dimension-level cave biome override, an entry of {@code carving}: a pack biome that replaces the cave biome within a band + * of world Y, optionally split into child entries by a noise pattern. IrisApi types only; {@code CarvingResolver} picks + * the entry for a position. + */ +@Snippet("dimension-carving-entry") +@Desc("Dimension-level cave biome override with absolute world Y bounds.") +public final class CarvingEntry { + private static final double DEFAULT_WORLD_Y_MIN = -64; + private static final double DEFAULT_WORLD_Y_MAX = 320; + private static final double DEFAULT_CHILD_SHRINK_FACTOR = 1.5; + private static final int DEFAULT_CHILD_RECURSION_DEPTH = 3; + + @Desc("Stable id for this carving entry") + private String id = ""; + + @Desc("Enable or disable this carving entry") + private boolean enabled = true; + + @Ref(Reference.PACK_BIOME) + @Desc("Cave biome to apply when world Y falls within worldYRange") + private String biome = ""; + + @Desc("Absolute world Y bounds where this carving entry applies") + private Range worldYRange = Range.of(DEFAULT_WORLD_Y_MIN, DEFAULT_WORLD_Y_MAX); + + @Desc("If this carving entry has child carving entries, this controls how small those child carving patches are.") + private double childShrinkFactor = DEFAULT_CHILD_SHRINK_FACTOR; + + @Desc("If this carving entry has child carving entries, this controls the shape pattern used to pick them.") + private NoiseStyle childStyle = NoiseStyle.of("CELLULAR_IRIS_DOUBLE"); + + @Desc("Child carving entry ids. Child ids can point back to parent ids to create cycles; recursion is bounded by childRecursionDepth.") + private List children = List.of(); + + @Desc("Maximum recursion depth when resolving child carving entries from this entry.") + private int childRecursionDepth = DEFAULT_CHILD_RECURSION_DEPTH; + + public CarvingEntry() { + } + + public String id() { + return id == null ? "" : id; + } + + public boolean enabled() { + return enabled; + } + + public String biome() { + return biome == null ? "" : biome; + } + + public Range worldYRange() { + return worldYRange; + } + + public double childShrinkFactor() { + return childShrinkFactor; + } + + public NoiseStyle childStyle() { + return childStyle; + } + + public List children() { + return children == null ? List.of() : Collections.unmodifiableList(children); + } + + public int childRecursionDepth() { + return childRecursionDepth; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java new file mode 100644 index 000000000..afd544963 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java @@ -0,0 +1,80 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.LinkedBiomes; +import com.volmit.config.MinItems; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * The cave biome overrides a dimension declares, written as {@code "carving": [...]}, the list of {@link CarvingEntry}s. + * The biome of every enabled entry takes part in the pack's layout like any biome the dimension reaches. + */ +@Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") +@Feature(id = "iris:carve/bands", name = "Cave biome bands", key = "carving", root = "entries", targets = Target.DIMENSION) +public final class CarvingSettings implements IrisFeature, LinkedBiomes { + @MinItems(1) + @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") + private List entries = List.of(); + + public CarvingSettings() { + } + + public CarvingSettings(List entries) { + this.entries = List.copyOf(entries); + } + + public List entries() { + return entries == null ? List.of() : Collections.unmodifiableList(entries); + } + + /** + * The biome key {@code reference} stands for: the biome of the entry with that id, ignoring surrounding blanks, or + * {@code reference} itself when no entry has the id. When several entries share an id the last one counts. + */ + public String biomeOf(String reference) { + CarvingEntry entry = null; + for (CarvingEntry candidate : entries()) { + if (candidate != null && !candidate.id().isBlank() && candidate.id().trim().equals(reference)) { + entry = candidate; + } + } + return entry == null ? reference : entry.biome(); + } + + @Override + public Set usedBiomes(Collection dimension) { + Set biomes = new LinkedHashSet<>(); + for (CarvingEntry entry : entries()) { + if (entry != null && entry.enabled()) { + biomes.add(entry.biome()); + } + } + return biomes; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java new file mode 100644 index 000000000..08f005403 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A biome's {@code caveMinDepthBelowSurface}, written as the bare number of blocks. */ +@Desc("Minimum depth below terrain surface required before this cave biome can be selected.") +@Feature(id = "iris:carve/min-depth", name = "Cave minimum depth", key = "caveMinDepthBelowSurface", root = "depth", targets = Target.BIOME) +public final class CaveDepthSettings implements IrisFeature { + @MinNumber(0) + @MaxNumber(256) + @Desc("Minimum depth below terrain surface required before this cave biome can be selected.") + private int depth = 0; + + public CaveDepthSettings() { + } + + public CaveDepthSettings(int depth) { + this.depth = depth; + } + + public int depth() { + return depth; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java b/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java index 0884897b3..a64df4d67 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java @@ -19,7 +19,10 @@ package art.arcane.iris.builtin.carve; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; import com.volmit.config.Desc; +import com.volmit.config.Feature; import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; @@ -35,11 +38,13 @@ import java.util.Optional; /** * A 3D cave profile as packs write it for a dimension, region or biome ({@code caveProfile}) or under * {@code snippet/cave-profile/}: the noise fields that decide where caves are, how they meet the surface, where - * cave fluid may sit and how objects find anchors in them. IrisApi types only; the carving module builds the noise. + * cave fluid may sit and how objects find anchors in them. A level that writes none has no profile, which is the + * same as one that is not {@code enabled}. IrisApi types only; the carving module builds the noise. */ @Snippet("cave-profile") @Desc("Represents a configurable 3D cave profile.") -public final class CaveProfile { +@Feature(id = "iris:carve/profile", name = "Cave profile", key = "caveProfile", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class CaveProfile implements IrisFeature { @Desc("Enable profile-driven cave carving.") private boolean enabled = false; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java new file mode 100644 index 000000000..796b062f8 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java @@ -0,0 +1,70 @@ +/* + * 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.builtin.floating; + +import art.arcane.iris.builtin.carve.CarvingSettings; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.LinkedBiomes; +import com.volmit.config.MinItems; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * The floating child biomes one biome declares, written as {@code "floatingChildBiomes": [...]}, the list of + * {@link FloatingChildBiome}s. The target biome of every child, and the biome its {@code carving} names, take part in the + * pack's layout like any biome a dimension reaches. + */ +@Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") +@Feature(id = "iris:floating/children", name = "Floating child biomes", key = "floatingChildBiomes", root = "children", targets = Target.BIOME) +public final class FloatingChildSettings implements IrisFeature, LinkedBiomes { + @MinItems(1) + @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") + private List children = List.of(); + + public FloatingChildSettings() { + } + + public FloatingChildSettings(List children) { + this.children = List.copyOf(children); + } + + public List children() { + return children == null ? List.of() : Collections.unmodifiableList(children); + } + + @Override + public Set usedBiomes(Collection dimension) { + CarvingSettings carving = dimension.stream().filter(CarvingSettings.class::isInstance).map(CarvingSettings.class::cast).findFirst().orElse(null); + Set biomes = new LinkedHashSet<>(); + for (FloatingChildBiome child : children()) { + if (child != null) { + biomes.add(child.biome()); + biomes.add(carving == null ? child.carving() : carving.biomeOf(child.carving())); + } + } + return biomes; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java b/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java new file mode 100644 index 000000000..24224b836 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.floating; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A biome's {@code mergeFloatingChildBiomes}, written as the bare boolean. */ +@Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") +@Feature(id = "iris:floating/merge", name = "Merge floating child biomes", key = "mergeFloatingChildBiomes", root = "merge", targets = Target.BIOME) +public final class MergeFloatingChildrenSettings implements IrisFeature { + @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") + private boolean merge = false; + + public MergeFloatingChildrenSettings() { + } + + public MergeFloatingChildrenSettings(boolean merge) { + this.merge = merge; + } + + public boolean merge() { + return merge; + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java index ee0b330a4..721dbbb0c 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java @@ -105,13 +105,21 @@ final class ResolvedOre { if (settings.palette().palette().isEmpty()) { return null; } - NoiseSampler sampler = chance.aquire(() -> noise.sampler(settings.chanceStyle(), terrainSeed)); - if (sampler.sample(x, y, z) > settings.threshold()) { + if (chanceNoise().sample(x, y, z) > settings.threshold()) { return null; } return pick(x, y, z); } + /** The chance noise, which this runs per block of the terrain, so a built one is read without creating a supplier. */ + private NoiseSampler chanceNoise() { + NoiseSampler built = chance.getIfPresent(); + if (built != null) { + return built; + } + return chance.aquire(() -> noise.sampler(settings.chanceStyle(), terrainSeed)); + } + private PlatformBlockState pick(int x, int y, int z) { if (blocks.isEmpty()) { return null; diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java index 8dc6a9b0e..1eb73d719 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -42,12 +42,19 @@ final class TerrainOres { return engine.getGeneration().state(TerrainOres.class, TerrainOres::new); } - /** The ore generators {@code owner}, a dimension, region or biome, declares; {@link ResolvedOres#NONE} when it declares none. */ + /** + * The ore generators {@code owner}, a dimension, region or biome, declares; {@link ResolvedOres#NONE} when it declares none. The + * terrain asks this for two owners per column, so a resolved set is read without taking the map's lock. + */ ResolvedOres of(IrisRegistrant owner) { OreSettings settings = owner.getModuleSettings().find(OreSettings.class).orElse(null); if (settings == null) { return ResolvedOres.NONE; } + ResolvedOres existing = resolved.get(settings); + if (existing != null) { + return existing; + } return resolved.computeIfAbsent(settings, declared -> ResolvedOres.of(declared, engine)); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 2660dc3f2..da5c48f1e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -19,13 +19,17 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.core.modules.IrisValues; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; +import art.arcane.iris.engine.modifier.CaveBiomeBands; +import art.arcane.iris.engine.object.terrain.carving.CarvingBands; +import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.spi.PlatformBlockState; @@ -89,7 +93,7 @@ public class CaveCarving { /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ public void carve(MantleWriter writer, int x, int z, ChunkContext context) { IrisComplex complex = context.getComplex(); - IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); + CarvingResolver.State resolverState = new CarvingResolver.State(); BlendScratch blendScratch = BLEND_SCRATCH.get(); int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); @@ -200,7 +204,7 @@ public class CaveCarving { } } - private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState) { + private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState) { BlendScratch blendScratch = BLEND_SCRATCH.get(); CaveProfile[] profileField = blendScratch.profileField; Map columnProfileWeights = blendScratch.columnProfileWeights; @@ -296,40 +300,40 @@ public class CaveCarving { return resolvedProfiles; } - private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { + private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, CarvingResolver.State resolverState, BlendScratch blendScratch) { List weightedProfiles = new ArrayList<>(); - List entries = engine.getDimension().getCarving(); - if (entries == null || entries.isEmpty()) { + List entries = CarvingBands.of(engine).entries(); + if (entries.isEmpty()) { return weightedProfiles; } - Map dimensionColumnPlans = blendScratch.dimensionColumnPlans; + Map dimensionColumnPlans = blendScratch.dimensionColumnPlans; dimensionColumnPlans.clear(); - for (IrisDimensionCarvingEntry entry : entries) { - if (entry == null || !entry.isEnabled()) { + for (ResolvedCarvingEntry entry : entries) { + if (!entry.enabled()) { continue; } - IrisBiome rootBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry, resolverState); + IrisBiome rootBiome = CarvingResolver.resolveEntryBiome(engine, entry, resolverState); if (rootBiome == null) { continue; } - IrisDimensionCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new IrisDimensionCarvingEntry[CHUNK_AREA]); + ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]); buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState); Map rootProfileColumnWeights = new IdentityHashMap<>(); List rootProfileOrder = new ArrayList<>(); - IrisRange worldYRange = entry.getWorldYRange(); + IrisRange worldYRange = entry.worldYRange() == null ? null : IrisValues.range(entry.worldYRange()); for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { - IrisDimensionCarvingEntry resolvedEntry = columnPlan[columnIndex]; - IrisBiome resolvedBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); + ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex]; + IrisBiome resolvedBiome = CarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); if (resolvedBiome == null) { continue; } - CaveProfile profile = resolvedBiome.getCaveProfile(); + CaveProfile profile = CaveProfiles.declaredBy(resolvedBiome); if (!isProfileEnabled(profile)) { continue; } @@ -351,7 +355,7 @@ public class CaveCarving { return weightedProfiles; } - private void buildDimensionColumnPlan(IrisDimensionCarvingEntry[] columnPlan, int chunkX, int chunkZ, IrisDimensionCarvingEntry entry, IrisDimensionCarvingResolver.State resolverState) { + private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry, CarvingResolver.State resolverState) { int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); for (int localX = 0; localX < CHUNK_SIZE; localX++) { @@ -359,12 +363,12 @@ public class CaveCarving { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldZ = baseZ + localZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - columnPlan[columnIndex] = IrisDimensionCarvingResolver.resolveFromRoot(engine, entry, worldX, worldZ, resolverState); + columnPlan[columnIndex] = CarvingResolver.resolveFromRoot(engine, entry, worldX, worldZ, resolverState); } } } - private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, IrisDimensionCarvingResolver.State resolverState, BlendScratch blendScratch) { + private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState, BlendScratch blendScratch) { int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; prefillProfileFieldSamples(startX, startZ, complex, blendScratch); @@ -404,23 +408,23 @@ public class CaveCarving { IrisRegion region, IrisBiome surfaceBiome, IrisBiome caveBiome, - IrisDimensionCarvingResolver.State resolverState + CarvingResolver.State resolverState ) { CaveProfile resolved = null; - CaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); + CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); if (isProfileEnabled(dimensionProfile)) { resolved = dimensionProfile; } if (region != null) { - CaveProfile regionProfile = region.getCaveProfile(); + CaveProfile regionProfile = CaveProfiles.declaredBy(region); if (isProfileEnabled(regionProfile)) { resolved = regionProfile; } } if (surfaceBiome != null) { - CaveProfile surfaceProfile = surfaceBiome.getCaveProfile(); + CaveProfile surfaceProfile = CaveProfiles.declaredBy(surfaceBiome); if (isProfileEnabled(surfaceProfile)) { resolved = surfaceProfile; } @@ -429,11 +433,11 @@ public class CaveCarving { int roundedSurfaceY = (int) Math.round(surfaceHeight); int sampleY = Math.max(1, roundedSurfaceY - 56); int worldY = sampleY + engine.getWorld().minHeight(); - IrisDimensionCarvingEntry rootCarvingEntry = IrisDimensionCarvingResolver.resolveRootEntry(engine, worldY, resolverState); + ResolvedCarvingEntry rootCarvingEntry = CarvingResolver.resolveRootEntry(engine, worldY, resolverState); IrisBiome resolvedCarvingBiome = null; if (rootCarvingEntry != null) { - IrisDimensionCarvingEntry resolvedCarvingEntry = IrisDimensionCarvingResolver.resolveFromRoot(engine, rootCarvingEntry, worldX, worldZ, resolverState); - resolvedCarvingBiome = IrisDimensionCarvingResolver.resolveEntryBiome(engine, resolvedCarvingEntry, resolverState); + ResolvedCarvingEntry resolvedCarvingEntry = CarvingResolver.resolveFromRoot(engine, rootCarvingEntry, worldX, worldZ, resolverState); + resolvedCarvingBiome = CarvingResolver.resolveEntryBiome(engine, resolvedCarvingEntry, resolverState); if (resolvedCarvingBiome != null) { caveBiome = resolvedCarvingBiome; } @@ -447,7 +451,7 @@ public class CaveCarving { if (depthBelowSurface <= 0) { effectiveCaveBiome = surfaceBiome; } else { - int minDepth = Math.max(0, caveBiome.getCaveMinDepthBelowSurface()); + int minDepth = Math.max(0, CaveBiomeBands.minDepthBelowSurface(caveBiome)); if (depthBelowSurface < minDepth) { effectiveCaveBiome = surfaceBiome; } @@ -455,7 +459,7 @@ public class CaveCarving { } } - CaveProfile caveProfile = effectiveCaveBiome.getCaveProfile(); + CaveProfile caveProfile = CaveProfiles.declaredBy(effectiveCaveBiome); if (isProfileEnabled(caveProfile)) { resolved = caveProfile; } @@ -680,7 +684,7 @@ public class CaveCarving { private final CaveProfile[] kernelProfiles = new CaveProfile[KERNEL_SIZE]; private final double[] kernelProfileWeights = new double[KERNEL_SIZE]; private final IdentityHashMap columnProfileWeights = new IdentityHashMap<>(); - private final IdentityHashMap dimensionColumnPlans = new IdentityHashMap<>(); + private final IdentityHashMap dimensionColumnPlans = new IdentityHashMap<>(); private final IdentityHashMap activeProfiles = new IdentityHashMap<>(); private final List profileOrder = new ArrayList<>(); private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java index b80204f93..b45fbe693 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -23,6 +23,7 @@ import art.arcane.iris.engine.data.cache.Cache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.modifier.FloatingIslands; +import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -56,7 +57,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro return sampleCache.get(key); } IrisBiome parent = parent(x, z); - if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) { + if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { resolvedSamples.add(key); return null; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 2a74bfb86..6537c02ce 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -543,8 +543,8 @@ public class FloatingObjectPlacing { try { IrisData data = engine.getData(); for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - List settings = biome.getFloatingChildBiomes(); - if (settings == null || settings.isEmpty()) { + List settings = FloatingChildren.declaredBy(biome); + if (settings.isEmpty()) { continue; } for (ResolvedFloatingChild entry : FloatingChildren.of(engine).of(settings)) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 88d18f4b8..288e9c139 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -25,6 +25,7 @@ import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import art.arcane.iris.core.IrisSettings; @@ -235,8 +236,8 @@ public class ObjectPlacing { int rejected = 0; int nullObjects = 0; int errors = 0; - CaveProfile biomeCaveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); - CaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome.getCaveProfile()); + CaveProfile biomeCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); + CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), CaveProfiles.declaredBy(caveBiome)); CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) { @@ -384,12 +385,12 @@ public class ObjectPlacing { @ChunkCoordinates private void placeProceduralObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region) { - CaveProfile surfaceCaveProfile = resolveCaveProfile(surfaceBiome.getCaveProfile(), region.getCaveProfile()); - CaveProfile regionCaveProfile = resolveCaveProfile(region.getCaveProfile(), caveBiome == null ? null : caveBiome.getCaveProfile()); + CaveProfile surfaceCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(surfaceBiome), CaveProfiles.declaredBy(region)); + CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), caveBiome == null ? null : CaveProfiles.declaredBy(caveBiome)); placeProceduralFrom(writer, rng, x, z, surfaceBiome.getProceduralObjects(), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); placeProceduralFrom(writer, rng, x, z, region.getProceduralObjects(), region.getName(), regionCaveProfile, null); if (caveBiome != null && caveBiome != surfaceBiome) { - CaveProfile caveProfile = resolveCaveProfile(caveBiome.getCaveProfile(), region.getCaveProfile()); + CaveProfile caveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); placeProceduralFrom(writer, rng, x, z, caveBiome.getProceduralObjects(), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); } } @@ -1319,7 +1320,7 @@ public class ObjectPlacing { } private CaveProfile resolveCaveProfile(CaveProfile preferred, CaveProfile secondary) { - CaveProfile dimensionProfile = engine.getDimension().getCaveProfile(); + CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); if (preferred != null && preferred.enabled()) { return preferred; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index d69592f3d..4d6a91412 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -18,7 +18,10 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.carve.CaveFieldModule; +import art.arcane.iris.builtin.carve.CarvingBiomeSettings; +import art.arcane.iris.builtin.carve.CarvingEnabledSettings; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.carve.CaveDepthSettings; import art.arcane.iris.builtin.carve.CaveProfile; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; @@ -28,6 +31,7 @@ import art.arcane.iris.engine.mantle.components.CaveCarving; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.service.CaveBiomes; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; @@ -51,8 +55,12 @@ public final class CarveModule implements IrisModule { @Override public void register(FeatureRegistry registry) { - registry.registerHeldType(CaveProfile.class); - registry.registerHeldType(CaveFieldModule.class); + registry.registerSettings(CaveProfile.class); + registry.registerSettings(CarvingSettings.class); + registry.registerSettings(CarvingEnabledSettings.class); + registry.registerSettings(CarvingBiomeSettings.class); + registry.registerSettings(CaveDepthSettings.class); + registry.registerService(CaveBiomes.class, new CaveBiomeBands()); } @Override @@ -83,6 +91,6 @@ public final class CarveModule implements IrisModule { * also does: Iris then skips this stage's mantle pass like any disabled component. */ private static boolean carves(IrisDimension dimension) { - return dimension.isCarvingEnabled(); + return dimension.getModuleSettings().find(CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 15242fee5..cc2b666a3 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -26,7 +26,6 @@ import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.documentation.ChunkCoordinates; @@ -82,7 +81,6 @@ public class CaveApplying { public void apply(int x, int z, Hunk output, boolean multicore, ChunkContext context) { PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start(); Mantle mantle = engine.getMantle().getMantle(); - IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State(); Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(2048); IrisCarveScratch scratch = SCRATCH.get(); scratch.reset(); @@ -174,7 +172,7 @@ public class CaveApplying { int worldZ = rz + chunkBlockZ; String customBiome = cavern.getCustomBiome(); IrisBiome biome = customBiome.isEmpty() - ? resolveCaveBiome(caveBiomeCache, worldX, yy, worldZ, resolverState) + ? resolveCaveBiome(caveBiomeCache, worldX, yy, worldZ) : resolveCustomBiome(customBiomeCache, customBiome); if (biome != null) { @@ -188,14 +186,14 @@ public class CaveApplying { }); for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - processColumnFromMask(output, mantleChunk, mantle, columnMasks[columnIndex], columnIndex, x, z, resolverState, caveBiomeCache, customBiomeCache); + processColumnFromMask(output, mantleChunk, mantle, columnMasks[columnIndex], columnIndex, x, z, caveBiomeCache, customBiomeCache); } for (int columnIndex = 0; columnIndex < 256; columnIndex++) { if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { continue; } - processBoundaryColumnFromMask(output, boundaryMasks[columnIndex], walls, columnIndex, x, z, resolverState, caveBiomeCache, customBiomeCache); + processBoundaryColumnFromMask(output, boundaryMasks[columnIndex], walls, columnIndex, x, z, caveBiomeCache, customBiomeCache); } // Surface-break carving must not leave an ore cap suspended across the opening. @@ -409,7 +407,6 @@ public class CaveApplying { int columnIndex, int chunkX, int chunkZ, - IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache ) { @@ -438,7 +435,7 @@ public class CaveApplying { zone.ceiling = buf; } else { if (zone.isValid(engine)) { - processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache); + processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, caveBiomeCache, customBiomeCache); } zone = new CaveZone(); zone.setFloor(y); @@ -450,7 +447,7 @@ public class CaveApplying { } if (zone.isValid(engine)) { - processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, resolverState, caveBiomeCache, customBiomeCache); + processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, caveBiomeCache, customBiomeCache); } } @@ -461,7 +458,6 @@ public class CaveApplying { int columnIndex, int chunkX, int chunkZ, - IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache ) { @@ -482,14 +478,14 @@ public class CaveApplying { if (y == zoneCeiling + 1) { zoneCeiling = y; } else { - paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, resolverState, caveBiomeCache, customBiomeCache); + paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, caveBiomeCache, customBiomeCache); zoneFloor = y; zoneCeiling = y; } y = boundaryMask.nextSetBit(y + 1); } - paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, resolverState, caveBiomeCache, customBiomeCache); + paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, caveBiomeCache, customBiomeCache); } private void paintBoundaryZone( @@ -501,16 +497,15 @@ public class CaveApplying { int worldZ, int zoneFloor, int zoneCeiling, - IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache ) { IrisBiome floorBiome = resolveCaveBoundaryBiome( walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, - resolverState, caveBiomeCache, customBiomeCache); + caveBiomeCache, customBiomeCache); IrisBiome ceilingBiome = resolveCaveBoundaryBiome( walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, - resolverState, caveBiomeCache, customBiomeCache); + caveBiomeCache, customBiomeCache); if (floorBiome == null && ceilingBiome == null) { return; } @@ -574,7 +569,7 @@ public class CaveApplying { return (h & 15L) == 0L; } - private void processZone(Hunk output, MantleChunk mc, Mantle mantle, CaveZone zone, int rx, int rz, int xx, int zz, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { + private void processZone(Hunk output, MantleChunk mc, Mantle mantle, CaveZone zone, int rx, int rz, int xx, int zz, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { int maxY = output.getHeight(); if (zone.ceiling + 1 < maxY && B.isDecorant(output.getRaw(rx, zone.ceiling + 1, rz))) { @@ -596,8 +591,8 @@ public class CaveApplying { mantle.set(xx, zone.floor, zz, MarkerMatter.CAVE_FLOOR); } - IrisBiome floorBiome = resolveCaveBoundaryBiome(mc, rx, zone.floor, rz, xx, zz, resolverState, caveBiomeCache, customBiomeCache); - IrisBiome ceilingBiome = resolveCaveBoundaryBiome(mc, rx, zone.ceiling, rz, xx, zz, resolverState, caveBiomeCache, customBiomeCache); + IrisBiome floorBiome = resolveCaveBoundaryBiome(mc, rx, zone.floor, rz, xx, zz, caveBiomeCache, customBiomeCache); + IrisBiome ceilingBiome = resolveCaveBoundaryBiome(mc, rx, zone.ceiling, rz, xx, zz, caveBiomeCache, customBiomeCache); if (floorBiome == null && ceilingBiome == null) { return; } @@ -651,10 +646,10 @@ public class CaveApplying { } } - IrisBiome resolveCaveBoundaryBiome(MantleChunk mantleChunk, int x, int y, int z, int worldX, int worldZ, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { + IrisBiome resolveCaveBoundaryBiome(MantleChunk mantleChunk, int x, int y, int z, int worldX, int worldZ, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { MatterCavern cavern = dataIfPresent(mantleChunk, x, y, z, MatterCavern.class); return resolveCaveBoundaryBiome( - cavern, worldX, y, worldZ, resolverState, caveBiomeCache, customBiomeCache); + cavern, worldX, y, worldZ, caveBiomeCache, customBiomeCache); } private static T dataIfPresent(MantleChunk mantleChunk, int x, int y, int z, Class type) { @@ -669,11 +664,11 @@ public class CaveApplying { return matter.getSlice(type).get(x & 15, y & 15, z & 15); } - IrisBiome resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, IrisDimensionCarvingResolver.State resolverState, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { + IrisBiome resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { if (cavern != null && !cavern.getCustomBiome().isEmpty()) { return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); } - return resolveCaveBiome(caveBiomeCache, worldX, y, worldZ, resolverState); + return resolveCaveBiome(caveBiomeCache, worldX, y, worldZ); } static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, PlatformBlockState layer) { @@ -695,16 +690,16 @@ public class CaveApplying { return state != null && state.hasGravity(); } - private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) { - IrisBiome center = sampleCaveBiome(caveBiomeCache, x, y, z, resolverState); + private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z) { + IrisBiome center = sampleCaveBiome(caveBiomeCache, x, y, z); if (center == null) { return null; } - IrisBiome xPos = sampleCaveBiome(caveBiomeCache, x + CAVE_BIOME_BLEND_RADIUS, y, z, resolverState); - IrisBiome xNeg = sampleCaveBiome(caveBiomeCache, x - CAVE_BIOME_BLEND_RADIUS, y, z, resolverState); - IrisBiome zPos = sampleCaveBiome(caveBiomeCache, x, y, z + CAVE_BIOME_BLEND_RADIUS, resolverState); - IrisBiome zNeg = sampleCaveBiome(caveBiomeCache, x, y, z - CAVE_BIOME_BLEND_RADIUS, resolverState); + IrisBiome xPos = sampleCaveBiome(caveBiomeCache, x + CAVE_BIOME_BLEND_RADIUS, y, z); + IrisBiome xNeg = sampleCaveBiome(caveBiomeCache, x - CAVE_BIOME_BLEND_RADIUS, y, z); + IrisBiome zPos = sampleCaveBiome(caveBiomeCache, x, y, z + CAVE_BIOME_BLEND_RADIUS); + IrisBiome zNeg = sampleCaveBiome(caveBiomeCache, x, y, z - CAVE_BIOME_BLEND_RADIUS); if (xPos == center && xNeg == center && zPos == center && zNeg == center) { return center; @@ -727,14 +722,14 @@ public class CaveApplying { return zNeg != null ? zNeg : center; } - private IrisBiome sampleCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z, IrisDimensionCarvingResolver.State resolverState) { + private IrisBiome sampleCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z) { long key = BlockPosition.toLong(x, y, z); IrisBiome cachedBiome = caveBiomeCache.get(key); if (cachedBiome != null) { return cachedBiome; } - IrisBiome resolvedBiome = engine.getCaveBiome(x, y, z, resolverState); + IrisBiome resolvedBiome = engine.getCaveBiome(x, y, z); if (resolvedBiome != null) { caveBiomeCache.put(key, resolvedBiome); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java new file mode 100644 index 000000000..4a67e77c3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java @@ -0,0 +1,61 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.service.CaveBiomes; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * What the carve module tells the host about cave biomes ({@link CaveBiomes}): the biome of the dimension's carving band at a + * position, and how far below the surface a biome's caves begin. + */ +public final class CaveBiomeBands implements CaveBiomes { + @Override + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + Engine engine = IrisPackWorld.of(world).engine(); + ResolvedCarvingEntry rootEntry = CarvingResolver.resolveRootEntry(engine, y + engine.getWorld().minHeight(), null); + if (rootEntry == null) { + return Optional.empty(); + } + ResolvedCarvingEntry entry = CarvingResolver.resolveFromRoot(engine, rootEntry, x, z, null); + if (CarvingResolver.resolveEntryBiome(engine, entry, null) == null) { + return Optional.empty(); + } + return Optional.of(entry.biomeKey().trim()); + } + + @Override + public int minDepthBelowSurface(PackWorld world, String biomeKey) { + IrisBiome biome = IrisPackWorld.of(world).engine().getData().getBiomeLoader().load(biomeKey); + return biome == null ? 0 : minDepthBelowSurface(biome); + } + + /** How many blocks below the surface {@code biome}'s caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ + public static int minDepthBelowSurface(IrisBiome biome) { + return biome.getModuleSettings().find(CaveDepthSettings.class).map(CaveDepthSettings::depth).orElse(0); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 2a8906b69..a6fa011ca 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -30,7 +30,6 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.EngineAssignedComponent; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -102,7 +101,6 @@ public class DepositPlacer extends EngineAssignedComponent { } public void generate(DepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) { - IrisDimensionCarvingResolver.State carvingState = new IrisDimensionCarvingResolver.State(); ResolvedDeposit deposit = resolved(k); if (k.spawnChance() < rng.d()) return; @@ -148,8 +146,7 @@ public class DepositPlacer extends EngineAssignedComponent { boolean oreDeposit = deposit.isOre(); IrisBiome surfaceBiome = context.getBiome().get(x, z); IrisBiome depositBiome = oreDeposit || k.usesCaveBiomeFilter() - ? getEngine().getCaveBiome( - (cx << 4) + x, biomeY, (cz << 4) + z, carvingState) + ? getEngine().getCaveBiome((cx << 4) + x, biomeY, (cz << 4) + z) : null; if (!deposit.matchesBiome(surfaceBiome, depositBiome)) { continue; @@ -211,7 +208,7 @@ public class DepositPlacer extends EngineAssignedComponent { if (chunk.get(nx, ny, nz, MatterCavern.class) == null) { PlatformBlockState ore = clump.getBlocks().get(j); PlatformBlockState remapped = resolveDepositVariant( - cx, cz, nx, ny, nz, ore, dimension, context, carvingState); + cx, cz, nx, ny, nz, ore, dimension, context); PlatformBlockState finalBlock = remapped != null ? remapped : B.toDeepSlateOre(current, ore); @@ -317,12 +314,12 @@ public class DepositPlacer extends EngineAssignedComponent { return Math.max(minimum, Math.min(center, maximum)); } - private PlatformBlockState resolveDepositVariant(int cx, int cz, int nx, int localY, int nz, PlatformBlockState ore, IrisDimension dimension, ChunkContext context, IrisDimensionCarvingResolver.State carvingState) { + private PlatformBlockState resolveDepositVariant(int cx, int cz, int nx, int localY, int nz, PlatformBlockState ore, IrisDimension dimension, ChunkContext context) { int worldX = (cx << 4) + nx; int worldZ = (cz << 4) + nz; int worldY = absoluteWorldY(getEngine().getMinHeight(), localY); - IrisBiome biome = getEngine().getCaveBiome(worldX, localY, worldZ, carvingState); + IrisBiome biome = getEngine().getCaveBiome(worldX, localY, worldZ); if (biome != null) { PlatformBlockState match = matchDepositVariant(biome, ore, worldY); if (match != null) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 70ee4b567..2cc02067c 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; import art.arcane.iris.builtin.prepare.SlopeClip; @@ -225,7 +226,7 @@ public class FloatingIslands { int wx = x + xf; int wz = z + zf; IrisBiome parent = boundarySampler.parent(wx, wz); - if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) { + if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { continue; } FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); @@ -310,7 +311,7 @@ public class FloatingIslands { int wx = x + xf; int wz = z + zf; IrisBiome parent = boundarySampler.parent(wx, wz); - if (parent == null || parent.getFloatingChildBiomes() == null || parent.getFloatingChildBiomes().isEmpty()) { + if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { continue; } FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 691d6ba22..f116a6cdc 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -18,7 +18,8 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; @@ -50,7 +51,8 @@ public final class FloatingModule implements IrisModule { @Override public void register(FeatureRegistry registry) { - registry.registerHeldType(FloatingChildBiome.class); + registry.registerSettings(FloatingChildSettings.class); + registry.registerSettings(MergeFloatingChildrenSettings.class); } @Override diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java new file mode 100644 index 000000000..916e35316 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java @@ -0,0 +1,71 @@ +/* + * 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.terrain.carving; + +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.engine.framework.Engine; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * What the carve module keeps for one world: the cave biome bands its dimension declares ({@link CarvingSettings}) made ready + * ({@link ResolvedCarvingEntry}), in the order the dimension lists them, and by id. + */ +public final class CarvingBands { + private final List entries; + private final Map index; + + CarvingBands(List declared) { + this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); + this.index = indexById(entries); + } + + CarvingBands(Engine engine) { + this(engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of())); + } + + /** The bands of the world {@code engine} generates now. */ + public static CarvingBands of(Engine engine) { + return engine.getGeneration().state(CarvingBands.class, CarvingBands::new); + } + + /** Every declared entry, enabled or not. */ + public List entries() { + return entries; + } + + /** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */ + public Map index() { + return index; + } + + private static Map indexById(List entries) { + Map index = new HashMap<>(); + for (ResolvedCarvingEntry entry : entries) { + if (!entry.id().isBlank()) { + index.put(entry.id().trim(), entry); + } + } + return Map.copyOf(index); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java similarity index 69% rename from src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java rename to src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index 951b70fe9..a4eb736ed 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -1,14 +1,13 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import art.arcane.volmlib.util.collection.KList; import art.arcane.iris.util.project.noise.CNG; +import com.volmit.config.Range; import java.lang.ref.WeakReference; import java.util.ArrayList; @@ -17,36 +16,40 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.Map; -public final class IrisDimensionCarvingResolver { +/** + * Picks the dimension's carving entry for a position: the last enabled root entry whose world Y band holds the height, + * then, through the entries' children, the one a noise pattern selects at the column. The state a caller passes (or, when + * it passes none, the thread's) keeps the picks and the entries' biomes, so a caller resolving many positions reuses them. + */ +public final class CarvingResolver { private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; private static final ThreadLocal> THREAD_STATE = ThreadLocal.withInitial(() -> new WeakReference<>(null)); - private IrisDimensionCarvingResolver() { + private CarvingResolver() { } - public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY) { + public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY) { return resolveRootEntry(engine, worldY, threadState()); } - public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { + public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { State resolvedState = state == null ? threadState() : state; resolvedState.bind(engine); if (resolvedState.rootEntriesByWorldY.containsKey(worldY)) { return resolvedState.rootEntriesByWorldY.get(worldY); } - IrisDimension dimension = engine.getDimension(); - List entries = dimension.getCarving(); - if (entries == null || entries.isEmpty()) { + List entries = resolvedState.bands.entries(); + if (entries.isEmpty()) { resolvedState.rootEntriesByWorldY.put(worldY, null); return null; } - IrisDimensionCarvingEntry resolved = null; - for (IrisDimensionCarvingEntry entry : entries) { + ResolvedCarvingEntry resolved = null; + for (ResolvedCarvingEntry entry : entries) { if (!isRootCandidate(engine, entry, worldY, resolvedState)) { continue; } @@ -58,11 +61,11 @@ public final class IrisDimensionCarvingResolver { return resolved; } - public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldZ) { + public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { return resolveFromRoot(engine, rootEntry, worldX, worldZ, threadState()); } - public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldZ, State state) { + public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ, State state) { State resolvedState = state == null ? threadState() : state; resolvedState.bind(engine); if (rootEntry == null) { @@ -74,22 +77,22 @@ public final class IrisDimensionCarvingResolver { return null; } - int remainingDepth = clampDepth(rootEntry.getChildRecursionDepth()); + int remainingDepth = clampDepth(rootEntry.childRecursionDepth()); if (remainingDepth <= 0) { return rootEntry; } - Map entryIndex = resolveEntryIndex(engine, resolvedState); - IrisDimensionCarvingEntry current = rootEntry; + Map entryIndex = resolvedState.bands.index(); + ResolvedCarvingEntry current = rootEntry; int depth = remainingDepth; while (depth > 0) { - IrisDimensionCarvingEntry selected = selectChild(engine, current, worldX, worldZ, entryIndex, resolvedState); + ResolvedCarvingEntry selected = selectChild(engine, current, worldX, worldZ, entryIndex, resolvedState); if (selected == null || selected == current) { break; } depth--; - int childDepthLimit = clampDepth(selected.getChildRecursionDepth()); + int childDepthLimit = clampDepth(selected.childRecursionDepth()); if (childDepthLimit < depth) { depth = childDepthLimit; } @@ -99,17 +102,17 @@ public final class IrisDimensionCarvingResolver { return current; } - public static IrisBiome resolveEntryBiome(Engine engine, IrisDimensionCarvingEntry entry) { + public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) { return resolveEntryBiome(engine, entry, null); } - public static IrisBiome resolveEntryBiome(Engine engine, IrisDimensionCarvingEntry entry, State state) { + public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry, State state) { if (entry == null) { return null; } if (state == null) { - return entry.getRealBiome(engine.getData()); + return entry.realBiome(engine.getData()); } state.bind(engine); @@ -117,17 +120,17 @@ public final class IrisDimensionCarvingResolver { return state.biomeCache.get(entry); } - IrisBiome biome = entry.getRealBiome(engine.getData()); + IrisBiome biome = entry.realBiome(engine.getData()); state.biomeCache.put(entry, biome); return biome; } - private static boolean isRootCandidate(Engine engine, IrisDimensionCarvingEntry entry, int worldY, State state) { - if (entry == null || !entry.isEnabled()) { + private static boolean isRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY, State state) { + if (entry == null || !entry.enabled()) { return false; } - IrisRange worldYRange = entry.getWorldYRange(); + Range worldYRange = entry.worldYRange(); if (worldYRange != null && !worldYRange.contains(worldY)) { return false; } @@ -135,16 +138,16 @@ public final class IrisDimensionCarvingResolver { return resolveEntryBiome(engine, entry, state) != null; } - private static IrisDimensionCarvingEntry selectChild( + private static ResolvedCarvingEntry selectChild( Engine engine, - IrisDimensionCarvingEntry parent, + ResolvedCarvingEntry parent, int worldX, int worldZ, - Map entryIndex, + Map entryIndex, State state ) { - KList children = parent.getChildren(); - if (children == null || children.isEmpty()) { + List children = parent.children(); + if (children.isEmpty()) { return parent; } @@ -164,7 +167,7 @@ public final class IrisDimensionCarvingResolver { } long seed = resolveChildSeed(engine, state); - CNG childGenerator = parent.getChildrenGenerator(seed, engine.getData()); + CNG childGenerator = parent.childrenGenerator(seed, engine.getData()); double sample = childGenerator.noiseFast2D(worldX, worldZ); int selectedIndex = (int) Math.round(IrisInterpolation.lerp(0, selectionPlan.maxIndex, sample)); CarvingChoice selected = selectionPlan.get(selectedIndex); @@ -177,31 +180,28 @@ public final class IrisDimensionCarvingResolver { private static ParentSelectionPlan buildSelectionPlan( Engine engine, - IrisDimensionCarvingEntry parent, + ResolvedCarvingEntry parent, IrisBiome parentBiome, - Map entryIndex, + Map entryIndex, State state ) { List options = new ArrayList<>(); - KList children = parent.getChildren(); - if (children != null) { - for (String childId : children) { - if (childId == null || childId.isBlank()) { - continue; - } - - IrisDimensionCarvingEntry child = entryIndex.get(childId.trim()); - if (child == null || !child.isEnabled()) { - continue; - } - - IrisBiome childBiome = resolveEntryBiome(engine, child, state); - if (childBiome == null) { - continue; - } - - options.add(new CarvingChoice(child, rarity(childBiome))); + for (String childId : parent.children()) { + if (childId == null || childId.isBlank()) { + continue; } + + ResolvedCarvingEntry child = entryIndex.get(childId.trim()); + if (child == null || !child.enabled()) { + continue; + } + + IrisBiome childBiome = resolveEntryBiome(engine, child, state); + if (childBiome == null) { + continue; + } + + options.add(new CarvingChoice(child, rarity(childBiome))); } options.add(new CarvingChoice(parent, rarity(parentBiome))); @@ -260,14 +260,6 @@ public final class IrisDimensionCarvingResolver { return Math.min(depth, MAX_CHILD_DEPTH); } - private static Map resolveEntryIndex(Engine engine, State state) { - if (state.entryIndex == null) { - state.entryIndex = engine.getDimension().getCarvingEntryIndex(); - } - - return state.entryIndex; - } - private static long resolveChildSeed(Engine engine, State state) { if (state.childSeed == null) { state.childSeed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; @@ -288,13 +280,13 @@ public final class IrisDimensionCarvingResolver { } public static final class State { - private final Map rootEntriesByWorldY = new HashMap<>(); - private final Map selectionPlans = new IdentityHashMap<>(); - private final Map biomeCache = new IdentityHashMap<>(); + private final Map rootEntriesByWorldY = new HashMap<>(); + private final Map selectionPlans = new IdentityHashMap<>(); + private final Map biomeCache = new IdentityHashMap<>(); private WeakReference engineIdentity; private WeakReference dimensionIdentity; private WeakReference dataIdentity; - private Map entryIndex; + private CarvingBands bands; private Long childSeed; private void bind(Engine engine) { @@ -308,10 +300,10 @@ public final class IrisDimensionCarvingResolver { engineIdentity = new WeakReference<>(engine); dimensionIdentity = new WeakReference<>(dimension); dataIdentity = new WeakReference<>(data); + bands = CarvingBands.of(engine); rootEntriesByWorldY.clear(); selectionPlans.clear(); biomeCache.clear(); - entryIndex = null; childSeed = null; } @@ -359,10 +351,10 @@ public final class IrisDimensionCarvingResolver { } private static final class CarvingChoice implements IRare { - private final IrisDimensionCarvingEntry entry; + private final ResolvedCarvingEntry entry; private final int rarity; - private CarvingChoice(IrisDimensionCarvingEntry entry, int rarity) { + private CarvingChoice(ResolvedCarvingEntry entry, int rarity) { this.entry = entry; this.rarity = rarity; } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java new file mode 100644 index 000000000..55628bb16 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java @@ -0,0 +1,33 @@ +/* + * 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.terrain.carving; + +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.core.loader.IrisRegistrant; + +/** The cave profiles dimensions, regions and biomes declare ({@code caveProfile}). */ +public final class CaveProfiles { + private CaveProfiles() { + } + + /** The profile {@code owner}, a dimension, region or biome, declares; null when it declares none, which is as good as one that is not enabled. */ + public static CaveProfile declaredBy(IrisRegistrant owner) { + return owner.getModuleSettings().find(CaveProfile.class).orElse(null); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java deleted file mode 100644 index 6256fc281..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisDimensionCarvingEntry.java +++ /dev/null @@ -1,84 +0,0 @@ -package art.arcane.iris.engine.object.terrain.carving; - -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.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.DependsOn; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -@Snippet("dimension-carving-entry") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Dimension-level cave biome override with absolute world Y bounds.") -@Data -public class IrisDimensionCarvingEntry { - private final transient AtomicCache realBiome = new AtomicCache<>(true); - private final transient Map childGenerators = new ConcurrentHashMap<>(); - - @Desc("Stable id for this carving entry") - private String id = ""; - - @Desc("Enable or disable this carving entry") - private boolean enabled = true; - - @RegistryListResource(IrisBiome.class) - @Desc("Cave biome to apply when world Y falls within worldYRange") - private String biome = ""; - - @Desc("Absolute world Y bounds where this carving entry applies") - private IrisRange worldYRange = new IrisRange(-64, 320); - - @DependsOn({"children"}) - @Desc("If this carving entry has child carving entries, this controls how small those child carving patches are.") - private double childShrinkFactor = 1.5; - - @DependsOn({"children"}) - @Desc("If this carving entry has child carving entries, this controls the shape pattern used to pick them.") - private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @ArrayType(min = 1, type = String.class) - @Desc("Child carving entry ids. Child ids can point back to parent ids to create cycles; recursion is bounded by childRecursionDepth.") - private KList children = new KList<>(); - - @Desc("Maximum recursion depth when resolving child carving entries from this entry.") - private int childRecursionDepth = 3; - - public IrisBiome getRealBiome(IrisData data) { - return realBiome.aquire(() -> { - String biomeKey = getBiome(); - if (biomeKey == null || biomeKey.isBlank()) { - return null; - } - - return data.getBiomeLoader().load(biomeKey.trim()); - }); - } - - public CNG getChildrenGenerator(long seed, IrisData data) { - String entryId = getId(); - long idHash = entryId == null ? 0L : entryId.trim().hashCode(); - long generatorSeed = seed ^ (idHash << 32) ^ 2137L; - return childGenerators.computeIfAbsent(generatorSeed, key -> { - double scale = Math.max(0.0001D, getChildShrinkFactor()); - RNG random = new RNG(key); - return getChildStyle().create(random.nextParallelRNG(2137), data).bake().scale(scale).bake(); - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java new file mode 100644 index 000000000..fc880344d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -0,0 +1,101 @@ +/* + * 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.terrain.carving; + +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisValues; +import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Range; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * One {@link CarvingEntry} made ready for one world: the biome it names, loaded from the pack when first asked for, and the + * noise that splits it into child entries, built once per seed. What the entry describes stays in the settings. + */ +public final class ResolvedCarvingEntry { + private static final long CHILD_GENERATOR_SALT = 2137L; + private static final int CHILD_GENERATOR_SIGNATURE = 2137; + private static final double MIN_CHILD_SCALE = 0.0001D; + + private final CarvingEntry settings; + private final IrisGeneratorStyle childStyle; + private final AtomicCache realBiome = new AtomicCache<>(true); + private final Map childGenerators = new ConcurrentHashMap<>(); + + ResolvedCarvingEntry(CarvingEntry settings) { + this.settings = settings; + this.childStyle = IrisValues.generatorStyle(settings.childStyle()); + } + + public String id() { + return settings.id(); + } + + public boolean enabled() { + return settings.enabled(); + } + + /** The biome key the entry names, as the pack wrote it. */ + public String biomeKey() { + return settings.biome(); + } + + public Range worldYRange() { + return settings.worldYRange(); + } + + public List children() { + return settings.children(); + } + + public int childRecursionDepth() { + return settings.childRecursionDepth(); + } + + /** The pack biome the entry names; null when it names none or the pack has no such biome. */ + public IrisBiome realBiome(IrisData data) { + return realBiome.aquire(() -> { + String biomeKey = settings.biome(); + if (biomeKey.isBlank()) { + return null; + } + + return data.getBiomeLoader().load(biomeKey.trim()); + }); + } + + /** The noise that picks between the entry and its children, seeded by {@code seed} and the entry's id. */ + public CNG childrenGenerator(long seed, IrisData data) { + long idHash = settings.id().trim().hashCode(); + long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; + return childGenerators.computeIfAbsent(generatorSeed, key -> { + double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor()); + RNG random = new RNG(key); + return childStyle.create(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), data).bake().scale(scale).bake(); + }); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java index 2a7492f4c..dd2ad533e 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java @@ -19,8 +19,11 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.world.biome.IrisBiome; import java.util.List; import java.util.Map; @@ -46,6 +49,16 @@ public final class FloatingChildren { return engine.getGeneration().state(FloatingChildren.class, FloatingChildren::new); } + /** The floating children {@code biome} declares, in the order it lists them; none when it declares none. */ + public static List declaredBy(IrisBiome biome) { + return biome.getModuleSettings().find(FloatingChildSettings.class).map(FloatingChildSettings::children).orElse(List.of()); + } + + /** Whether {@code biome} samples every floating child on its own and unions their islands instead of picking one per column. */ + public static boolean merges(IrisBiome biome) { + return biome.getModuleSettings().find(MergeFloatingChildrenSettings.class).map(MergeFloatingChildrenSettings::merge).orElse(false); + } + public ResolvedFloatingChild of(FloatingChildBiome settings) { return resolved.computeIfAbsent(settings, ResolvedFloatingChild::new); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 7fc7b6f1c..ae339e57f 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -196,8 +196,8 @@ public final class FloatingIslandSample { } public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { - List settings = parent.getFloatingChildBiomes(); - if (settings == null || settings.isEmpty()) { + List settings = FloatingChildren.declaredBy(parent); + if (settings.isEmpty()) { return reject(REJECT_NO_ENTRIES); } KList entries = new KList<>(FloatingChildren.of(data).of(settings)); @@ -208,7 +208,7 @@ public final class FloatingIslandSample { int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent); int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); - if (parent.isMergeFloatingChildBiomes()) { + if (FloatingChildren.merges(parent)) { return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, parentBoundaryDistance, boundaryFieldWidth); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index e50ec5226..518bb6fbc 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -18,20 +18,22 @@ package art.arcane.iris.engine.object.terrain.floating; +import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisValues; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObjectScale; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; +import art.arcane.iris.engine.object.terrain.carving.CarvingBands; +import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -137,11 +139,12 @@ public final class ResolvedFloatingChild implements IRare { return carvingProfileSamplerCache.aquire(() -> { IrisBiome resolved = resolveCarvingBiome(settings.carving(), engine, data); - if (resolved == null || resolved.getCaveProfile() == null || !resolved.getCaveProfile().enabled()) { + CaveProfile profile = resolved == null ? null : CaveProfiles.declaredBy(resolved); + if (profile == null || !profile.enabled()) { return null; } - return new IrisCaveProfileSampler(engine, resolved.getCaveProfile()); + return new IrisCaveProfileSampler(engine, profile); }); } @@ -155,12 +158,9 @@ public final class ResolvedFloatingChild implements IRare { return null; } - IrisDimension dimension = engine.getDimension(); - if (dimension != null && dimension.getCarvingEntryIndex() != null) { - IrisDimensionCarvingEntry entry = dimension.getCarvingEntryIndex().get(carving); - if (entry != null) { - return IrisDimensionCarvingResolver.resolveEntryBiome(engine, entry); - } + ResolvedCarvingEntry entry = CarvingBands.of(engine).index().get(carving); + if (entry != null) { + return CarvingResolver.resolveEntryBiome(engine, entry); } if (data.getBiomeLoader() == null) { 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 index d6da53ad2..63f928f93 100644 --- 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 @@ -18,8 +18,6 @@ package art.arcane.iris.engine.object.world.biome; -import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.entity.IrisEffect; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.loot.IrisBlockDrops; @@ -104,7 +102,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { private transient volatile SeededBiomeGenerator recentBiomeGenerator; private final transient AtomicCache maxHeight = new AtomicCache<>(); private final transient AtomicCache maxWithObjectHeight = new AtomicCache<>(); - private final transient AtomicCache realCarveBiome = new AtomicCache<>(); private final transient AtomicCache> realChildren = new AtomicCache<>(); private final transient AtomicCache> layerHeightGenerators = new AtomicCache<>(); private final transient AtomicCache> layerSeaHeightGenerators = new AtomicCache<>(); @@ -138,8 +135,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { private boolean lockLayers = false; @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") private int lockLayersMax = 7; - @Desc("Profile-driven 3D cave configuration") - private CaveProfile caveProfile = new CaveProfile(); @MinNumber(1) @MaxNumber(512) @Desc("The rarity of this biome (integer)") @@ -172,13 +167,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @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<>(); - @RegistryListResource(IrisBiome.class) - @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") - private String carvingBiome = ""; - @MinNumber(0) - @MaxNumber(256) - @Desc("Minimum depth below terrain surface required before this cave biome can be selected.") - private int caveMinDepthBelowSurface = 0; @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") private IrisBiomePaletteLayer slab = new IrisBiomePaletteLayer().zero(); @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") @@ -201,11 +189,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @ArrayType(min = 1, type = IrisStructurePlacement.class) @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this biome") private KList structures = new KList<>(); - @ArrayType(min = 1, type = FloatingChildBiome.class) - @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") - private KList floatingChildBiomes = new KList<>(); - @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") - private boolean mergeFloatingChildBiomes = false; @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()); @@ -321,19 +304,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { return IrisBiomeGenLinks.getGenLink(this, loadKey); } - public IrisBiome getRealCarvingBiome(IrisData data) { - return realCarveBiome.aquire(() -> - { - IrisBiome biome = data.getBiomeLoader().load(getCarvingBiome()); - - if (biome == null) { - biome = this; - } - - return biome; - }); - } - public KList getSurfaceObjects() { return getSurfaceObjectsCache().aquire(() -> { 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 index b59850df2..3f007b2e2 100644 --- 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 @@ -18,8 +18,6 @@ package art.arcane.iris.engine.object.world.dimension; -import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.image.IrisImageMap; @@ -34,7 +32,6 @@ import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.procedural.tree.IrisTreeSettings; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.terrain.carving.IrisDimensionCarvingEntry; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.world.IrisEnvironment; import art.arcane.iris.engine.object.world.IrisWorldBoundary; @@ -45,7 +42,6 @@ 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.spi.PlatformBlockState; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.nms.datapack.DataVersion; import art.arcane.iris.core.nms.datapack.IDataFixer; @@ -84,7 +80,6 @@ import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayDeque; import java.util.Deque; -import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Locale; @@ -110,7 +105,6 @@ public class IrisDimension extends IrisRegistrant { private final transient AtomicCache cosr = new AtomicCache<>(); private final transient AtomicCache rad = new AtomicCache<>(); private final transient AtomicCache featuresUsed = new AtomicCache<>(); - private final transient AtomicCache> carvingEntryIndex = new AtomicCache<>(); @MinNumber(2) @Required @Desc("The human readable name of this dimension") @@ -175,13 +169,6 @@ public class IrisDimension extends IrisRegistrant { private boolean postProcessingSlabs = true; @Desc("Add painted walls in post processing") private boolean postProcessingWalls = true; - @Desc("Enable or disable all carving for this dimension") - private boolean carvingEnabled = true; - @ArrayType(type = IrisDimensionCarvingEntry.class, min = 1) - @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") - private KList carving = new KList<>(); - @Desc("Profile-driven 3D cave configuration") - private CaveProfile caveProfile = new CaveProfile(); @Desc("Refuse to place surface objects and trees over carved surface openings.") private boolean requireObjectSurfaceSupport = true; @MinNumber(0) @@ -298,36 +285,6 @@ public class IrisDimension extends IrisRegistrant { return (int) getDimensionHeight().getMin(); } - public Map getCarvingEntryIndex() { - return carvingEntryIndex.aquire(() -> { - Map index = new HashMap<>(); - KList entries = getCarving(); - if (entries == null || entries.isEmpty()) { - return index; - } - - for (IrisDimensionCarvingEntry entry : entries) { - if (entry == null) { - continue; - } - - String entryId = entry.getId(); - if (entryId == null || entryId.isBlank()) { - continue; - } - - index.put(entryId.trim(), entry); - } - - return index; - }); - } - - public void setCarving(KList carving) { - this.carving = carving == null ? new KList<>() : carving; - carvingEntryIndex.reset(); - } - public int getFluidHeight() { return fluidHeight - (int) dimensionHeight.getMin(); } @@ -449,17 +406,9 @@ public class IrisDimension extends IrisRegistrant { } } - KList carvingEntries = getCarving(); - if (carvingEntries != null) { - for (IrisDimensionCarvingEntry entry : carvingEntries) { - if (entry != null && entry.isEnabled()) { - addReachableBiomeKey(pending, entry.getBiome()); - } - } - } + addReachableBiomeKeys(pending, getModuleSettings().usedBiomes(getModuleSettings())); Set visited = new HashSet<>(); - Map carvingEntryIndex = getCarvingEntryIndex(); while (!pending.isEmpty()) { String biomeKey = pending.removeFirst(); if (!visited.add(biomeKey)) { @@ -479,20 +428,8 @@ public class IrisDimension extends IrisRegistrant { visited.add(loadKey); biomes.put(loadKey, biome); addReachableBiomeKeys(pending, biome.getChildren()); - addReachableBiomeKey(pending, biome.getCarvingBiome()); - KList floatingChildren = biome.getFloatingChildBiomes(); - if (floatingChildren == null) { - continue; - } - for (FloatingChildBiome floatingChild : floatingChildren) { - if (floatingChild != null) { - addReachableBiomeKey(pending, floatingChild.biome()); - String carvingReference = floatingChild.carving(); - IrisDimensionCarvingEntry carvingEntry = carvingEntryIndex.get(carvingReference); - addReachableBiomeKey(pending, - carvingEntry == null ? carvingReference : carvingEntry.getBiome()); - } - } + addReachableBiomeKeys(pending, biome.getModuleSettings().treeBiomes()); + addReachableBiomeKeys(pending, biome.getModuleSettings().usedBiomes(getModuleSettings())); } return biomes.v(); 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 index 60b0583ce..3bc2a7fd0 100644 --- 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 @@ -18,7 +18,6 @@ package art.arcane.iris.engine.object.world.region; -import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.entity.IrisEffect; import art.arcane.iris.engine.object.entity.spawn.IrisSpawner; import art.arcane.iris.engine.object.loot.IrisBlockDrops; @@ -32,7 +31,6 @@ 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.spi.PlatformBlockState; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.object.annotations.ArrayType; @@ -123,8 +121,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { @MinNumber(0.0001) @Desc("How large cave biomes are in this region") private double caveBiomeZoom = 1; - @Desc("Profile-driven 3D cave configuration") - private CaveProfile caveProfile = new CaveProfile(); @RegistryListResource(IrisBiome.class) @Required @ArrayType(min = 1, type = String.class) @@ -216,7 +212,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { continue; } - names.add(biome.getCarvingBiome()); + names.addAll(biome.getModuleSettings().treeBiomes()); b.put(biome.getLoadKey(), biome); names.addAll(biome.getChildren()); } @@ -313,7 +309,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { continue; } - names.add(biome.getCarvingBiome()); + names.addAll(biome.getModuleSettings().treeBiomes()); b.put(biome.getLoadKey(), biome); names.addAll(biome.getChildren()); } From c9efe0d73d5d39aee96409cbe27f1f2faa32e528 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 08:53:57 +0200 Subject: [PATCH 053/139] ObjectPlacing: a dimension without a cave profile falls back to one shared default profile --- .../arcane/iris/engine/mantle/components/ObjectPlacing.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 288e9c139..80e64d2e1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -79,6 +79,7 @@ import java.util.concurrent.atomic.AtomicLong; * placement reach of any object the dimension can place. */ public class ObjectPlacing { + private static final CaveProfile DEFAULT_CAVE_PROFILE = new CaveProfile(); private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L; private static final int BEDROCK_CLEARANCE = 6; private static final byte LIQUID_FORCED_AIR = 3; @@ -1333,7 +1334,7 @@ public class ObjectPlacing { return dimensionProfile; } - return new CaveProfile(); + return DEFAULT_CAVE_PROFILE; } private CaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, CaveProfile caveProfile) { From 697d21f8a445d541873653940c155ace320dc881 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:00:03 +0200 Subject: [PATCH 054/139] PlacementLoot takes the placement's lists, so its picks can be tested --- .../art/arcane/iris/engine/loot/LootGiving.java | 2 +- .../art/arcane/iris/engine/loot/PlacementLoot.java | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 94af45f91..94db333c0 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -55,7 +55,7 @@ public final class LootGiving implements Loot { IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z); if (placement != null) { objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty(); - Source picked = placementLoot(world, engine).pick(placement, platformState(site), rng, x, worldY, z); + Source picked = placementLoot(world, engine).pick(placement.getVanillaLoot(), placement.getLoot(), platformState(site), rng, x, worldY, z); if (picked != null) { sources.add(picked); if (placement.isOverrideGlobalLoot()) { diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index 18ef3d37f..e059d4a06 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.loot.IObjectLoot; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; @@ -61,13 +60,15 @@ final class PlacementLoot { } /** - * The table the placement gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, - * {@code z}; null when it gives it none. + * The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot}, + * gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives + * it none. */ - Loot.Source pick(IrisObjectPlacement placement, PlatformBlockState container, RNG rng, int x, int worldY, int z) { + Loot.Source pick(List platformLoot, List packLoot, PlatformBlockState container, + RNG rng, int x, int worldY, int z) { Candidates candidates = new Candidates(container); - add(candidates, placement.getVanillaLoot(), name -> platformSource(name, x, worldY, z)); - add(candidates, placement.getLoot(), this::packSource); + add(candidates, platformLoot, name -> platformSource(name, x, worldY, z)); + add(candidates, packLoot, this::packSource); List pool = candidates.pool(); Candidate picked = LootResolver.pickWeighted(pool, Candidate::weight, rng); return picked == null ? null : picked.source(); From 651ff77c8514da658fa011da5ae787d176b112fb Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:01:15 +0200 Subject: [PATCH 055/139] README: iris:loot and iris:spawn settings, AmbientEffects, PlacementLoot --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4bf62dc47..7c52a866b 100644 --- a/README.md +++ b/README.md @@ -39,8 +39,15 @@ objects are trees) and says which biomes and regions place an object (`ObjectLoc them (`LootValidator`), and provides `Loot` (`LootGiving`: which tables a container draws from and the `ItemDrop`s a table gives) and `BlockDrops` (`BlockDropping`). `iris:spawn` owns spawners, entities and markers (`SpawnResources`, folders `spawners`, `entities`, `markers`) and provides `EntitySpawns` (`EntitySpawning`: what to spawn in a chunk or at -a marker, as `EntitySpec`s; `EntityResolution` makes the entity's random choices). Iris's Bukkit code creates the items -and entities from those values (`BukkitItemStacks`, `BukkitEntitySpawner`). +a marker, as `EntitySpec`s; `EntityResolution` makes the entity's random choices) and `AmbientEffects` (`AmbientEffecting`: +the effects due around a player, with their random values). Iris's Bukkit code creates the items and entities from those +values (`BukkitItemStacks`, `BukkitEntitySpawner`, `BukkitAmbientEffects`); the modded adapters, which cannot name IrisApi +types, ask through the host-typed `ContentServices`. +The settings of both modules are `builtin.loot` and `builtin.spawn` types of IrisApi annotations only: `iris:loot` declares +`loot` (object, also the shape of an entity's `loot`) and `blockDrops` (list) for dimensions, regions and biomes; +`iris:spawn` declares `entitySpawners` (list of spawner keys) for the same and `effects` (list, `iris:spawn/effects`) for +regions and biomes. The loot tables, spawners, entities and markers are plain module types too (`LootTable`, `Spawner`, +`EntityDefinition`, `SpawnMarker`). `PlacementLoot` picks the table an object placement gives one of its chests. `iris:decorant` keeps its per-world `Decorating` in the world's state store (`context.world().state(...)`); the other built-ins still reach the same store through `IrisChunk.state(...)` / `engine.getGeneration().state(...)`. From bf2a0b5e5960bcb655ec9b54ebd4bc179f112aa1 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:10:24 +0200 Subject: [PATCH 056/139] iris:post, iris:perfection and iris:matter use only IrisApi and art.arcane.iris.builtin; PendingSettings carries the dimension and biome settings C and T are moving; built-ins order after the jar's stages without requiring them --- .../arcane/iris/builtin/PendingSettings.java | 65 +++ .../iris/engine/actuator/DecorantModule.java | 3 +- .../iris/engine/modifier/CustomModule.java | 3 +- .../iris/engine/modifier/FloatingModule.java | 3 +- .../iris/engine/modifier/MatterModule.java | 95 ++-- .../engine/modifier/PerfectionModule.java | 191 ++++--- .../iris/engine/modifier/PostModule.java | 18 +- .../engine/modifier/SurfaceSmoothing.java | 532 +++++++++--------- 8 files changed, 459 insertions(+), 451 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/PendingSettings.java diff --git a/src/main/java/art/arcane/iris/builtin/PendingSettings.java b/src/main/java/art/arcane/iris/builtin/PendingSettings.java new file mode 100644 index 000000000..e9010b830 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/PendingSettings.java @@ -0,0 +1,65 @@ +/* + * 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.builtin; + +import com.volmit.block.BlockState; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * Transitional: settings Iris's built-in modules read that still live on Iris's dimension and biome classes while + * wave 3a moves them into module settings, {@code hideOresForHiddenOre} (agent C) and {@code postProcessingWalls}, + * {@code postProcessingSlabs} and a biome's {@code wall} and {@code slab} (agent T). Iris's worlds implement it. When + * those settings land, each method gives way to a read of its module setting and this type is deleted; nothing else + * may use it. + */ +public interface PendingSettings { + /** The pending settings of {@code world}, which must be a world Iris generates. */ + static PendingSettings of(PackWorld world) { + if (world instanceof PendingSettings pending) { + return pending; + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** The dimension's {@code hideOresForHiddenOre}. */ + boolean hidesOres(); + + /** The dimension's {@code postProcessingWalls}. */ + boolean postProcessingWalls(); + + /** The dimension's {@code postProcessingSlabs}. */ + boolean postProcessingSlabs(); + + /** The {@code wall} of the surface biome of the column at {@code x}, {@code z}; empty when its palette lists no block. */ + Optional wall(int x, int z); + + /** The {@code slab} of the surface biome of the column at {@code x}, {@code z}. */ + BiomeLayer slab(int x, int z); + + /** One of a biome's palette layers, picking as Iris always picked it, with the world's post-processing seed. */ + interface BiomeLayer { + /** The block the layer picks at {@code x}, {@code y}, {@code z}; empty when none of its blocks exists. */ + Optional at(double x, double y, double z); + + /** Whether the layer's slope condition holds where the terrain's slope is {@code slope}. */ + boolean allowsSlope(double slope); + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index bf486e46c..a86b1b286 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -72,7 +72,8 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Decorant.DECORATE).requires(IrisStages.Matter.INSERT).run(DecorantModule::decorate); + // Ordering only: iris:matter ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT.ref()).run(DecorantModule::decorate); } private static void decorate(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java index a88cf7566..763bc40a9 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java @@ -51,7 +51,8 @@ public final class CustomModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Custom.BLOCKS).requires(IrisStages.Perfection.SURFACE).run(CustomModule::record); + // Ordering only: iris:perfection ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Custom.BLOCKS).softAfter(IrisStages.Perfection.SURFACE.ref()).run(CustomModule::record); } private static void record(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 691d6ba22..27c7fc31b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -57,7 +57,8 @@ public final class FloatingModule implements IrisModule { public void install(StageGraph graph) { graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE.ref()).reach(FloatingModule::objectReach) .run(FloatingModule::objects); - graph.define(IrisStages.Floating.SOLIDS).requires(IrisStages.Post.SMOOTH).run(FloatingModule::solids); + // Ordering only: iris:post ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH.ref()).run(FloatingModule::solids); graph.define(IrisStages.Floating.DECORATE).requires(IrisStages.Decorant.DECORATE).run(FloatingModule::decorate); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java index 4bbb8e0cc..248cdd926 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -19,29 +19,25 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.BlockBox; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.TerrainSampler; /** * Module {@code iris:matter}: copies the blocks the mantle planned for the chunk, its objects and structures, - * into it, unless the dimension turns the mantle off ({@code useMantle}). Where an upper dimension sits above, - * blocks at or above its surface are left out. It orders itself after deposits without requiring them, since - * deposits run only where a level declares some. + * into it (a dimension with {@code useMantle} off plans none). Where an upper dimension sits above, blocks at or + * above where it begins are left out. It orders itself after deposits without requiring them, since deposits run + * only where a level declares some. */ public final class MatterModule implements IrisModule { private static final String VERSION = "built-in"; - private static final int CHUNK_SHIFT = 4; - private static final int CHUNK_COLUMNS = 16 * 16; + private static final int CHUNK_WIDTH = 16; + private static final int NO_LIMIT = Integer.MAX_VALUE; @Override public ModuleInfo info() { @@ -57,59 +53,32 @@ public final class MatterModule implements IrisModule { } private static void insert(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - if (chunk.bypassesMantleStages()) { - return; - } - chunk.state(MatterInsertion.class, MatterInsertion::new).insert(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.blocks()); + int originX = context.originX(); + int originZ = context.originZ(); + Hunk blocks = context.hunk(BlockState.class); + int[] limits = upperLimits(context.terrain(), originX, originZ); + BlockBox chunk = new BlockBox(originX, 0, originZ, originX + CHUNK_WIDTH, blocks.getHeight(), originZ + CHUNK_WIDTH); + context.mantle().blocks().visit(chunk, (x, y, z, block) -> { + int localX = x - originX; + int localZ = z - originZ; + if (y < limits[column(localX, localZ)]) { + blocks.set(localX, y, localZ, block); + } + }); } - /** Copies the mantle's blocks into chunks for one engine runtime. */ - static final class MatterInsertion { - private final Engine engine; - - MatterInsertion(Engine engine) { - this.engine = engine; - } - - /** Copies the blocks the mantle holds for chunk {@code x}, {@code z} into {@code blocks}. */ - @ChunkCoordinates - void insert(int x, int z, Hunk blocks) { - if (!engine.getDimension().isUseMantle()) { - return; - } - - UpperDimensionContext upperCtx = engine.getUpperContext(); - boolean protectUpper = upperCtx != null; - - MantleChunk chunk = engine.getMantle().getMantle().getChunk(x, z).use(); - try { - if (protectUpper) { - int chunkBlockX = x << CHUNK_SHIFT; - int chunkBlockZ = z << CHUNK_SHIFT; - int gap = engine.getDimension().getUpperDimensionGap(); - int[] upperYs = new int[CHUNK_COLUMNS]; - for (int i = 0; i < CHUNK_COLUMNS; i++) { - int lx = i >> 4; - int lz = i & 15; - int worldX = chunkBlockX + lx; - int worldZ = chunkBlockZ + lz; - int he = (int) Math.round(engine.getComplex().getHeightStream().get((double) worldX, (double) worldZ)); - int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); - upperYs[i] = Math.max(rawUpper, he + gap); - } - chunk.iterate(PlatformBlockState.class, (lx, y, lz, value) -> { - int colIdx = (lx << 4) | (lz & 15); - if (y < upperYs[colIdx]) { - blocks.set(lx, y, lz, value); - } - }); - } else { - chunk.iterate(PlatformBlockState.class, (lx, y, lz, value) -> blocks.set(lx, y, lz, value)); - } - } finally { - chunk.release(); + /** Per column, the height from which the upper dimension takes over, or no limit. */ + static int[] upperLimits(TerrainSampler terrain, int originX, int originZ) { + int[] limits = new int[CHUNK_WIDTH * CHUNK_WIDTH]; + for (int localX = 0; localX < CHUNK_WIDTH; localX++) { + for (int localZ = 0; localZ < CHUNK_WIDTH; localZ++) { + limits[column(localX, localZ)] = terrain.upperDimensionY(originX + localX, originZ + localZ).orElse(NO_LIMIT); } } + return limits; + } + + private static int column(int localX, int localZ) { + return localX * CHUNK_WIDTH + localZ; } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index 6e45f193f..897ef2a90 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -19,21 +19,20 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import art.arcane.iris.builtin.PendingSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; import java.util.ArrayList; import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; @@ -45,12 +44,8 @@ import java.util.Map; public final class PerfectionModule implements IrisModule { private static final String VERSION = "built-in"; private static final String HALF = "half"; - private static final char PROPERTIES_START = '['; - - private static final class States { - private static final PlatformBlockState AIR = B.getState("AIR"); - private static final Map ORE_BASES = oreBases(); - } + private static final BlockState AIR = new BlockState("minecraft:air"); + private static final Map ORE_BASES = oreBases(); @Override public ModuleInfo info() { @@ -63,121 +58,123 @@ public final class PerfectionModule implements IrisModule { } private static void perfect(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - Engine engine = chunk.engine(); - IrisDimension dimension = engine.getDimension(); - PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); - Hunk blocks = chunk.blocks(); - if (dimension.isHideOresForHiddenOre()) { - hideOres(blocks); + Hunk blocks = context.hunk(BlockState.class); + if (PendingSettings.of(context.world()).hidesOres()) { + hideOres(blocks, new IdentityHashMap<>()); } + Surfaces surfaces = new Surfaces(blocks, context.resources().blocks(), new IdentityHashMap<>()); boolean removed; do { - removed = removeUnsupportedDecorants(blocks); + removed = surfaces.removeUnsupportedDecorants(); } while (removed); - engine.getMetrics().getPerfection().put(stopwatch.getMilliseconds()); } - private static void hideOres(Hunk blocks) { + /** {@code hidden} remembers per state instance what it is hidden as, itself for a block that is no ore. */ + private static void hideOres(Hunk blocks, Map hidden) { for (int x = 0; x < blocks.getWidth(); x++) { for (int z = 0; z < blocks.getDepth(); z++) { for (int y = blocks.getHeight() - 1; y >= 0; y--) { - PlatformBlockState block = blocks.get(x, y, z); - PlatformBlockState base = block == null ? null : States.ORE_BASES.get(materialOf(block)); - if (base != null) { - blocks.set(x, y, z, base); + BlockState block = blocks.get(x, y, z); + BlockState shown = hidden.computeIfAbsent(block, state -> ORE_BASES.getOrDefault(state.material(), state)); + if (shown != block) { + blocks.set(x, y, z, shown); } } } } } - /** One pass over every column; whether it removed anything. */ - private static boolean removeUnsupportedDecorants(Hunk blocks) { - boolean removed = false; - for (int x = 0; x < blocks.getWidth(); x++) { - for (int z = 0; z < blocks.getDepth(); z++) { - for (int surface : surfaces(blocks, x, z)) { - removed |= removeIfUnsupported(blocks, x, surface, z); + /** + * The decorations of one chunk and the ground they stand on. Finding the surfaces asks about every block of the chunk, + * which holds few distinct states, so whether a state is solid is asked once per state instance. + */ + private record Surfaces(Hunk blocks, BlockRegistry registry, Map solidStates) { + /** One pass over every column; whether it removed anything. */ + boolean removeUnsupportedDecorants() { + boolean removed = false; + for (int x = 0; x < blocks.getWidth(); x++) { + for (int z = 0; z < blocks.getDepth(); z++) { + for (int surface : surfaces(x, z)) { + removed |= removeIfUnsupported(x, surface, z); + } } } + return removed; } - return removed; - } - /** The topmost solid block of a column and each solid block with open space above it below that. */ - private static List surfaces(Hunk blocks, int x, int z) { - List surfaces = new ArrayList<>(); - int top = topSolid(blocks, x, z); - surfaces.add(top); - boolean inside = true; - for (int y = top; y >= 0; y--) { - boolean solid = isSolid(blocks.get(x, y, z)); - if (solid != inside) { - inside = solid; - if (inside) { - surfaces.add(y); + /** The topmost solid block of a column and each solid block with open space above it below that. */ + private List surfaces(int x, int z) { + List surfaces = new ArrayList<>(); + int top = topSolid(x, z); + surfaces.add(top); + boolean inside = true; + for (int y = top; y >= 0; y--) { + boolean solid = isSolid(blocks.get(x, y, z)); + if (solid != inside) { + inside = solid; + if (inside) { + surfaces.add(y); + } } } + return surfaces; } - return surfaces; - } - private static boolean removeIfUnsupported(Hunk blocks, int x, int y, int z) { - PlatformBlockState tip = blocks.get(x, y, z); - if (tip == null || !B.isDecorant(tip)) { - return false; - } - PlatformBlockState below = blocks.get(x, y - 1, z); - if (below == null || !B.canPlaceOnto(tip, below)) { - blocks.set(x, y, z, States.AIR); + private boolean removeIfUnsupported(int x, int y, int z) { + BlockState tip = blocks.get(x, y, z); + if (!registry.hasTrait(tip, BlockTrait.DECORATION)) { + return false; + } + BlockState below = blockAt(x, y - 1, z); + if (below == null || !registry.canPlaceOn(tip, below)) { + blocks.set(x, y, z, AIR); + return true; + } + if (!below.properties().containsKey(HALF)) { + return false; + } + BlockState belowBelow = blockAt(x, y - 2, z); + if (belowBelow != null && registry.canPlaceOn(below, belowBelow)) { + return false; + } + blocks.set(x, y, z, AIR); + blocks.set(x, y - 1, z, AIR); return true; } - if (!IrisProceduralBlocks.hasProperty(below, HALF)) { - return false; - } - PlatformBlockState belowBelow = blocks.get(x, y - 2, z); - if (belowBelow != null && B.canPlaceOnto(below, belowBelow)) { - return false; - } - blocks.set(x, y, z, States.AIR); - blocks.set(x, y - 1, z, States.AIR); - return true; - } - private static int topSolid(Hunk blocks, int x, int z) { - for (int y = blocks.getHeight() - 1; y >= 0; y--) { - if (isSolid(blocks.get(x, y, z))) { - return y; + private int topSolid(int x, int z) { + for (int y = blocks.getHeight() - 1; y >= 0; y--) { + if (isSolid(blocks.get(x, y, z))) { + return y; + } } + return 0; + } + + private boolean isSolid(BlockState block) { + return solidStates.computeIfAbsent(block, state -> !(registry.hasTrait(state, BlockTrait.AIR) || registry.hasTrait(state, BlockTrait.FLUID))); + } + + /** The block at {@code y}, or null below the chunk's bottom. */ + private BlockState blockAt(int x, int y, int z) { + return y < 0 ? null : blocks.get(x, y, z); } - return 0; } - private static boolean isSolid(PlatformBlockState block) { - return block != null && !(B.isAir(block) || B.isFluid(block)); - } - - private static String materialOf(PlatformBlockState state) { - String key = state.key(); - int properties = key.indexOf(PROPERTIES_START); - return properties < 0 ? key : key.substring(0, properties); - } - - private static Map oreBases() { - Map bases = new HashMap<>(); - PlatformBlockState stone = B.getState("STONE"); - PlatformBlockState deepslate = B.getState("DEEPSLATE"); - PlatformBlockState netherrack = B.getState("NETHERRACK"); - PlatformBlockState blackstone = B.getState("BLACKSTONE"); + private static Map oreBases() { + Map bases = new HashMap<>(); + BlockState stone = new BlockState("minecraft:stone"); + BlockState deepslate = new BlockState("minecraft:deepslate"); + BlockState netherrack = new BlockState("minecraft:netherrack"); + BlockState blackstone = new BlockState("minecraft:blackstone"); for (String ore : List.of("coal", "copper", "iron", "gold", "redstone", "lapis", "diamond", "emerald")) { - bases.put("minecraft:" + ore + "_ore", stone); - bases.put("minecraft:deepslate_" + ore + "_ore", deepslate); + bases.put(ResourceId.parse("minecraft:" + ore + "_ore"), stone); + bases.put(ResourceId.parse("minecraft:deepslate_" + ore + "_ore"), deepslate); } - bases.put("minecraft:nether_gold_ore", netherrack); - bases.put("minecraft:nether_quartz_ore", netherrack); - bases.put("minecraft:ancient_debris", netherrack); - bases.put("minecraft:gilded_blackstone", blackstone); + bases.put(ResourceId.parse("minecraft:nether_gold_ore"), netherrack); + bases.put(ResourceId.parse("minecraft:nether_quartz_ore"), netherrack); + bases.put(ResourceId.parse("minecraft:ancient_debris"), netherrack); + bases.put(ResourceId.parse("minecraft:gilded_blackstone"), blackstone); return bases; } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index a39f8546f..1f7146c74 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -19,16 +19,11 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; import com.volmit.IrisModule; import com.volmit.ModuleInfo; -import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; -/** - * Module {@code iris:post}: smooths the carved surface with {@link SurfaceSmoothing}, except while maintenance - * regeneration bypasses the mantle. - */ +/** Module {@code iris:post}: smooths the carved surface with {@link SurfaceSmoothing}. */ public final class PostModule implements IrisModule { private static final String VERSION = "built-in"; @@ -39,15 +34,6 @@ public final class PostModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Post.SMOOTH).requires(IrisStages.Carve.APPLY).run(PostModule::smooth); - } - - private static void smooth(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - if (chunk.bypassesMantleStages()) { - return; - } - chunk.state(SurfaceSmoothing.class, SurfaceSmoothing::new) - .smooth(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + graph.define(IrisStages.Post.SMOOTH).requires(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 6b15edda1..61baa072b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -18,333 +18,321 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.prepare.SlopeClip; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.builtin.PendingSettings; +import art.arcane.iris.builtin.PendingSettings.BiomeLayer; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.Optional; /** - * Smooths the carved surface for {@link PostModule}: floating nibs, single-block bumps and potholes, walls under - * steep faces, slabs on steps, waterlogging and the foliage that lost its ground. One per engine runtime, - * holding the post stream's random. + * Smooths the carved surface of one chunk for {@link PostModule}: floating nibs, single-block bumps and potholes, + * walls under steep faces, slabs on steps, waterlogging and the foliage that lost its ground. */ -public class SurfaceSmoothing { - private static final class States { - private static final PlatformBlockState AIR = B.getState("AIR"); +final class SurfaceSmoothing { + private static final BlockState AIR = new BlockState("minecraft:air"); + private static final ResourceId AIR_ID = AIR.material(); + private static final ResourceId CAVE_AIR_ID = ResourceId.parse("minecraft:cave_air"); + private static final ResourceId WATER_ID = ResourceId.parse("minecraft:water"); + private static final ResourceId SNOW_ID = ResourceId.parse("minecraft:snow"); + private static final ResourceId DEAD_BUSH_ID = ResourceId.parse("minecraft:dead_bush"); + private static final String SLAB_SUFFIX = "_slab"; + private static final String WATERLOGGED = "waterlogged"; + private static final String TRUE = "true"; + /** The face properties of a connecting block, such as a vine's, each with the neighbour it faces. */ + private static final List FACES = List.of(new Face("north", 0, 0, -1), new Face("east", 1, 0, 0), + new Face("south", 0, 0, 1), new Face("west", -1, 0, 0), new Face("up", 0, 1, 0), new Face("down", 0, -1, 0)); + + private final Hunk blocks; + private final BlockRegistry registry; + private final TerrainSampler terrain; + private final PendingSettings settings; + private final int originX; + private final int originZ; + private final int planeWidth; + private final int[] heights; + private final boolean walls; + private final boolean slabs; + private final int fluidHeight; + + private SurfaceSmoothing(ChunkStageContext context) { + this.blocks = context.hunk(BlockState.class); + this.registry = context.resources().blocks(); + this.terrain = context.terrain(); + this.settings = PendingSettings.of(context.world()); + this.originX = context.originX(); + this.originZ = context.originZ(); + this.planeWidth = blocks.getWidth() + 2; + this.heights = heightPlane(); + this.walls = settings.postProcessingWalls(); + this.slabs = settings.postProcessingSlabs(); + this.fluidHeight = terrain.fluidHeight(); } - private final Engine engine; - private final RNG rng; - - public SurfaceSmoothing(Engine engine) { - this.engine = engine; - rng = new RNG(engine.getSeedManager().getPost()); + /** Smooths the chunk of {@code context}. */ + static void smooth(ChunkStageContext context) { + new SurfaceSmoothing(context).smoothColumns(); } - /** Smooths the chunk whose first block is {@code x}, {@code z}. */ - public void smooth(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - // The post stage runs sequentially on production (multicore false); an uncontended - // monitor per probe is still a monitor times ~10k probes per chunk. - Hunk sync = multicore ? output.synchronize() : output; - int width = output.getWidth(); - int depth = output.getDepth(); - int planeWidth = width + 2; - int[] heights = heightPlane(x, z, width, depth, planeWidth); - IrisDimension dimension = engine.getDimension(); - boolean walls = dimension.isPostProcessingWalls(); - boolean slabs = dimension.isPostProcessingSlabs(); - int fluidHeight = dimension.getFluidHeight(); - for (int i = 0; i < width; i++) { - for (int j = 0; j < depth; j++) { - post(i, j, sync, i + x, j + z, context, heights, planeWidth, walls, slabs, fluidHeight); + private void smoothColumns() { + for (int i = 0; i < blocks.getWidth(); i++) { + for (int j = 0; j < blocks.getDepth(); j++) { + post(i, j); } } - - engine.getMetrics().getPost().put(p.getMilliseconds()); } /** * Every column reads its own height plus its four neighbours, so adjacent columns would otherwise - * resolve the same height stream entry up to five times. Resolve the padded plane once instead. The - * four diagonal corners are never read, so they are left unresolved. + * resolve the same height up to five times. Resolve the padded plane once instead. The four diagonal + * corners are never read, so they are left unresolved. */ - private int[] heightPlane(int x, int z, int width, int depth, int planeWidth) { - int[] heights = new int[planeWidth * (depth + 2)]; - EngineMantle mantle = engine.getMantle(); - + private int[] heightPlane() { + int width = blocks.getWidth(); + int depth = blocks.getDepth(); + int[] plane = new int[planeWidth * (depth + 2)]; for (int j = -1; j <= depth; j++) { boolean edge = j == -1 || j == depth; int from = edge ? 0 : -1; int to = edge ? width - 1 : width; int row = (j + 1) * planeWidth; - for (int i = from; i <= to; i++) { - heights[row + i + 1] = mantle.trueHeight(x + i, z + j); + plane[row + i + 1] = surfaceHeight(originX + i, originZ + j); } } - - return heights; + return plane; } - private void post(int currentPostX, int currentPostZ, Hunk currentData, int x, int z, ChunkContext context, int[] heights, int planeWidth, boolean walls, boolean slabs, int fluidHeight) { - // x/z are world coordinates, the hunk is indexed relative to this chunk origin. - int originX = x - currentPostX; - int originZ = z - currentPostZ; - int center = (currentPostZ + 1) * planeWidth + currentPostX + 1; + private int surfaceHeight(int x, int z) { + return (int) Math.round(terrain.column(x, z).surfaceY()); + } + + private void post(int localX, int localZ) { + int x = originX + localX; + int z = originZ + localZ; + int center = (localZ + 1) * planeWidth + localX + 1; int h = heights[center]; int ha = heights[center + 1]; int hb = heights[center + planeWidth]; int hc = heights[center - 1]; int hd = heights[center - planeWidth]; - // Floating Nibs - int g = 0; - if (h < 1) { return; } - g += ha < h - 1 ? 1 : 0; - g += hb < h - 1 ? 1 : 0; - g += hc < h - 1 ? 1 : 0; - g += hd < h - 1 ? 1 : 0; - - if (g == 4 && isAir(x, h - 1, z, originX, originZ, currentData)) { - setPostBlock(x, h, z, States.AIR, originX, originZ, currentData); - - for (int i = h - 1; i > 0; i--) { - if (!isAir(x, i, z, originX, originZ, currentData)) { - h = i; - break; - } - } - } - - // Nibs - g = 0; - g += ha == h - 1 ? 1 : 0; - g += hb == h - 1 ? 1 : 0; - g += hc == h - 1 ? 1 : 0; - g += hd == h - 1 ? 1 : 0; - - if (g >= 4) { - PlatformBlockState bcState = getPostBlock(x, h, z, originX, originZ, currentData); - PlatformBlockState bState = getPostBlock(x, h + 1, z, originX, originZ, currentData); - - if (bState.isOccluding() && bState.isSolid()) { - if (bcState.isSolid()) { - setPostBlock(x, h, z, bState, originX, originZ, currentData); - h--; - } - } - } else { - // Potholes - g = 0; - g += ha == h + 1 ? 1 : 0; - g += hb == h + 1 ? 1 : 0; - g += hc == h + 1 ? 1 : 0; - g += hd == h + 1 ? 1 : 0; - - if (g >= 4) { - PlatformBlockState ba = getPostBlock(x, ha, z, originX, originZ, currentData); - PlatformBlockState bb = getPostBlock(x, hb, z, originX, originZ, currentData); - PlatformBlockState bc = getPostBlock(x, hc, z, originX, originZ, currentData); - PlatformBlockState bd = getPostBlock(x, hd, z, originX, originZ, currentData); - g = 0; - g = B.isSolid(ba) ? g + 1 : g; - g = B.isSolid(bb) ? g + 1 : g; - g = B.isSolid(bc) ? g + 1 : g; - g = B.isSolid(bd) ? g + 1 : g; - - if (g >= 3) { - setPostBlock(x, h + 1, z, getPostBlock(x, h, z, originX, originZ, currentData), originX, originZ, currentData); - h++; - } - } - } - - // Wall Patcher - IrisBiome biome = context.getBiome().get(currentPostX, currentPostZ); - + h = removeFloatingNib(x, z, h, ha, hb, hc, hd); + h = levelBumpOrPothole(x, z, h, ha, hb, hc, hd); if (walls) { - if (!biome.getWall().getPalette().isEmpty()) { - if (ha < h - 2 || hb < h - 2 || hc < h - 2 || hd < h - 2) { - boolean brokeGround = false; - int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); - - for (int i = h; i > h - max; i--) { - PlatformBlockState d = biome.getWall().get(rng, x + i, i + h, z + i, engine.getData()); - - if (d != null) { - if (isAirOrWater(x, i, z, originX, originZ, currentData)) { - if (brokeGround) { - break; - } - - continue; - } - - setPostBlock(x, i, z, d, originX, originZ, currentData); - brokeGround = true; - } - } - } - } + paintWall(x, z, h, ha, hb, hc, hd); } - - // Slab if (slabs) { - //@builder - if ((ha == h + 1 && isSolidNonSlab(x + 1, ha, z, originX, originZ, currentData)) - || (hb == h + 1 && isSolidNonSlab(x, hb, z + 1, originX, originZ, currentData)) - || (hc == h + 1 && isSolidNonSlab(x - 1, hc, z, originX, originZ, currentData)) - || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, originX, originZ, currentData))) - //@done - { - SlopeClip sc = biome.getSlab().getSlopeCondition(); - PlatformBlockState d = sc.isValid(engine.getComplex().getSlopeStream().get(x, z)) ? biome.getSlab().get(rng, x, h, z, engine.getData()) : null; + h = placeSlab(x, z, h, ha, hb, hc, hd); + } + settleWaterlogging(x, z, h); + settleFoliage(x, z, h); + } - if (d != null) { - boolean cancel = B.isAir(d); - - if (IrisProceduralBlocks.materialKey(d).equals("minecraft:snow") && h + 1 <= fluidHeight) { - cancel = true; - } - - if (isSnowLayer(x, h, z, originX, originZ, currentData)) { - cancel = true; - } - - if (!cancel && isAirOrWater(x, h + 1, z, originX, originZ, currentData)) { - setPostBlock(x, h + 1, z, d, originX, originZ, currentData); - h++; - } - } + private int removeFloatingNib(int x, int z, int h, int ha, int hb, int hc, int hd) { + int g = lower(ha, h - 1) + lower(hb, h - 1) + lower(hc, h - 1) + lower(hd, h - 1); + if (g != 4 || !isAir(x, h - 1, z)) { + return h; + } + set(x, h, z, AIR); + for (int i = h - 1; i > 0; i--) { + if (!isAir(x, i, z)) { + return i; } } + return h; + } - // Waterlogging - PlatformBlockState b = getPostBlock(x, h, z, originX, originZ, currentData); - - if (IrisProceduralBlocks.hasProperty(b, "waterlogged")) { - boolean w = false; - - if (h <= fluidHeight + 1) { - if (isWaterOrWaterlogged(x, h + 1, z, originX, originZ, currentData)) { - w = true; - } else if ((isWaterOrWaterlogged(x + 1, h, z, originX, originZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, originX, originZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, originX, originZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, originX, originZ, currentData))) { - w = true; - } - } - - if (w != "true".equals(IrisProceduralBlocks.propertyValue(b, "waterlogged"))) { - setPostBlock(x, h, z, b.withProperty("waterlogged", String.valueOf(w)), originX, originZ, currentData); + private int levelBumpOrPothole(int x, int z, int h, int ha, int hb, int hc, int hd) { + int g = same(ha, h - 1) + same(hb, h - 1) + same(hc, h - 1) + same(hd, h - 1); + if (g >= 4) { + BlockState bump = get(x, h, z); + BlockState above = get(x, h + 1, z); + if (has(above, BlockTrait.OCCLUDING) && has(above, BlockTrait.SOLID) && has(bump, BlockTrait.SOLID)) { + set(x, h, z, above); + return h - 1; } + return h; } - - // Foliage - b = getPostBlock(x, h + 1, z, originX, originZ, currentData); - - if (B.isVineBlock(b)) { - PlatformBlockState result = b; - int finalH = h + 1; - - for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { - if (!IrisProceduralBlocks.hasProperty(b, face)) { - continue; - } - int[] mod = IrisProceduralBlocks.faceOffset(face); - PlatformBlockState d = getPostBlock(x + mod[0], finalH + mod[1], z + mod[2], originX, originZ, currentData); - result = result.withProperty(face, String.valueOf(!B.isAir(d) && !B.isVineBlock(d))); - } - if (!result.equals(b)) { - setPostBlock(x, h + 1, z, result, originX, originZ, currentData); - } + g = same(ha, h + 1) + same(hb, h + 1) + same(hc, h + 1) + same(hd, h + 1); + if (g < 4) { + return h; } - - if (B.isFoliage(b) || IrisProceduralBlocks.materialKey(b).equals("minecraft:dead_bush")) { - PlatformBlockState onto = getPostBlock(x, h, z, originX, originZ, currentData); - - if (!B.canPlaceOnto(b, onto) && !B.isDecorant(b)) { - setPostBlock(x, h + 1, z, States.AIR, originX, originZ, currentData); - } + int solidSides = solid(get(x, ha, z)) + solid(get(x, hb, z)) + solid(get(x, hc, z)) + solid(get(x, hd, z)); + if (solidSides < 3) { + return h; } + set(x, h + 1, z, get(x, h, z)); + return h + 1; } - public boolean isAir(int x, int y, int z, int originX, int originZ, Hunk currentData) { - String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)); - return material.equals("minecraft:air") || material.equals("minecraft:cave_air"); - } - - public boolean hasGravity(int x, int y, int z, int originX, int originZ, Hunk currentData) { - String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)); - return material.equals("minecraft:sand") || material.equals("minecraft:red_sand") || material.endsWith("_concrete_powder"); - } - - public boolean isSolid(int x, int y, int z, int originX, int originZ, Hunk currentData) { - PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData); - return B.isSolid(d) && !B.isVineBlock(d); - } - - public boolean isSolidNonSlab(int x, int y, int z, int originX, int originZ, Hunk currentData) { - PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData); - return B.isSolid(d) && !IrisProceduralBlocks.materialKey(d).endsWith("_slab"); - } - - public boolean isAirOrWater(int x, int y, int z, int originX, int originZ, Hunk currentData) { - String material = IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)); - return material.equals("minecraft:water") || material.equals("minecraft:air") || material.equals("minecraft:cave_air"); - } - - public boolean isSlab(int x, int y, int z, int originX, int originZ, Hunk currentData) { - return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).endsWith("_slab"); - } - - public boolean isSnowLayer(int x, int y, int z, int originX, int originZ, Hunk currentData) { - return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).equals("minecraft:snow"); - } - - public boolean isWater(int x, int y, int z, int originX, int originZ, Hunk currentData) { - return IrisProceduralBlocks.materialKey(getPostBlock(x, y, z, originX, originZ, currentData)).equals("minecraft:water"); - } - - public boolean isWaterOrWaterlogged(int x, int y, int z, int originX, int originZ, Hunk currentData) { - PlatformBlockState d = getPostBlock(x, y, z, originX, originZ, currentData); - return IrisProceduralBlocks.materialKey(d).equals("minecraft:water") || "true".equals(IrisProceduralBlocks.propertyValue(d, "waterlogged")); - } - - public boolean isLiquid(int x, int y, int z, int originX, int originZ, Hunk currentData) { - return IrisProceduralBlocks.hasProperty(getPostBlock(x, y, z, originX, originZ, currentData), "level"); - } - - public void setPostBlock(int x, int y, int z, PlatformBlockState d, int originX, int originZ, Hunk currentData) { - int lx = x - originX; - int lz = z - originZ; - - if (lx < 0 || lz < 0 || lx >= currentData.getWidth() || lz >= currentData.getDepth() || y < 0 || y >= currentData.getHeight()) { + private void paintWall(int x, int z, int h, int ha, int hb, int hc, int hd) { + if (ha >= h - 2 && hb >= h - 2 && hc >= h - 2 && hd >= h - 2) { return; } + Optional wall = settings.wall(x, z); + if (wall.isEmpty()) { + return; + } + boolean brokeGround = false; + int max = Math.abs(Math.max(h - ha, Math.max(h - hb, Math.max(h - hc, h - hd)))); + for (int i = h; i > h - max; i--) { + Optional block = wall.get().at(x + i, i + h, z + i); + if (block.isEmpty()) { + continue; + } + if (isAirOrWater(x, i, z)) { + if (brokeGround) { + break; + } + continue; + } + set(x, i, z, block.get()); + brokeGround = true; + } + } - currentData.set(lx, y, lz, d); + private int placeSlab(int x, int z, int h, int ha, int hb, int hc, int hd) { + boolean step = (ha == h + 1 && isSolidNonSlab(x + 1, ha, z)) + || (hb == h + 1 && isSolidNonSlab(x, hb, z + 1)) + || (hc == h + 1 && isSolidNonSlab(x - 1, hc, z)) + || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1)); + if (!step) { + return h; + } + BiomeLayer slab = settings.slab(x, z); + if (!slab.allowsSlope(terrain.column(x, z).slope())) { + return h; + } + Optional picked = slab.at(x, h, z); + if (picked.isEmpty()) { + return h; + } + BlockState block = picked.get(); + boolean cancel = has(block, BlockTrait.AIR) + || block.material().equals(SNOW_ID) && h + 1 <= fluidHeight + || isSnowLayer(x, h, z); + if (cancel || !isAirOrWater(x, h + 1, z)) { + return h; + } + set(x, h + 1, z, block); + return h + 1; + } + + private void settleWaterlogging(int x, int z, int h) { + BlockState block = get(x, h, z); + if (!block.properties().containsKey(WATERLOGGED)) { + return; + } + boolean waterlogged = h <= fluidHeight + 1 && (isWaterOrWaterlogged(x, h + 1, z) + || isWaterOrWaterlogged(x + 1, h, z) || isWaterOrWaterlogged(x - 1, h, z) + || isWaterOrWaterlogged(x, h, z + 1) || isWaterOrWaterlogged(x, h, z - 1)); + if (waterlogged != TRUE.equals(block.properties().get(WATERLOGGED))) { + set(x, h, z, block.withProperty(WATERLOGGED, String.valueOf(waterlogged))); + } + } + + private void settleFoliage(int x, int z, int h) { + BlockState block = get(x, h + 1, z); + if (has(block, BlockTrait.VINE)) { + connectVine(x, h + 1, z, block); + } + if (!has(block, BlockTrait.FOLIAGE) && !block.material().equals(DEAD_BUSH_ID)) { + return; + } + if (!registry.canPlaceOn(block, get(x, h, z)) && !has(block, BlockTrait.DECORATION)) { + set(x, h + 1, z, AIR); + } + } + + /** A vine faces each neighbour it can cling to, a block that is neither air nor another vine. */ + private void connectVine(int x, int y, int z, BlockState vine) { + BlockState connected = vine; + for (Face face : FACES) { + if (!vine.properties().containsKey(face.property())) { + continue; + } + BlockState neighbour = get(x + face.dx(), y + face.dy(), z + face.dz()); + connected = connected.withProperty(face.property(), String.valueOf(!has(neighbour, BlockTrait.AIR) && !has(neighbour, BlockTrait.VINE))); + } + if (!connected.equals(vine)) { + set(x, y, z, connected); + } + } + + private boolean isAir(int x, int y, int z) { + ResourceId material = get(x, y, z).material(); + return material.equals(AIR_ID) || material.equals(CAVE_AIR_ID); + } + + private boolean isSolidNonSlab(int x, int y, int z) { + BlockState block = get(x, y, z); + return has(block, BlockTrait.SOLID) && !block.material().path().endsWith(SLAB_SUFFIX); + } + + private boolean isAirOrWater(int x, int y, int z) { + ResourceId material = get(x, y, z).material(); + return material.equals(WATER_ID) || material.equals(AIR_ID) || material.equals(CAVE_AIR_ID); + } + + private boolean isSnowLayer(int x, int y, int z) { + return get(x, y, z).material().equals(SNOW_ID); + } + + private boolean isWaterOrWaterlogged(int x, int y, int z) { + BlockState block = get(x, y, z); + return block.material().equals(WATER_ID) || TRUE.equals(block.properties().get(WATERLOGGED)); + } + + private boolean has(BlockState block, BlockTrait trait) { + return registry.hasTrait(block, trait); + } + + private int solid(BlockState block) { + return has(block, BlockTrait.SOLID) ? 1 : 0; + } + + private static int lower(int neighbour, int than) { + return neighbour < than ? 1 : 0; + } + + private static int same(int neighbour, int as) { + return neighbour == as ? 1 : 0; + } + + /** Writes inside the chunk only; a step on a neighbour column outside it is left alone. */ + private void set(int x, int y, int z, BlockState block) { + int localX = x - originX; + int localZ = z - originZ; + if (localX < 0 || localZ < 0 || localX >= blocks.getWidth() || localZ >= blocks.getDepth() || y < 0 || y >= blocks.getHeight()) { + return; + } + blocks.set(localX, y, localZ, block); } /** * Neighbour columns can sit one block outside this chunk, and the blocks of an adjacent chunk are not - * available while generating this one. Resolve the hunk index relative to the chunk origin and let - * getClosest clamp to the nearest in-chunk column instead of wrapping to the opposite chunk edge. + * available while generating this one. Clamp to the nearest block of the chunk instead of wrapping to the + * opposite edge. */ - public PlatformBlockState getPostBlock(int x, int y, int z, int originX, int originZ, Hunk h) { - PlatformBlockState b = h.getClosest(x - originX, y, z - originZ); + private BlockState get(int x, int y, int z) { + return blocks.get(clamp(x - originX, blocks.getWidth()), clamp(y, blocks.getHeight()), clamp(z - originZ, blocks.getDepth())); + } - return b == null ? States.AIR : b; + private static int clamp(int value, int size) { + return value < 0 ? 0 : Math.min(value, size - 1); + } + + private record Face(String property, int dx, int dy, int dz) { } } From 04ae40341f6488c8bd368587cbe01e976fcf00bc Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:10:24 +0200 Subject: [PATCH 057/139] The built-ins jar holds iris:post, iris:perfection and iris:matter; its check sees VolmLib and Gson as exposed packages --- build.gradle.kts | 16 ++++++++++++++-- builtin-modules.txt | 6 +++++- settings.gradle.kts | 7 +++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 17cf1bfd4..1a888f0f4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -64,19 +64,31 @@ val builtinModuleList = readBuiltinModuleList(builtinModulesFile) val builtinModulesJarName = "iris-builtins.jar" val builtinModuleEntryFile = "com.volmit.IrisModule" -/** Host packages pack modules may use besides the IrisApi. Keep in step with IrisModuleHost.BUILT_IN_API_PACKAGE in Iris. */ -val exposedHostPackages = listOf("art.arcane.iris.builtin") +/** + * Host packages pack modules may use besides the IrisApi: the built-in module API, VolmLib and Gson. Keep in step with + * IrisModuleHost.EXPOSED_PACKAGES in Iris. + */ +val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.volmlib", "com.google.gson") val irisClasses = irisRoot.resolve("core/build/classes/java/main") val builtinModulesBuild = layout.buildDirectory.dir("builtin-modules") val checkedJarsDirectory = layout.buildDirectory.dir("libs") +repositories { + mavenCentral() +} + +/** What the jar check sees besides Iris's classes: the IrisApi and the libraries Iris shares with pack modules. */ val irisApiForChecks by configurations.creating { isCanBeConsumed = false + isTransitive = false attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) } dependencies { irisApiForChecks("com.volmit:IrisApi") + irisApiForChecks("com.github.VolmitSoftware:VolmLib") + // The Gson Iris compiles against (Iris/gradle/libs.versions.toml); at runtime modules get the platform's copy. + irisApiForChecks("com.google.code.gson:gson:2.14.0") } val compileBuiltins = tasks.register("compileBuiltins") { diff --git a/builtin-modules.txt b/builtin-modules.txt index 71a8684bd..824782905 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -13,4 +13,8 @@ # that with IrisApi's pack class checks and fails naming the class and what it uses. # # Moving a module here means removing it from IrisModuleHost.generationModules() or PlacementModules.all() in Iris. -# Nothing is ported yet. + +module art.arcane.iris.engine.modifier.PostModule +include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class +module art.arcane.iris.engine.modifier.PerfectionModule +module art.arcane.iris.engine.modifier.MatterModule diff --git a/settings.gradle.kts b/settings.gradle.kts index a480323b7..841797c9e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -2,3 +2,10 @@ rootProject.name = "IrisModule" // Keep the public API discoverable when importing the default module. includeBuild("../IrisApi") + +// The built-ins jar check sees the libraries Iris shares with pack modules; VolmLib comes from the sibling checkout, as for Iris. +includeBuild("../VolmLib") { + dependencySubstitution { + substitute(module("com.github.VolmitSoftware:VolmLib")).using(project(":shared")) + } +} From 029406b448793c8aec4a6f11f2a81f9463af20af Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:12:33 +0200 Subject: [PATCH 058/139] Mechanical: LazyBoundedCache comes from VolmLib (art.arcane.volmlib.util.cache) --- .../arcane/iris/engine/object/material/IrisMaterialPalette.java | 2 +- .../art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java | 2 +- .../art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java | 2 +- .../iris/engine/object/noise/expression/IrisExpressionLoad.java | 2 +- .../iris/engine/object/placement/IrisObjectPlacement.java | 2 +- .../art/arcane/iris/engine/object/world/biome/IrisBiome.java | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) 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 index 1434f9d2d..d4b9216dd 100644 --- a/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java +++ b/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java @@ -23,7 +23,7 @@ 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.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.data.cache.LazyBoundedCache; +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; 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 index a6245d290..4a435a604 100644 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java @@ -21,7 +21,7 @@ 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.iris.engine.data.cache.LazyBoundedCache; +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; 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 index a65c2da3e..8dd8c8f9d 100644 --- a/src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.noise; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.LazyBoundedCache; +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; 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 index 4e3af17eb..0de6b5aeb 100644 --- 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 @@ -23,7 +23,7 @@ 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.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.data.cache.LazyBoundedCache; +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; 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 index ee0075335..b606758e5 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -46,7 +46,7 @@ import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.data.cache.LazyBoundedCache; +import art.arcane.volmlib.util.cache.LazyBoundedCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.annotations.ArrayType; 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 index 2be388ff5..2be0d7f14 100644 --- 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 @@ -43,7 +43,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.data.cache.AtomicCache; -import art.arcane.iris.engine.data.cache.LazyBoundedCache; +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; From 9761138fb014b1035377d81537afd9176a94c677 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:15:34 +0200 Subject: [PATCH 059/139] IrisSeed: Iris's per-feature world seeds for the built-ins, the one place they reach SeedManager --- .../art/arcane/iris/builtin/IrisSeed.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/main/java/art/arcane/iris/builtin/IrisSeed.java diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeed.java b/src/main/java/art/arcane/iris/builtin/IrisSeed.java new file mode 100644 index 000000000..9e589b67e --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/IrisSeed.java @@ -0,0 +1,44 @@ +/* + * 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.builtin; + +import com.volmit.world.PackWorld; + +/** + * The seeds Iris derives from a world's seed for its own features. Iris derives them one after another from a shared + * random, so they cannot be worked out from the world seed alone. Built-in modules seed their randoms and noise with + * them, so worlds generated before the features were modules generate the same; a pack module derives its own seeds + * from {@link PackWorld#seed()}. + */ +public enum IrisSeed { + BIOME, CARVE, COMPONENT, DECORATOR, DEPOSIT, ENTITY, LOOT, MANTLE, POST, TERRAIN; + + /** This seed of {@code world}, which must be a world Iris generates. */ + public long of(PackWorld world) { + if (world instanceof Source source) { + return source.seed(this); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** Iris's worlds answer for their seeds. */ + public interface Source { + long seed(IrisSeed seed); + } +} From df6081b7b7a87ecaf346a9f046fb2c03e5b84859 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 13:16:39 +0200 Subject: [PATCH 060/139] README: the built-ins jar holds post, perfection and matter; the built-in facades --- README.md | 18 +++++++++++++++--- .../art/arcane/iris/builtin/package-info.java | 4 ++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4bf62dc47..d10d9dae6 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,18 @@ module jar for a pack's `modules/` folder. `builtin-modules.txt` lists what goes (the jar's entry points, written to `META-INF/services/com.volmit.IrisModule`) and `include ` lines for further classes. The classes come from Iris core's compiled output, which the task builds first. Before the jar lands in `build/libs`, `ModuleJarCheck` of IrisApi runs the class checks of a pack load on it, -with `art.arcane.iris.builtin` as the only exposed Iris package; a listed class that uses Iris internals fails -the task naming the class and what it uses. `check` runs the task. Nothing is ported yet, so the jar is empty -and not loadable as a pack module (a pack module jar must name at least one module). +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. `check` runs the task. + +The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and +`art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain +sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. +Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting +`iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, +`iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. + +`art.arcane.iris.builtin` also holds the few facades only Iris's own built-ins use, interfaces Iris's worlds implement: +`IrisSeed` (Iris's per-feature world seeds, so existing worlds generate the same) and, until wave 3a's settings moves +land, `PendingSettings` (the dimension's `hideOresForHiddenOre`, `postProcessingWalls`, `postProcessingSlabs` and a +biome's `wall` and `slab`, which agents C and T are turning into module settings; it is deleted at that merge). diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 49b8bca4e..b9f9bccec 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -27,6 +27,10 @@ * subpackage per built-in module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} * for {@code iris:deposit}. *

+ * Besides those, it holds narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement, for what + * they need from Iris's internals and no pack module does: {@link art.arcane.iris.builtin.IrisSeed}, and the transitional + * {@link art.arcane.iris.builtin.PendingSettings}. Keep them few: each is a promise. + *

* Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A * pack module can require such a stage to run after it, but cannot read its output: the pack load rejects * a pack class that uses a type Iris hides. From db0f8a9186d7fc1364653280f9b7f519942758d1 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 14:25:32 +0200 Subject: [PATCH 061/139] iris:biome and iris:custom leave the module sources: Iris registers them itself, in core --- README.md | 14 +- .../iris/engine/actuator/BiomeModule.java | 126 ------------------ .../iris/engine/modifier/CustomModule.java | 119 ----------------- 3 files changed, 13 insertions(+), 246 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/modifier/CustomModule.java diff --git a/README.md b/README.md index ffcece855..928a612b6 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,16 @@ mantle components outside the stage graph any more. Their stage constants, and t types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live beside the features they replace. +Two of those modules are not in this project: `iris:biome` (writes the layout's platform biomes into the chunk) and +`iris:custom` (records the platform's custom blocks of content plugins) are Iris itself, so their classes live in Iris +core (`art.arcane.iris.core.modules.BiomeModule` and `CustomModule`) and Iris registers them (`IrisModuleHost`), not +the built-ins jar. Their stage constants stay in `art.arcane.iris.builtin.IrisStages`, so packs can still order after them. + +Built-in modules log through the `ModuleLog` IrisApi hands them (`context.log()` in a stage body, `world.log()` in a +service or hook, `registry.log()` while registering), which labels each line with the module's id, so these sources do not +use `IrisLogging`. Classes of the host's object model (the host-classes list) and code that only has an engine or pack +data still log as Iris itself. + Built-in modules also own pack resources and checks of their own. `iris:structure` reads structures, jigsaw pools and jigsaw pieces as resource kinds (`StructureResources`), from the folders and files packs have always used, and checks them with its validator (`StructureValidator`: assembly samples and vanilla structure @@ -130,7 +140,9 @@ The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting `iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, -`iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. +`iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder +when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to +`builtin-modules.txt`): add a module to the jar and to that list together. `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the diff --git a/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java b/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java deleted file mode 100644 index 429052981..000000000 --- a/src/main/java/art/arcane/iris/engine/actuator/BiomeModule.java +++ /dev/null @@ -1,126 +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.actuator; - -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBiome; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.context.ChunkedDataCache; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterBiomeInject; -import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import com.volmit.IrisModule; -import com.volmit.ModuleInfo; -import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; - -/** - * Module {@code iris:biome}: writes each column's biome into the chunk's biome hunk, a custom biome under the - * dimension's namespace, and records the biome id in the mantle for platforms that inject biomes later. - */ -public final class BiomeModule implements IrisModule { - private static final String VERSION = "built-in"; - - @Override - public ModuleInfo info() { - return ModuleInfo.of("iris:biome", "Biomes", VERSION); - } - - @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Biome.WRITE).run(BiomeModule::write); - } - - private static void write(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - chunk.state(BiomeWriter.class, BiomeWriter::new).write(chunk.originX(), chunk.originZ(), chunk.biomes(), chunk.context()); - } - - /** What writing biomes keeps for one engine runtime: the biome stream's random and the platform biomes resolved so far. */ - static final class BiomeWriter { - private final Engine engine; - private final RNG rng; - private final KMap resolvedBiomes = new KMap<>(); - - BiomeWriter(Engine engine) { - this.engine = engine; - this.rng = new RNG(engine.getSeedManager().getBiome()); - } - - /** A partial biome write fails the chunk: a chunk flagged done with default biomes would keep them forever. */ - void write(int originX, int originZ, Hunk biomes, ChunkContext context) { - PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); - Mantle mantle = engine.getMantle().getMantle(); - ChunkedDataCache biomeCache = context.getBiome(); - for (int localX = 0; localX < biomes.getWidth(); localX++) { - for (int localZ = 0; localZ < biomes.getDepth(); localZ++) { - int worldX = originX + localX; - int worldZ = originZ + localZ; - ResolvedBiome resolved = resolve(keyOf(biomeCache.get(localX, localZ), worldX, worldZ)); - if (resolved.biome() != null) { - biomes.set(localX, 0, localZ, localX, biomes.getHeight() - 1, localZ, resolved.biome()); - } - mantle.set(worldX, 0, worldZ, resolved.matter()); - } - } - engine.getMetrics().getBiome().put(stopwatch.getMilliseconds()); - } - - private String keyOf(IrisBiome biome, int worldX, int worldZ) { - if (!biome.isCustom()) { - return biome.getSkyBiomeKey(rng, engine, worldX, 0, worldZ); - } - IrisBiomeCustom custom = biome.getCustomBiome(rng, engine, worldX, 0, worldZ); - return engine.getDimension().getLoadKey() + ":" + custom.getId(); - } - - /** - * The registry lookup and the biome id depend only on the key, so the pair is cached instead of paying two - * string-keyed lookups per column. Unresolved biomes are never cached, so a biome registered later still - * resolves. - */ - private ResolvedBiome resolve(String key) { - ResolvedBiome cached = key == null ? null : resolvedBiomes.get(key); - if (cached != null) { - return cached; - } - IrisPlatform platform = IrisPlatforms.get(); - PlatformBiome biome = platform.registries().biome(key); - ResolvedBiome resolved = new ResolvedBiome(biome, BiomeInjectMatter.get(platform.biomeWriter().biomeIdFor(key))); - if (key != null && biome != null) { - resolvedBiomes.put(key, resolved); - } - return resolved; - } - } - - private record ResolvedBiome(PlatformBiome biome, MatterBiomeInject matter) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java b/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java deleted file mode 100644 index 763bc40a9..000000000 --- a/src/main/java/art/arcane/iris/engine/modifier/CustomModule.java +++ /dev/null @@ -1,119 +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.modifier; - -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.link.Identifier; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.parallel.BurstExecutor; -import art.arcane.iris.util.common.parallel.MultiBurst; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.mantle.flag.MantleFlag; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; -import com.volmit.IrisModule; -import com.volmit.ModuleInfo; -import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; - -/** - * Module {@code iris:custom}: records the chunk's content-plugin blocks for the server to place later: each - * custom block's placement key goes into the mantle and the block itself is replaced by its base state. Skipped - * while maintenance regeneration bypasses the mantle. - */ -public final class CustomModule implements IrisModule { - private static final String VERSION = "built-in"; - private static final int CHUNK_SHIFT = 4; - private static final int SECTION_MASK = 15; - - @Override - public ModuleInfo info() { - return ModuleInfo.of("iris:custom", "Custom blocks", VERSION); - } - - @Override - public void install(StageGraph graph) { - // Ordering only: iris:perfection ships in the built-ins jar, which a pack may not have. - graph.define(IrisStages.Custom.BLOCKS).softAfter(IrisStages.Perfection.SURFACE.ref()).run(CustomModule::record); - } - - private static void record(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - if (chunk.bypassesMantleStages()) { - return; - } - chunk.state(CustomBlockRecording.class, CustomBlockRecording::new).record(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore()); - } - - /** Moves the custom blocks of a chunk into the mantle for one engine runtime. */ - static final class CustomBlockRecording { - private final Engine engine; - - CustomBlockRecording(Engine engine) { - this.engine = engine; - } - - /** Records the custom blocks of the chunk whose first block is {@code x}, {@code z}, when its mantle chunk is flagged as having some. */ - void record(int x, int z, Hunk output, boolean multicore) { - MantleChunk mc = engine.getMantle().getMantle().getChunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); - if (!mc.isFlagged(MantleFlag.CUSTOM_ACTIVE)) { - return; - } - mc.use(); - - BurstExecutor burst = MultiBurst.burst.burst(output.getHeight()); - burst.setMulticore(multicore); - // complete() must run before release() even when queueing throws — detached burst - // tasks must never write into a released chunk, and a lost permit wedges close(). - try { - for (int y = 0; y < output.getHeight(); y++) { - int finalY = y; - burst.queue(() -> { - for (int rX = 0; rX < output.getWidth(); rX++) { - for (int rZ = 0; rZ < output.getDepth(); rZ++) { - PlatformBlockState b = output.get(rX, finalY, rZ); - if (b == null || !b.isCustom()) { - continue; - } - String placementKey = b.deferredPlacementKey(); - PlatformBlockState baseState = b.placementBaseState(); - if (placementKey == null || baseState == null) { - continue; - } - - mc.getOrCreate(finalY >> CHUNK_SHIFT) - .slice(Identifier.class) - .set(rX, finalY & SECTION_MASK, rZ, Identifier.fromString(placementKey)); - output.set(rX, finalY, rZ, baseState); - } - } - }); - } - } finally { - try { - burst.complete(); - } finally { - mc.release(); - } - } - } - } -} From fb92f88ab1478c9aa617f58a030371dfdb693225 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 14:25:32 +0200 Subject: [PATCH 062/139] Modules log through the ModuleLog of their context, world or registry instead of IrisLogging; helpers without one take it from their caller --- .../iris/engine/actuator/TerrainModule.java | 8 +- .../engine/decorator/BiomeDecorators.java | 16 ++- .../iris/engine/decorator/DecoratorCore.java | 14 +-- .../engine/decorator/FloatingDecorator.java | 5 +- .../decorator/IrisCeilingDecorator.java | 2 +- .../decorator/IrisSeaFloorDecorator.java | 2 +- .../decorator/IrisSeaSurfaceDecorator.java | 2 +- .../decorator/IrisShoreLineDecorator.java | 2 +- .../decorator/IrisSurfaceDecorator.java | 4 +- .../engine/decorator/ResolvedDecorator.java | 14 ++- .../framework/IrisStructureLocator.java | 17 +-- .../engine/framework/StructureAssembler.java | 5 +- .../structure/StructureGraphCatalog.java | 32 ++--- .../structure/fit/StructureFitting.java | 2 +- .../structure/fit/SurfaceFitting.java | 21 ++-- .../arcane/iris/engine/loot/LootGiving.java | 2 +- .../iris/engine/loot/PlacementLoot.java | 8 +- .../FloatingIslandSampleResolver.java | 7 +- .../components/FloatingObjectPlacing.java | 22 ++-- .../components/GoldenDebugObjectPlacer.java | 14 ++- .../mantle/components/ObjectLocating.java | 2 +- .../mantle/components/ObjectModule.java | 18 +-- .../mantle/components/ObjectPlacing.java | 113 ++++++++---------- .../mantle/components/StructureModule.java | 16 ++- .../mantle/components/StructurePlacing.java | 12 +- .../iris/engine/modifier/CarveModule.java | 4 +- .../iris/engine/modifier/CaveApplying.java | 5 +- .../iris/engine/modifier/FloatingIslands.java | 20 ++-- .../iris/engine/modifier/FloatingModule.java | 24 ++-- .../object/placement/ValidateModule.java | 8 +- .../floating/FloatingIslandSample.java | 52 ++++---- .../world/biome/IrisBiomeColorRenderer.java | 2 +- .../iris/engine/spawn/EntitySpawning.java | 5 +- .../iris/engine/terrain/BiomeLayers.java | 14 ++- 34 files changed, 270 insertions(+), 224 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 279980029..9237e9ea4 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -55,6 +55,7 @@ import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; +import com.volmit.ModuleLog; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; import com.volmit.world.PackWorld; @@ -103,7 +104,8 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { private static void shape(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - chunk.state(TerrainShaper.class, TerrainShaper::new).shape(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); + ModuleLog log = context.log(); + chunk.state(TerrainShaper.class, generating -> new TerrainShaper(generating, log)).shape(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); } /** What shaping terrain keeps for one engine runtime: the terrain stream's random. */ @@ -116,8 +118,8 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { private final TerrainOres ores; private final RNG rng; - TerrainShaper(Engine engine) { - this(engine, TerrainPalettes.of(engine), BiomeLayers.of(engine), TerrainOres.of(engine)); + TerrainShaper(Engine engine, ModuleLog log) { + this(engine, TerrainPalettes.of(engine), BiomeLayers.of(engine, log), TerrainOres.of(engine)); } TerrainShaper(Engine engine, TerrainPalettes palettes, BiomeLayers layers, TerrainOres ores) { diff --git a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java index e288f9f2e..e38734947 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java +++ b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -24,6 +24,7 @@ import art.arcane.iris.builtin.decorant.Decorator; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.ModuleLog; import com.volmit.world.PackWorld; import java.util.ArrayList; @@ -48,16 +49,22 @@ public final class BiomeDecorators { private static final long INDEX_SEED_FACTOR = 0xC2B2AE3D27D4EB4FL; private final Engine engine; + private final ModuleLog log; private final Map> decorators = new ConcurrentHashMap<>(); private volatile Double busiestBiomeLoad; /** @param world a world of an Iris engine */ BiomeDecorators(PackWorld world) { - this(IrisPackWorld.of(world).engine()); + this(IrisPackWorld.of(world).engine(), world.log()); } BiomeDecorators(Engine engine) { + this(engine, engine.getGeneration().world().log()); + } + + BiomeDecorators(Engine engine, ModuleLog log) { this.engine = engine; + this.log = log; } /** The world {@code engine} generates now. */ @@ -70,6 +77,11 @@ public final class BiomeDecorators { return world.state(BiomeDecorators.class, BiomeDecorators::new); } + /** The log of the module that decorates, which the decorators write to. */ + ModuleLog log() { + return log; + } + /** Whether the biome declares any decorator. */ public boolean hasDecorators(IrisBiome biome) { DecorantSettings settings = settingsOf(biome); @@ -158,7 +170,7 @@ public final class BiomeDecorators { if (decorator == null) { continue; } - ResolvedDecorator resolved = ResolvedDecorator.of(decorator, engine, decoratorSeed(biomeKey, index)); + ResolvedDecorator resolved = ResolvedDecorator.of(decorator, engine, decoratorSeed(biomeKey, index), log); staging.computeIfAbsent(decorator.partOf(), part -> new ArrayList<>()).add(resolved); } diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java index 3762479c5..26fc4aa2a 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -22,11 +22,11 @@ import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; 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.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockSupport; import org.bukkit.block.data.BlockData; @@ -68,7 +68,7 @@ final class DecoratorCore { } /** The decorator of {@code bucket} that decorates the column, drawing from {@code colRng} to choose between those whose chance noise passes. */ - static ResolvedDecorator pickDecorator(ResolvedDecorator[] bucket, RNG colRng, double realX, double realZ) { + static ResolvedDecorator pickDecorator(ResolvedDecorator[] bucket, RNG colRng, double realX, double realZ, ModuleLog log) { ResolvedDecorator picked = null; int count = 0; @@ -81,7 +81,7 @@ final class DecoratorCore { } } } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("A decorator failed to pick for the column", e); } } @@ -99,7 +99,7 @@ final class DecoratorCore { static void placeSurfaceSingle(ResolvedDecorator decorator, int x, int z, int realX, int height, int realZ, Hunk data, - boolean underwater, boolean caveSkipFluid, EngineMantle mantle) { + boolean underwater, boolean caveSkipFluid, EngineMantle mantle, ModuleLog log) { if (height < 0 || height >= data.getHeight()) { return; } @@ -140,7 +140,7 @@ final class DecoratorCore { data.set(x, lowerY, z, lower); data.set(x, upperY, z, upper); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to place a two-block plant", e); } return; } @@ -291,7 +291,7 @@ final class DecoratorCore { static void placeFloatingSimple(ResolvedDecorator decorator, int xf, int zf, int realX, int realZ, - int height, int max, Hunk data) { + int height, int max, Hunk data, ModuleLog log) { PlatformBlockState bd = decorator.pickBlock(realX, realZ); if (bd == null) { return; @@ -311,7 +311,7 @@ final class DecoratorCore { data.set(xf, lowerY, zf, lower); data.set(xf, upperY, zf, upper); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to place a two-block plant", e); } return; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java index ebf564456..dac61cbe9 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java @@ -36,7 +36,8 @@ public class FloatingDecorator { int xf, int zf, int realX, int realZ, int height, int max, Hunk data, RNG rng, Runnable candidatesNullCallback) { - ResolvedDecorator decorator = DecoratorCore.pickDecorator(BiomeDecorators.of(engine).decorators(target, part), rng, realX, realZ); + BiomeDecorators decorators = BiomeDecorators.of(engine); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(target, part), rng, realX, realZ, decorators.log()); if (decorator == null) { candidatesNullCallback.run(); @@ -44,7 +45,7 @@ public class FloatingDecorator { } if (!decorator.isStacking()) { - DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data); + DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data, decorators.log()); return max > 1 ? 1 : 0; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java index ccbb7e951..ed02dcee9 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java @@ -45,7 +45,7 @@ public class IrisCeilingDecorator extends IrisEngineDecorator { Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType); RNG rng = getRNG(realX, realZ); - ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); if (decorator == null) { return; diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java index b183bece4..5f943c85c 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java @@ -36,7 +36,7 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { RNG rng = getRNG(realX, realZ); - ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); if (decorator == null) { return; diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java index aaca4f012..89e2f4459 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java @@ -36,7 +36,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { RNG rng = getRNG(realX, realZ); - ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); if (decorator == null) { return; diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java index 39bbd4cc8..944cf0213 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java @@ -50,7 +50,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { } RNG rng = getRNG(realX, realZ); - ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); if (decorator == null) { return; diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java index fde5ae2b5..296d5e533 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java @@ -58,7 +58,7 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { boolean underwater = isUnderwater(inferredType, height, fluidHeight); boolean caveSkipFluid = skipsFluid(inferredType); RNG rng = getRNG(realX, realZ); - ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ); + ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); if (decorator == null || !isSlopeValid(decorator, realX, realZ)) { return; @@ -75,7 +75,7 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { } DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ, - data, underwater, caveSkipFluid, getEngine().getMantle()); + data, underwater, caveSkipFluid, getEngine().getMantle(), decorators.log()); } static boolean isUnderwater(InferredType inferredType, int height, int fluidHeight) { diff --git a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java index 8f9296005..7f60b5310 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -23,9 +23,9 @@ import art.arcane.iris.builtin.decorant.Decorator; import art.arcane.iris.engine.data.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; +import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; import com.volmit.noise.NoiseFactory; @@ -57,6 +57,7 @@ final class ResolvedDecorator { private final AtomicCache chanceNoise = new AtomicCache<>(); private final AtomicCache varianceNoise = new AtomicCache<>(); private final AtomicCache heightNoise = new AtomicCache<>(); + private final ModuleLog log; /** * @param blocks the palette as the platform's blocks, each repeated by its weight @@ -64,9 +65,11 @@ final class ResolvedDecorator { * @param forceBlock the block it forces onto the surface, or null * @param whitelist the blocks it may only be placed onto; ignored unless the decorator has a whitelist * @param blacklist the blocks it is never placed onto; ignored unless the decorator has a blacklist + * @param log the log of the module that decorates */ ResolvedDecorator(Decorator settings, long seed, NoiseFactory noise, List blocks, List topBlocks, - PlatformBlockState forceBlock, List whitelist, List blacklist) { + PlatformBlockState forceBlock, List whitelist, List blacklist, + ModuleLog log) { this.settings = settings; this.seed = seed; this.noise = noise; @@ -77,15 +80,16 @@ final class ResolvedDecorator { this.forceBlock = forceBlock; this.whitelist = whitelist.toArray(new PlatformBlockState[0]); this.blacklist = blacklist.toArray(new PlatformBlockState[0]); + this.log = log; } /** {@code settings} ready for {@code engine}: its blocks resolved through the pack, its noise seeded from {@code seed}. */ - static ResolvedDecorator of(Decorator settings, Engine engine, long seed) { + static ResolvedDecorator of(Decorator settings, Engine engine, long seed, ModuleLog log) { var resources = engine.getData().getPackResources(); BlockRegistry registry = resources.blocks(); PlatformBlockState forced = settings.forceBlock().map(spec -> platformState(registry, spec)).orElse(null); return new ResolvedDecorator(settings, seed, resources.noise(), weighted(registry, settings.palette()), - weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist())); + weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist()), log); } private static PlatformBlockState platformState(BlockRegistry registry, BlockSpec spec) { @@ -195,7 +199,7 @@ final class ResolvedDecorator { /** The block of the palette at the position, for decorations that fill a column block by block; null when the palette has no block. */ PlatformBlockState blockAt(IrisBiome biome, double x, double y, double z) { if (blocks.isEmpty()) { - IrisLogging.warnOnce("decorator-empty:" + biome.getName(), "Empty Block Data for " + biome.getName()); + log.warnOnce("decorator-empty:" + biome.getName(), "Empty Block Data for " + biome.getName()); return null; } diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index b2c446447..dbfd240ee 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -39,8 +39,10 @@ import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppressio import art.arcane.iris.engine.object.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.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; +import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import java.util.ArrayList; @@ -509,14 +511,14 @@ public final class IrisStructureLocator { throw new IllegalStateException("Iris structure placement references missing structure '" + selectedKey + "'"); } - StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure); + 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)); + 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())) { @@ -1118,17 +1120,18 @@ public final class IrisStructureLocator { 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(engine.getDimension().getStructures(), data, loadKeys, normalizedLoadKeys, vanillaAliases, + collect(engine.getDimension().getStructures(), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, suppressedVanillaSources, placements, true); KList regions = engine.getDimension().getAllRegions(engine); if (regions != null) { for (IrisRegion region : regions) { - collect(region == null ? null : region.getStructures(), data, + collect(region == null ? null : region.getStructures(), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, suppressedVanillaSources, placements, false); } @@ -1136,7 +1139,7 @@ public final class IrisStructureLocator { KList biomes = engine.getDimension().getReachableBiomes(engine); if (biomes != null) { for (IrisBiome biome : biomes) { - collect(biome == null ? null : biome.getStructures(), data, + collect(biome == null ? null : biome.getStructures(), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, suppressedVanillaSources, placements, false); } @@ -1165,7 +1168,7 @@ public final class IrisStructureLocator { return Collections.unmodifiableSet(nativeKeys); } - private static void collect(KList source, IrisData data, Set loadKeys, + private static void collect(KList source, IrisData data, ModuleLog log, Set loadKeys, Set normalizedLoadKeys, Set vanillaAliases, Set suppressedVanillaSources, List placements, boolean allowNativeSuppression) { @@ -1230,7 +1233,7 @@ public final class IrisStructureLocator { throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey + "' must declare a valid namespaced vanillaSource"); } - if (!StructureGraphCatalog.guaranteesRuntimeOutput(data, structure)) { + 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"); } diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java b/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java index 08df2d833..cef458cb6 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java +++ b/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java @@ -45,6 +45,7 @@ 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; @@ -89,11 +90,11 @@ public final class StructureAssembler { ? this.structure.getMaxSizeChunks() * 16 : 0; } - public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin) { + 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), origin); + return forCompilation(StructureGraphCatalog.compile(activeData, activeStructure, log), origin); } public static StructureAssembler forResolver(StructureGraphResolver resolver, IrisStructure structure, 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 index 9b6a46333..e2ebb3068 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java @@ -5,11 +5,11 @@ 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.iris.spi.IrisLogging; 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; @@ -30,35 +30,35 @@ public final class StructureGraphCatalog { private StructureGraphCatalog() { } - public static StructureGraphCompilation compile(IrisData data, IrisStructure structure) { + 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); + return compileAndReport(activeData, activeStructure, log); } ConcurrentMap catalog = CACHE.get( activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); - return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure)); + return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure, log)); } - public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure) { + public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure, ModuleLog log) { IrisData activeData = Objects.requireNonNull(data); IrisStructure activeStructure = Objects.requireNonNull(structure); - if (!compile(activeData, activeStructure).guaranteesAssemblyOutput()) { + if (!compile(activeData, activeStructure, log).guaranteesAssemblyOutput()) { return false; } String structureKey = activeStructure.getLoadKey(); if (structureKey == null || structureKey.isBlank()) { - return sampleRuntimeAssembly(activeData, activeStructure); + return sampleRuntimeAssembly(activeData, activeStructure, log); } ConcurrentMap catalog = RUNTIME_OUTPUT.get( activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); return catalog.computeIfAbsent( - structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure)); + structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure, log)); } - private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure) { + 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() @@ -66,29 +66,29 @@ public final class StructureGraphCatalog { for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { String message = "[StructureGraph:" + structureKey + "] " + diagnostic.message(); if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) { - IrisLogging.error(message); + log.error(message, null); } else { - IrisLogging.warn(message); + log.warn(message); } } if (!compilation.isAssemblyViable()) { - IrisLogging.error("[StructureGraph:" + structureKey - + "] Graph rejected because deterministic assembly did not complete."); + log.error("[StructureGraph:" + structureKey + + "] Graph rejected because deterministic assembly did not complete.", null); } return compilation; } - private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure) { + 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)); + data, structure, new IrisPosition(0, 64, 0), log); StructureAssemblyResult result = assembler.assemble(new RNG(seed)); if (!result.hasOutput()) { return false; } } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to sample the runtime assembly of a structure", e); return false; } } 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 index 00a49a70c..9bc5992ea 100644 --- 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 @@ -90,7 +90,7 @@ public final class StructureFitting { private void prepare() { vacuumFoundations = SurfaceFitting.prepareSurfaceStructures(blocks, area, starts, surfaceHeight, - SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS); + SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS, fit.log()); TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), this::naturalBlock, this::paletteBlock); RigidSupport.bridgeRigidPieceSupport(blocks, area, starts); } diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java index 262188652..baa1d1ff0 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.framework.structure.fit; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; -import art.arcane.iris.spi.IrisLogging; +import com.volmit.ModuleLog; import com.volmit.block.BlockState; import com.volmit.vanilla.StructureStep; import com.volmit.vanilla.TemplateCells; @@ -66,16 +66,17 @@ final class SurfaceFitting { } static VacuumFoundationPlan prepareSurfaceStructures(FitBlocks blocks, Box area, List starts, - IntBinaryOperator surfaceHeight, int maximumTemplateCells) { + IntBinaryOperator surfaceHeight, int maximumTemplateCells, + ModuleLog log) { if (starts.isEmpty()) { return VacuumFoundationPlan.EMPTY; } Objects.requireNonNull(surfaceHeight, "Surface structure terrain fitting requires an Iris height resolver"); - List anchors = collectSourceSurfaceAnchors(blocks, area, starts, maximumTemplateCells); + List anchors = collectSourceSurfaceAnchors(blocks, area, starts, maximumTemplateCells, log); if (!anchors.isEmpty()) { fitSurfaceTerrain(blocks, area, anchors, surfaceHeight); } - VacuumFootprint vacuum = collectVacuumFootprint(blocks, area, starts, maximumTemplateCells); + VacuumFootprint vacuum = collectVacuumFootprint(blocks, area, starts, maximumTemplateCells, log); if (!vacuum.anchors().isEmpty()) { fitVacuumTerrain(blocks, area, vacuum, surfaceHeight); } @@ -208,7 +209,7 @@ final class SurfaceFitting { } private static List collectSourceSurfaceAnchors(FitBlocks blocks, Box area, List starts, - int maximumTemplateCells) { + int maximumTemplateCells, ModuleLog log) { Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); List anchors = new ArrayList<>(); Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); @@ -228,7 +229,7 @@ final class SurfaceFitting { } catch (TemplateBudgetExceeded ignored) { budgetExceeded = true; warnBudget(WARNED_SOURCE_BUDGET, start, "SOURCE", - "skipping remaining processed footprints for this start"); + "skipping remaining processed footprints for this start", log); } } for (BlockPosition junction : piece.junctions()) { @@ -263,15 +264,15 @@ final class SurfaceFitting { } } - private static void warnBudget(Set warned, FitStart start, String mode, String consequence) { + private static void warnBudget(Set warned, FitStart start, String mode, String consequence, ModuleLog log) { if (warned.add(start.structureId())) { - IrisLogging.warn("Native structure " + mode + " fitting for '" + start.structureId() + log.warn("Native structure " + mode + " fitting for '" + start.structureId() + "' exceeded its bounded template budget; " + consequence); } } private static VacuumFootprint collectVacuumFootprint(FitBlocks blocks, Box area, List starts, - int maximumTemplateCells) { + int maximumTemplateCells, ModuleLog log) { Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); Map anchors = new HashMap<>(); Map columnCaps = new HashMap<>(); @@ -316,7 +317,7 @@ final class SurfaceFitting { } } } catch (TemplateBudgetExceeded ignored) { - warnBudget(WARNED_VACUUM_BUDGET, start, "VACUUM", "using jigsaw junction smoothing for oversized starts"); + warnBudget(WARNED_VACUUM_BUDGET, start, "VACUUM", "using jigsaw junction smoothing for oversized starts", log); continue; } targetAnchors.forEach((column, anchor) -> anchors.merge(column, anchor, SurfaceFitting::preferredVacuumAnchor)); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 94db333c0..1dde569ca 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -82,7 +82,7 @@ public final class LootGiving implements Loot { private static PlacementLoot placementLoot(PackWorld world, Engine engine) { PlatformLootTables platformTables = world.state(PlatformLootTables.class, ignored -> new PlatformLootTables()); - return new PlacementLoot(engine.getData(), platformTables::keys, lootSeed(engine)); + return new PlacementLoot(engine.getData(), platformTables::keys, lootSeed(engine), world.log()); } private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) { diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index e059d4a06..29db05407 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -21,10 +21,10 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.LootResolver; import art.arcane.iris.engine.object.loot.IObjectLoot; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import com.volmit.service.Loot; import java.util.ArrayList; @@ -46,12 +46,14 @@ final class PlacementLoot { private final IrisData data; private final Supplier> platformTables; private final long lootSeed; + private final ModuleLog log; /** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */ - PlacementLoot(IrisData data, Supplier> platformTables, long lootSeed) { + PlacementLoot(IrisData data, Supplier> platformTables, long lootSeed, ModuleLog log) { this.data = data; this.platformTables = platformTables; this.lootSeed = lootSeed; + this.log = log; } /** The platform's loot table keys, which a placement may name, in the form a placement names them. */ @@ -81,7 +83,7 @@ final class PlacementLoot { } Loot.Source source = sourceOf.apply(entry.getName()); if (source == null) { - IrisLogging.warn("Couldn't find loot table " + entry.getName()); + log.warn("Couldn't find loot table " + entry.getName()); continue; } candidates.add(entry, data, new Candidate(source, entry.getWeight())); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java index b45fbe693..0a3a5c243 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -27,6 +27,7 @@ import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import org.jetbrains.annotations.Nullable; @@ -39,13 +40,15 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro private final FloatingIslandBoundarySampler boundarySampler; private final Long2ObjectOpenHashMap sampleCache; private final LongOpenHashSet resolvedSamples; + private final ModuleLog log; - FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler) { + FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { this.data = engineMantle.getData(); this.engine = engineMantle.getEngine(); this.chunkHeight = engine.getHeight(); this.baseSeed = engine.getSeedManager().getTerrain() ^ FloatingIslands.FLOATING_BASE_SEED_SALT; this.boundarySampler = boundarySampler; + this.log = log; this.sampleCache = new Long2ObjectOpenHashMap<>(); this.resolvedSamples = new LongOpenHashSet(); } @@ -61,7 +64,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro resolvedSamples.add(key); return null; } - FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler); + FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler, log); resolvedSamples.add(key); if (sample != null) { sampleCache.put(key, sample); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 6537c02ce..05d869a6f 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -35,7 +35,6 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.math.IrisBlockVector; @@ -44,6 +43,7 @@ import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.documentation.ChunkCoordinates; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import java.io.File; import java.util.HashMap; import java.util.HashSet; @@ -62,9 +62,11 @@ public class FloatingObjectPlacing { private static final IrisObjectRotation ROTATION_NONE = IrisObjectRotation.of(0, 0, 0); private final Engine engine; + private final ModuleLog log; - public FloatingObjectPlacing(Engine engine) { + public FloatingObjectPlacing(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}. */ @@ -74,7 +76,7 @@ public class FloatingObjectPlacing { int minX = x << 4; int minZ = z << 4; RNG chunkRng = new RNG(Cache.key(x, z) + engine.getSeedManager().getMantle() + 0x0FA710BEL); - FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(engine.getMantle(), context.getFloatingIslandBoundarySampler()); + FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(engine.getMantle(), context.getFloatingIslandBoundarySampler(), log); FloatingIslandSample.clearChunkMemo(); @@ -212,7 +214,7 @@ public class FloatingObjectPlacing { } }, null, data); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to place a floating object", e); } } } @@ -297,7 +299,7 @@ public class FloatingObjectPlacing { } } catch (Throwable e) { transaction.discard(); - IrisLogging.reportError(e); + log.error("Failed to place an anchored floating object", e); } } } @@ -399,7 +401,7 @@ public class FloatingObjectPlacing { } } catch (Throwable e) { transaction.discard(); - IrisLogging.reportError(e); + log.error("Failed to place an inverted floating object", e); } } } @@ -559,12 +561,12 @@ public class FloatingObjectPlacing { maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveBottomObjects(target), data, sizeCache, warnedLargeObjects)); } } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to work out the reach of a floating biome's objects", e); } } } } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to work out the reach of the floating biomes' objects", e); } return maxObjectExtent; } @@ -593,11 +595,11 @@ public class FloatingObjectPlacing { } int reach = ObjectPlacing.calculatePlacementReach(size, placement); if (reach > 128 && warnedLargeObjects.add(objectKey)) { - IrisLogging.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); } radius = Math.max(radius, reach); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to size a floating object", e); } } } 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 index 696305827..4dd1c86ba 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java @@ -22,8 +22,8 @@ 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.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.ModuleLog; final class GoldenDebugObjectPlacer implements IObjectPlacer { private static final int[] GOLDEN_DEBUG_TARGET = parseGoldenDebugTarget(resolveGoldenDebugSpec()); @@ -31,10 +31,12 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { private final IObjectPlacer delegate; private final String tag; + private final ModuleLog log; - GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag) { + GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) { this.delegate = delegate; this.tag = tag; + this.log = log; } private static String resolveGoldenDebugSpec() { @@ -77,14 +79,14 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { @Override public int getHighest(int x, int z, IrisData data) { int result = delegate.getHighest(x, z, data); - IrisLogging.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ")=" + result); + 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); - IrisLogging.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result); + log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result); return result; } @@ -106,7 +108,7 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { @Override public boolean isCarved(int x, int y, int z) { boolean result = delegate.isCarved(x, y, z); - IrisLogging.debug("Goldendebug query: tag=" + tag + " isCarved(" + x + "," + y + "," + z + ")=" + result); + log.debug("Goldendebug query: tag=" + tag + " isCarved(" + x + "," + y + "," + z + ")=" + result); return result; } @@ -118,7 +120,7 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { @Override public boolean isSolid(int x, int y, int z) { boolean result = delegate.isSolid(x, y, z); - IrisLogging.debug("Goldendebug query: tag=" + tag + " isSolid(" + x + "," + y + "," + z + ")=" + result); + log.debug("Goldendebug query: tag=" + tag + " isSolid(" + x + "," + y + "," + z + ")=" + result); return result; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index b022b03f3..e4e27f575 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -36,7 +36,7 @@ import java.util.Set; public final class ObjectLocating implements ObjectsAt { @Override public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return ObjectModule.placing(engine(world)).guess(chunkX, chunkZ); + return ObjectModule.placing(engine(world), world.log()).guess(chunkX, chunkZ); } @Override diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 111889133..b4b572e9b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -35,6 +35,7 @@ import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; +import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; import com.volmit.service.SaplingGrowth; @@ -53,6 +54,8 @@ import com.volmit.world.PackWorld; public final class ObjectModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; + private ModuleLog log; + @Override public ModuleInfo info() { return ModuleInfo.of("iris:objects", "Objects", VERSION); @@ -60,11 +63,12 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Objects.PLACE).requires(IrisStages.Carve.CAVES).reach(ObjectModule::reach).run(ObjectModule::place); + graph.define(IrisStages.Objects.PLACE).requires(IrisStages.Carve.CAVES).reach(this::reach).run(ObjectModule::place); } @Override public void register(FeatureRegistry registry) { + log = registry.log(); registry.registerService(ObjectsAt.class, new ObjectLocating()); registry.registerService(SaplingGrowth.class, new TreeGrowing()); registry.registerHeldType(TreeCanopy.class); @@ -85,15 +89,15 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); - placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + placing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); } - private static int reach(PackSettings settings) { - return placing(IrisPackSettings.of(settings).engine()).reach(); + private int reach(PackSettings settings) { + return placing(IrisPackSettings.of(settings).engine(), log).reach(); } - /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks. */ - public static ObjectPlacing placing(Engine engine) { - return engine.getGeneration().state(ObjectPlacing.class, ObjectPlacing::new); + /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks; {@code log} is the module's. */ + public static ObjectPlacing placing(Engine engine, ModuleLog log) { + return engine.getGeneration().state(ObjectPlacing.class, generating -> new ObjectPlacing(generating, log)); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 80e64d2e1..211bee07e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -47,7 +47,6 @@ import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; import art.arcane.iris.engine.object.world.region.IrisRegion; -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.collection.KSet; @@ -59,6 +58,7 @@ import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterStructurePOI; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.project.noise.NoiseType; +import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import art.arcane.iris.spi.PlatformBlockState; @@ -87,18 +87,20 @@ public class ObjectPlacing { private static final Set MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet(); private final Engine engine; + private final ModuleLog log; - public ObjectPlacing(Engine engine) { + public ObjectPlacing(Engine engine, ModuleLog log) { this.engine = engine; + this.log = log; } - private static String placementMarker(IrisObject object, int id, String context) { + private String placementMarker(IrisObject object, int id, String context) { String key = object == null ? null : object.getLoadKey(); if (key == null || key.isEmpty() || key.equals("null")) { String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); if (MISSING_LOAD_KEY_WARNED.add(fingerprint)) { java.io.File file = object == null ? null : object.getLoadFile(); - IrisLogging.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context + log.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context + ", file=" + (file == null ? "" : file.getPath()) + "). " + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); } @@ -137,7 +139,7 @@ public class ObjectPlacing { carvedBlocks++; } } - IrisLogging.debug("Cave object diag: chunk=" + x + "," + z + log.debug("Cave object diag: chunk=" + x + "," + z + " surfaceBiome=" + surfaceBiome.getLoadKey() + " caveBiome=" + caveBiome.getLoadKey() + " surfaceY=" + surfaceY @@ -148,7 +150,7 @@ public class ObjectPlacing { + " sameBiome=" + (caveBiome == surfaceBiome || java.util.Objects.equals(caveBiome.getLoadKey(), surfaceBiome.getLoadKey()))); } if (traceRegen) { - IrisLogging.debug("Regen object layer start: chunk=" + x + "," + z + log.debug("Regen object layer start: chunk=" + x + "," + z + " surfaceBiome=" + surfaceBiome.getLoadKey() + " caveBiome=" + caveBiome.getLoadKey() + " region=" + region.getLoadKey() @@ -165,7 +167,7 @@ public class ObjectPlacing { placeUpperObjects(writer, rng, x, z, xxx, zzz, surfaceY, upperCtx, dimension, complex, traceRegen); } if (traceRegen) { - IrisLogging.debug("Regen object layer done: chunk=" + x + "," + z + log.debug("Regen object layer done: chunk=" + x + "," + z + " biomeSurfacePlacersChecked=" + summary.biomeSurfacePlacersChecked() + " biomeSurfacePlacersTriggered=" + summary.biomeSurfacePlacersTriggered() + " biomeCavePlacersChecked=" + summary.biomeCavePlacersChecked() @@ -245,7 +247,7 @@ public class ObjectPlacing { biomeSurfaceChecked++; boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); if (traceRegen) { - IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + log.debug("Regen object placer chance: chunk=" + x + "," + z + " scope=biome-surface" + " chanceResult=" + chance + " chanceBase=" + i.getChance() @@ -263,10 +265,9 @@ public class ObjectPlacing { errors += result.errors(); } catch (Throwable e) { errors++; - IrisLogging.reportError(e); - IrisLogging.error("Failed to place objects in the following biome: " + surfaceBiome.getName()); - IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); - IrisLogging.error("Are these objects missing?"); + log.error("Failed to place objects in the following biome: " + surfaceBiome.getName(), e); + log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); } } } @@ -278,7 +279,7 @@ public class ObjectPlacing { biomeCaveChecked++; boolean chance = rng.chance(i.getChance()); if (traceRegen) { - IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + log.debug("Regen object placer chance: chunk=" + x + "," + z + " scope=biome-cave" + " chanceResult=" + chance + " chanceBase=" + i.getChance() @@ -296,10 +297,9 @@ public class ObjectPlacing { errors += result.errors(); } catch (Throwable e) { errors++; - IrisLogging.reportError(e); - IrisLogging.error("Failed to place cave objects in the following biome: " + caveBiome.getName()); - IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); - IrisLogging.error("Are these objects missing?"); + log.error("Failed to place cave objects in the following biome: " + caveBiome.getName(), e); + log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); } } } @@ -308,7 +308,7 @@ public class ObjectPlacing { regionSurfaceChecked++; boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); if (traceRegen) { - IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + log.debug("Regen object placer chance: chunk=" + x + "," + z + " scope=region-surface" + " chanceResult=" + chance + " chanceBase=" + i.getChance() @@ -326,10 +326,9 @@ public class ObjectPlacing { errors += result.errors(); } catch (Throwable e) { errors++; - IrisLogging.reportError(e); - IrisLogging.error("Failed to place objects in the following region: " + region.getName()); - IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); - IrisLogging.error("Are these objects missing?"); + log.error("Failed to place objects in the following region: " + region.getName(), e); + log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); } } } @@ -341,7 +340,7 @@ public class ObjectPlacing { regionCaveChecked++; boolean chance = rng.chance(i.getChance()); if (traceRegen) { - IrisLogging.debug("Regen object placer chance: chunk=" + x + "," + z + log.debug("Regen object placer chance: chunk=" + x + "," + z + " scope=region-cave" + " chanceResult=" + chance + " chanceBase=" + i.getChance() @@ -359,10 +358,9 @@ public class ObjectPlacing { errors += result.errors(); } catch (Throwable e) { errors++; - IrisLogging.reportError(e); - IrisLogging.error("Failed to place cave objects in the following region: " + region.getName()); - IrisLogging.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); - IrisLogging.error("Are these objects missing?"); + log.error("Failed to place cave objects in the following region: " + region.getName(), e); + log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); } } } @@ -419,7 +417,7 @@ public class ObjectPlacing { boolean treePlacement = p instanceof IrisProceduralTree; boolean chancePassed = passesProceduralChance(rng, p.getChance()); if (golden) { - IrisLogging.debug("Goldendebug procedural chance: chunk=" + x + "," + z + log.debug("Goldendebug procedural chance: chunk=" + x + "," + z + " scope=" + scope + " placement=" + p.getName() + " passed=" + chancePassed); @@ -438,13 +436,13 @@ public class ObjectPlacing { int minDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); IObjectPlacer basePlacer = p.isPlausible() ? new DecayControlPlacer(writer) : writer; - IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName()) : basePlacer; + IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName(), log) : basePlacer; int density = Math.max(1, p.getDensity()); for (int i = 0; i < density; i++) { IrisObject variant = p.getVariantObject(engine.getData(), rng); if (variant == null) { if (golden) { - IrisLogging.debug("Goldendebug procedural pick: chunk=" + x + "," + z + log.debug("Goldendebug procedural pick: chunk=" + x + "," + z + " placement=" + p.getName() + " densityIndex=" + i + " variant=null"); @@ -469,7 +467,7 @@ public class ObjectPlacing { } if (carving && caveAnchor == null) { if (golden) { - IrisLogging.debug("Goldendebug procedural cave anchor rejected: chunk=" + x + "," + z + log.debug("Goldendebug procedural cave anchor rejected: chunk=" + x + "," + z + " placement=" + p.getName() + " minDepthBelowSurface=" + minDepthBelowSurface); } @@ -480,7 +478,7 @@ public class ObjectPlacing { int id = rng.i(0, Integer.MAX_VALUE); if (golden) { KList pool = p.getVariantObjects(engine.getData()); - IrisLogging.debug("Goldendebug procedural pick: chunk=" + x + "," + z + log.debug("Goldendebug procedural pick: chunk=" + x + "," + z + " placement=" + p.getName() + " densityIndex=" + i + " variant=" + variant.getLoadKey() @@ -496,7 +494,7 @@ public class ObjectPlacing { if (carving) { int caveFloorY = caveAnchor.y(); if (golden) { - IrisLogging.debug("Goldendebug procedural caveFloor: chunk=" + x + "," + z + log.debug("Goldendebug procedural caveFloor: chunk=" + x + "," + z + " placement=" + p.getName() + " xx=" + xx + " zz=" + zz @@ -530,7 +528,7 @@ public class ObjectPlacing { }, null, engine.getData()); } if (golden) { - IrisLogging.debug("Goldendebug procedural result: chunk=" + x + "," + z + log.debug("Goldendebug procedural result: chunk=" + x + "," + z + " placement=" + p.getName() + " variant=" + variant.getLoadKey() + " xx=" + xx @@ -539,8 +537,7 @@ public class ObjectPlacing { + " commit=" + commitResult); } } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.error("Failed to place procedural object '" + p.getName() + "' in " + scope); + log.error("Failed to place procedural object '" + p.getName() + "' in " + scope, e); } } } @@ -670,7 +667,7 @@ public class ObjectPlacing { if (v == null) { nullObjects++; if (traceRegen) { - IrisLogging.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " densityIndex=" + i + " density=" + density @@ -683,9 +680,9 @@ public class ObjectPlacing { IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v); boolean treePlacement = isTreePlacement(v, effectivePlacement); int id = rng.i(0, Integer.MAX_VALUE); - IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey()) : writer; + IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey(), log) : writer; if (golden) { - IrisLogging.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + v.getLoadKey() + " densityIndex=" + i @@ -714,7 +711,7 @@ public class ObjectPlacing { } if (golden) { - IrisLogging.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + v.getLoadKey() + " resultY=" + result @@ -722,7 +719,7 @@ public class ObjectPlacing { } if (traceRegen) { - IrisLogging.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + v.getLoadKey() + " resultY=" + result @@ -734,13 +731,12 @@ public class ObjectPlacing { } } catch (Throwable e) { errors++; - IrisLogging.reportError(e); - IrisLogging.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + v.getLoadKey() + " densityIndex=" + i + " density=" + density - + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage()); + + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage(), e); } } @@ -808,7 +804,7 @@ public class ObjectPlacing { if (object == null) { nullObjects++; if (traceRegen) { - IrisLogging.debug("Regen cave object placement null object: chunk=" + metricChunkX + "," + metricChunkZ + log.debug("Regen cave object placement null object: chunk=" + metricChunkX + "," + metricChunkZ + " scope=" + scope + " densityIndex=" + i + " density=" + density @@ -922,7 +918,7 @@ public class ObjectPlacing { } if (traceRegen) { - IrisLogging.debug("Regen cave object placement result: chunk=" + metricChunkX + "," + metricChunkZ + log.debug("Regen cave object placement result: chunk=" + metricChunkX + "," + metricChunkZ + " scope=" + scope + " object=" + object.getLoadKey() + " resultY=" + result @@ -935,13 +931,12 @@ public class ObjectPlacing { } } catch (Throwable e) { errors++; - IrisLogging.reportError(e); - IrisLogging.error("Regen cave object placement exception: chunk=" + metricChunkX + "," + metricChunkZ + log.error("Regen cave object placement exception: chunk=" + metricChunkX + "," + metricChunkZ + " scope=" + scope + " object=" + object.getLoadKey() + " densityIndex=" + i + " density=" + density - + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage()); + + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage(), e); logCaveReject( scope, "EXCEPTION", @@ -993,9 +988,8 @@ public class ObjectPlacing { try { placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-biome-surface"); } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.error("Failed to place upper-dimension objects in biome " + upperBiome.getName() - + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")"); + log.error("Failed to place upper-dimension objects in biome " + upperBiome.getName() + + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")", e); } } } @@ -1008,9 +1002,8 @@ public class ObjectPlacing { try { placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-region-surface"); } catch (Throwable e) { - IrisLogging.reportError(e); - IrisLogging.error("Failed to place upper-dimension objects in region " + upperRegion.getName() - + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")"); + log.error("Failed to place upper-dimension objects in region " + upperRegion.getName() + + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")", e); } } } @@ -1081,7 +1074,7 @@ public class ObjectPlacing { }, null, engine.getData()); if (traceRegen) { - IrisLogging.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + v.getLoadKey() + " anchorY=" + anchorY @@ -1140,7 +1133,7 @@ public class ObjectPlacing { int suppressed = state.suppressed.getAndSet(0); String anchorYText = anchorY == null ? "none" : String.valueOf(anchorY); String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + String.valueOf(error.getMessage()); - IrisLogging.debug("Cave object reject: scope=" + scope + log.debug("Cave object reject: scope=" + scope + " reason=" + reason + " chunk=" + chunkX + "," + chunkZ + " object=" + objectKey @@ -1496,11 +1489,11 @@ public class ObjectPlacing { } int reach = calculatePlacementReach(size, placement); if (reach > 128 && warnedLargeObjects.add(objectKey)) { - IrisLogging.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); } radius = Math.max(radius, reach); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to work out the reach of an object placement", e); } } } @@ -1586,7 +1579,7 @@ public class ObjectPlacing { try { return IrisObject.sampleSize(engine.getData().getObjectLoader().findFile(objectKey)); } catch (IOException e) { - IrisLogging.reportError(e); + log.error("Failed to size an object", e); } return null; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 5ffbbd75f..e97c60212 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -35,6 +35,7 @@ import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; +import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.service.StructureLocator; import com.volmit.service.VanillaStructures; @@ -63,6 +64,8 @@ import com.volmit.world.PackWorld; public final class StructureModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; + private ModuleLog log; + @Override public ModuleInfo info() { return ModuleInfo.of("iris:structure", "Structures", VERSION); @@ -71,11 +74,12 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { @Override public void install(StageGraph graph) { graph.define(IrisStages.Structure.PLACE).requires(IrisStages.Objects.PLACE).softAfter(IrisStages.Floating.OBJECTS.ref()) - .reach(StructureModule::reach).run(StructureModule::place); + .reach(this::reach).run(StructureModule::place); } @Override public void register(FeatureRegistry registry) { + log = registry.log(); registry.registerSettings(StructureSettings.class); StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new StructureValidator()); @@ -95,14 +99,14 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); - placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + placing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); } - private static int reach(PackSettings settings) { - return placing(IrisPackSettings.of(settings).engine()).reach(); + private int reach(PackSettings settings) { + return placing(IrisPackSettings.of(settings).engine(), log).reach(); } - private static StructurePlacing placing(Engine engine) { - return engine.getGeneration().state(StructurePlacing.class, StructurePlacing::new); + private static StructurePlacing placing(Engine engine, ModuleLog log) { + return engine.getGeneration().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log)); } } 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 index 82fb45784..5297cc4c5 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -39,11 +39,11 @@ import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; 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.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.math.IrisBlockVector; @@ -72,9 +72,11 @@ 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) { + 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}. */ @@ -99,7 +101,7 @@ public class StructurePlacing { boolean trace = IrisSettings.get().getGeneral().isDebug(); if (trace) { - IrisLogging.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.getStructures() + log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.getStructures() + " anchor=" + placement.resolvedAnchor() + " band=" + placement.getMinHeight() + ".." + placement.getMaxHeight()); } @@ -112,7 +114,7 @@ public class StructurePlacing { RNG rng = resolved.rng(); int baseY = resolved.baseY(); if (trace) { - IrisLogging.debug("[StructTrace] ASSEMBLED chunk=" + cx + "," + cz + " key=" + key + " baseY=" + baseY + " pieces=" + pieces.size()); + log.debug("[StructTrace] ASSEMBLED chunk=" + cx + "," + cz + " key=" + key + " baseY=" + baseY + " pieces=" + pieces.size()); } if (!placement.isAnchoredUnderground()) { @@ -319,7 +321,7 @@ public class StructurePlacing { } if (IrisSettings.get().getGeneral().isDebug()) { - IrisLogging.info("Overbore carving structure cavern: shape=" + shape + " pieces=" + pieces.size() + 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); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 4d6a91412..41dd78bc4 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -31,6 +31,7 @@ import art.arcane.iris.engine.mantle.components.CaveCarving; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; import com.volmit.service.CaveBiomes; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; @@ -82,7 +83,8 @@ public final class CarveModule implements IrisModule { if (chunk.bypassesMantleStages()) { return; } - chunk.state(CaveApplying.class, CaveApplying::new).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, + ModuleLog log = context.log(); + chunk.state(CaveApplying.class, generating -> new CaveApplying(generating, log)).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.blocks(), chunk.multicore(), chunk.context()); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index c4fa70d32..306822d7d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -44,6 +44,7 @@ import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.slices.MarkerMatter; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import lombok.Data; import art.arcane.iris.spi.PlatformBlockState; @@ -72,11 +73,11 @@ public class CaveApplying { private final IrisSurfaceDecorator surfaceDecorator; private final IrisCeilingDecorator ceilingDecorator; - public CaveApplying(Engine engine) { + public CaveApplying(Engine engine, ModuleLog log) { this.engine = engine; rng = new RNG(engine.getSeedManager().getCarve()); decorators = BiomeDecorators.of(engine); - layers = BiomeLayers.of(engine); + layers = BiomeLayers.of(engine, log); palettes = TerrainPalettes.of(engine); surfaceDecorator = new IrisSurfaceDecorator(engine); ceilingDecorator = new IrisCeilingDecorator(engine); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 8b5f55ff9..f82faea84 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -38,7 +38,6 @@ import art.arcane.iris.engine.terrain.BiomeLayers; import art.arcane.iris.engine.terrain.ResolvedLayer; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.hunk.Hunk; @@ -51,6 +50,7 @@ import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.ModuleLog; import java.util.IdentityHashMap; import static art.arcane.iris.engine.mantle.EngineMantle.AIR; @@ -68,6 +68,7 @@ public class FloatingIslands { private final RNG rng; private final EngineDecorator seaSurfaceDecorator; private final BiomeLayers biomeLayers; + private final ModuleLog log; private KList generateBottomPaletteLayers(ResolvedFloatingChild entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette() == null || entry.settings().bottomPalette().isEmpty()) { @@ -108,7 +109,7 @@ public class FloatingIslands { try { generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom())); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to pick a block of a floating island's palette", e); } } @@ -207,11 +208,12 @@ public class FloatingIslands { } } - public FloatingIslands(Engine engine) { + public FloatingIslands(Engine engine, ModuleLog log) { this.engine = engine; + this.log = log; rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); - biomeLayers = BiomeLayers.of(engine); + biomeLayers = BiomeLayers.of(engine, log); } /** Fills the islands' solids into the chunk whose first block is {@code x}, {@code z}. */ @@ -233,7 +235,7 @@ public class FloatingIslands { if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { continue; } - FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); if (sample == null) { continue; } @@ -318,7 +320,7 @@ public class FloatingIslands { if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { continue; } - FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); if (sample == null) { continue; } @@ -338,7 +340,7 @@ public class FloatingIslands { RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(baseSeed, wx, wz)); FloatingDecorator.decorateColumn(engine, target, DecorationPart.NONE, xf, zf, wx, wz, topY, max, output, colRng, NOOP_DECORATION_MISS); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to decorate the top of a floating island", e); } } } @@ -370,7 +372,7 @@ public class FloatingIslands { try { seaSurfaceDecorator.decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, output, target, fluidTopY, chunkHeight); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to decorate the sea surface of a floating island", e); } } } @@ -402,7 +404,7 @@ public class FloatingIslands { engine.getMantle().getMantle().set(wx, y, wz, matter); } } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("Failed to write the sky biomes of a floating island", e); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index cc22d9244..75db8e168 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -29,6 +29,7 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; @@ -44,6 +45,8 @@ import com.volmit.stage.StageGraph; public final class FloatingModule implements IrisModule { private static final String VERSION = "built-in"; + private ModuleLog log; + @Override public ModuleInfo info() { return ModuleInfo.of("iris:floating", "Floating islands", VERSION); @@ -51,13 +54,14 @@ public final class FloatingModule implements IrisModule { @Override public void register(FeatureRegistry registry) { + log = registry.log(); registry.registerSettings(FloatingChildSettings.class); registry.registerSettings(MergeFloatingChildrenSettings.class); } @Override public void install(StageGraph graph) { - graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE.ref()).reach(FloatingModule::objectReach) + graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE.ref()).reach(this::objectReach) .run(FloatingModule::objects); // Ordering only: iris:post ships in the built-ins jar, which a pack may not have. graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH.ref()).run(FloatingModule::solids); @@ -66,28 +70,28 @@ public final class FloatingModule implements IrisModule { private static void objects(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); - objectPlacing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + objectPlacing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); } - private static int objectReach(PackSettings settings) { - return objectPlacing(IrisPackSettings.of(settings).engine()).reach(); + private int objectReach(PackSettings settings) { + return objectPlacing(IrisPackSettings.of(settings).engine(), log).reach(); } private static void solids(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - islands(chunk).fillSolids(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + islands(chunk, context.log()).fillSolids(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); } private static void decorate(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - islands(chunk).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + islands(chunk, context.log()).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); } - private static FloatingObjectPlacing objectPlacing(Engine engine) { - return engine.getGeneration().state(FloatingObjectPlacing.class, FloatingObjectPlacing::new); + private static FloatingObjectPlacing objectPlacing(Engine engine, ModuleLog log) { + return engine.getGeneration().state(FloatingObjectPlacing.class, generating -> new FloatingObjectPlacing(generating, log)); } - private static FloatingIslands islands(IrisChunk chunk) { - return chunk.state(FloatingIslands.class, FloatingIslands::new); + private static FloatingIslands islands(IrisChunk chunk, ModuleLog log) { + return chunk.state(FloatingIslands.class, generating -> new FloatingIslands(generating, log)); } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index a2d0db2dc..d73057b02 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -28,10 +28,10 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.NativeStructureVolume; import art.arcane.iris.engine.framework.PlacedObject; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.spi.IrisLogging; import art.arcane.volmlib.util.collection.KList; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; import com.volmit.block.BlockState; import com.volmit.object.ObjectBlock; import com.volmit.stage.PlacementStageContext; @@ -87,7 +87,7 @@ public final class ValidateModule implements IrisModule { int y = context.output(IrisStages.Anchor.HEIGHT).y(); boolean sampled = placement.requestedY() < 0; if (sampled && config.getCarvingSupport().supportsSurface() && isOnBedrock(prepared, y)) { - warnImplausibleBedrockPlacement(placement, config, y); + warnImplausibleBedrockPlacement(placement, config, y, context.log()); context.reject("bedrock-anchor"); return; } @@ -239,7 +239,7 @@ public final class ValidateModule implements IrisModule { return false; } - private static void warnImplausibleBedrockPlacement(IrisPlacement placement, IrisObjectPlacement config, int y) { + private static void warnImplausibleBedrockPlacement(IrisPlacement placement, IrisObjectPlacement config, int y, ModuleLog log) { String key = placement.object().getLoadKey(); String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); long now = System.currentTimeMillis(); @@ -248,7 +248,7 @@ public final class ValidateModule implements IrisModule { return; } IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); - IrisLogging.warn("Implausible object placement rejected: " + log.warn("Implausible object placement rejected: " + (key == null ? "" : key) + " resolved anchorY=" + y + " at (" + placement.x() + "," + placement.z() + ") mode=" + config.getMode() + " carving=" + config.getCarvingSupport() diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index ae339e57f..668cebc73 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -23,9 +23,9 @@ import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; +import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; import java.util.Arrays; @@ -78,13 +78,13 @@ public final class FloatingIslandSample { FOOTPRINT_MEMO.get().clear(); } - public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { + public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL); HashMap memo = CHUNK_MEMO.get(); if (memo.containsKey(key)) { return memo.get(key); } - FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); + FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); memo.put(key, result); return result; } @@ -94,10 +94,10 @@ public final class FloatingIslandSample { return null; } - private static void warnNullCng(String styleField, IrisBiome parent) { + private static void warnNullCng(String styleField, IrisBiome parent, ModuleLog log) { if (NULL_CNG_WARNED.compareAndSet(false, true)) { String biomeKey = parent == null ? "" : parent.getLoadKey(); - IrisLogging.warn("Floating child biome on " + biomeKey + " has a null CNG for " + styleField + log.warn("Floating child biome on " + biomeKey + " has a null CNG for " + styleField + " (style factory returned null or AtomicCache swallowed an exception); skipping floating sampling until pack is fixed"); } } @@ -176,41 +176,41 @@ public final class FloatingIslandSample { } private static int maximumEdgeFieldWidth(KList entries, long baseSeed, - IrisData data, IrisBiome parent) { + IrisData data, IrisBiome parent, ModuleLog log) { int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH; for (ResolvedFloatingChild entry : entries) { - FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent); + FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent, log); maximumWidth = Math.max(maximumWidth, profile.fieldWidth()); } return maximumWidth; } private static FloatingIslandEdgeProfile resolveEdgeProfile(ResolvedFloatingChild entry, long baseSeed, - IrisData data, IrisBiome parent) { + IrisData data, IrisBiome parent, ModuleLog log) { FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data); if (profile != null) { return profile; } - warnNullCng("edgeTaperVariationStyle", parent); + warnNullCng("edgeTaperVariationStyle", parent, log); return FloatingIslandEdgeProfile.DEFAULT; } - public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { + public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { List settings = FloatingChildren.declaredBy(parent); if (settings.isEmpty()) { return reject(REJECT_NO_ENTRIES); } KList entries = new KList<>(FloatingChildren.of(data).of(settings)); - return sample(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler); + return sample(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); } - static FloatingIslandSample sample(IrisBiome parent, KList entries, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler) { - int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent); + static FloatingIslandSample sample(IrisBiome parent, KList entries, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent, log); int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); if (FloatingChildren.merges(parent)) { return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, - parentBoundaryDistance, boundaryFieldWidth); + parentBoundaryDistance, boundaryFieldWidth, log); } ResolvedFloatingChild entry; @@ -221,7 +221,7 @@ public final class FloatingIslandSample { ResolvedFloatingChild reference = entries.getFirst(); CNG picker = reference.getPickerCng(baseSeed, data); if (picker == null) { - warnNullCng("pickerStyle", parent); + warnNullCng("pickerStyle", parent, log); return reject(REJECT_NO_PICK); } FloatingIslandBoundarySampler.OwnershipSample ownership = boundarySampler.ownership( @@ -234,20 +234,20 @@ public final class FloatingIslandSample { } return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, - parentBoundaryDistance, ownershipBoundaryDistance); + parentBoundaryDistance, ownershipBoundaryDistance, log); } private static FloatingIslandSample sampleMerged(IrisBiome parent, KList entries, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, - int parentBoundaryDistance, int boundaryFieldWidth) { + int parentBoundaryDistance, int boundaryFieldWidth, ModuleLog log) { KList samples = new KList<>(); int minY = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; for (ResolvedFloatingChild entry : entries) { FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, - boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1); + boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1, log); if (sample == null) { continue; } @@ -311,11 +311,11 @@ public final class FloatingIslandSample { private static FloatingIslandSample sampleEntry(IrisBiome parent, ResolvedFloatingChild entry, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, - int parentBoundaryDistance, int ownershipBoundaryDistance) { - FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent); + int parentBoundaryDistance, int ownershipBoundaryDistance, ModuleLog log) { + FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent, log); CNG footprintCng = entry.getFootprintCng(baseSeed, data); if (footprintCng == null) { - warnNullCng("footprintStyle", parent); + warnNullCng("footprintStyle", parent, log); return reject(REJECT_NO_SEED); } double threshold = Math.max(0, Math.min(1, entry.settings().footprintThreshold())); @@ -341,7 +341,7 @@ public final class FloatingIslandSample { CNG altitudeCng = entry.getAltitudeCng(baseSeed, data); if (altitudeCng == null) { - warnNullCng("altitudeStyle", parent); + warnNullCng("altitudeStyle", parent, log); return reject(REJECT_NO_SEED); } double altNoise = altitudeCng.noise(wx, wz); @@ -352,12 +352,12 @@ public final class FloatingIslandSample { int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); IrisBiome target = entry.getRealBiome(parent, data); - int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data); + int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data, log); int topH = roundedEdgeHeight(fullTopHeight, edgeFade); CNG bottomCng = entry.getBottomCng(baseSeed, data); if (bottomCng == null) { - warnNullCng("bottomStyle", parent); + warnNullCng("bottomStyle", parent, log); return reject(REJECT_NO_SEED); } double bottomNoise = bottomCng.noise(wx, wz); @@ -775,7 +775,7 @@ public final class FloatingIslandSample { } } - private static int computeTopHeight(ResolvedFloatingChild entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data) { + private static int computeTopHeight(ResolvedFloatingChild entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data, ModuleLog log) { int maxTopHeight = Math.max(0, entry.settings().maxTopHeight()); if (maxTopHeight == 0) { return 0; @@ -785,7 +785,7 @@ public final class FloatingIslandSample { case NOISE -> { CNG topCng = entry.getTopShapeCng(baseSeed, data); if (topCng == null) { - warnNullCng("topShapeStyle", null); + warnNullCng("topShapeStyle", null, log); yield maxTopHeight / 2; } double n = topCng.noise(wx, wz); 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 index e99ff02aa..a8882ca8d 100644 --- 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 @@ -83,7 +83,7 @@ final class IrisBiomeColorRenderer { } case LAYER_LOAD -> { return biome.getCacheColorLayerLoad().aquire(() -> { - BiomeLayers layers = BiomeLayers.of(engine); + BiomeLayers layers = BiomeLayers.of(engine, engine.getGeneration().world().log()); return Color.getHSBColor(0.625f, (float) (BiomeLayers.layersOf(biome).size() / layers.busiestLayerCount(engine)), 1f); }); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index afe14ae5e..d55ad48ca 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -34,7 +34,6 @@ import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; @@ -108,7 +107,7 @@ public final class EntitySpawning implements EntitySpawns { List spawners = new ArrayList<>(); for (String key : marker.spawners()) { if (SpawnResources.spawner(engine.getData(), key) == null) { - IrisLogging.error("Cannot load spawner: " + key + " for marker " + tag); + world.log().error("Cannot load spawner: " + key + " for marker " + tag, null); continue; } spawners.add(key); @@ -216,7 +215,7 @@ public final class EntitySpawning implements EntitySpawns { private void addAttempt(List attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) { EntityDefinition entity = SpawnResources.entity(engine.getData(), candidate.spawn().entity()); if (entity == null) { - IrisLogging.debug(" You are trying to spawn an entity that does not exist!"); + world.log().debug(" You are trying to spawn an entity that does not exist!"); return; } diff --git a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java index 00a80dccf..957f84278 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java +++ b/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java @@ -35,13 +35,13 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -67,20 +67,22 @@ public final class BiomeLayers { } private final Supplier layerBlocks; + private final ModuleLog log; private final Map resolved = new ConcurrentHashMap<>(); private final Map>> surfaceHeights = new ConcurrentHashMap<>(); private final Map>> seaHeights = new ConcurrentHashMap<>(); private volatile Double busiestBiomeLayerCount; - /** The layers of the world {@code engine} generates now. */ - public static BiomeLayers of(Engine engine) { + /** The layers of the world {@code engine} generates now, reporting failures to {@code log}. */ + public static BiomeLayers of(Engine engine, ModuleLog log) { return engine.getGeneration().state(BiomeLayers.class, - generating -> new BiomeLayers(() -> LayerBlocks.of(generating.getGeneration().world()))); + generating -> new BiomeLayers(() -> LayerBlocks.of(generating.getGeneration().world()), log)); } /** The layers of a world whose layer blocks {@code layerBlocks} gives, asked for when a layer first picks a block. */ - public BiomeLayers(Supplier layerBlocks) { + public BiomeLayers(Supplier layerBlocks, ModuleLog log) { this.layerBlocks = layerBlocks; + this.log = log; } /** {@code layer} ready for this world; its block picks are the world's {@link LayerBlocks}. */ @@ -272,7 +274,7 @@ public final class BiomeLayers { try { blocks.add(layer.get(random, index + j, (wx + j) / zoom, j, (wz - j) / zoom)); } catch (Throwable e) { - IrisLogging.reportError(e); + log.error("A biome layer failed to pick a block", e); } } From 78eee638ae44b3b2f40049ae2a037737571b3ae8 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 14:46:22 +0200 Subject: [PATCH 063/139] iris:post reads its neighbours' heights through TerrainSampler.surfaceY, which spares the host the slope of every column of the height plane --- .../java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 33aff2573..e25ebad01 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -146,7 +146,7 @@ final class SurfaceSmoothing { } private int surfaceHeight(int x, int z) { - return (int) Math.round(terrain.column(x, z).surfaceY()); + return (int) Math.round(terrain.surfaceY(x, z)); } private void post(int localX, int localZ) { From 0b02cb3298066afebf487a3b4e1ea8e69332b68b Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 15:18:05 +0200 Subject: [PATCH 064/139] Mechanical: Vector3i, IrisVector, IrisBlockVector, VectorMap, AtomicCache and Cache's key helpers come from VolmLib --- .../arcane/iris/engine/actuator/ResolvedOre.java | 2 +- .../iris/engine/decorator/ResolvedDecorator.java | 2 +- .../components/CaveObjectPlacementTransaction.java | 6 +++--- .../components/FloatingIslandSampleResolver.java | 4 ++-- .../mantle/components/FloatingObjectPlacing.java | 6 +++--- .../engine/mantle/components/ObjectPlacing.java | 14 +++++++------- .../components/StructureCarvingFootprint.java | 2 +- .../engine/mantle/components/StructurePlacing.java | 6 +++--- .../arcane/iris/engine/modifier/DepositPlacer.java | 2 +- .../iris/engine/modifier/ResolvedDeposit.java | 4 ++-- .../engine/modifier/ResolvedDepositVariant.java | 2 +- .../IrisCompatabilityBlockFilter.java | 2 +- .../compatibility/IrisCompatabilityItemFilter.java | 2 +- .../iris/engine/object/loot/IrisObjectLoot.java | 2 +- .../engine/object/loot/IrisObjectVanillaLoot.java | 2 +- .../engine/object/marker/IrisObjectMarker.java | 2 +- .../iris/engine/object/material/IrisBlockData.java | 2 +- .../object/material/IrisMaterialPalette.java | 2 +- .../object/noise/expression/IrisExpression.java | 2 +- .../noise/expression/IrisExpressionLoad.java | 2 +- .../object/placement/IrisSurfaceSupport.java | 2 +- .../engine/object/placement/ObjectSpinKernel.java | 2 +- .../engine/object/placement/PrepareModule.java | 2 +- .../engine/object/placement/PreparedPlacement.java | 2 +- .../iris/engine/object/prefab/IrisObject.java | 10 +++++----- .../iris/engine/object/prefab/IrisObjectIO.java | 4 ++-- .../engine/object/prefab/IrisObjectRotation.java | 2 +- .../iris/engine/object/prefab/IrisObjectScale.java | 2 +- .../engine/object/prefab/IrisObjectShaping.java | 8 ++++---- .../engine/object/prefab/IrisObjectTransforms.java | 6 +++--- .../engine/object/prefab/IrisObjectTranslate.java | 2 +- .../iris/engine/object/prefab/LegacyTileData.java | 2 +- .../object/procedural/IrisProceduralBlocks.java | 4 ++-- .../procedural/ResolvedProceduralPlacement.java | 2 +- .../object/procedural/coral/CoralGenerator.java | 2 +- .../object/procedural/crystal/CrystalCanvas.java | 2 +- .../procedural/crystal/CrystalGenerator.java | 2 +- .../formation/FormationBlockResolver.java | 2 +- .../procedural/formation/FormationCanvas.java | 2 +- .../procedural/formation/FormationGenerator.java | 2 +- .../formation/FormationShapeBuilder.java | 2 +- .../object/procedural/fungi/FungusCapBuilder.java | 2 +- .../object/procedural/fungi/FungusGenerator.java | 2 +- .../procedural/fungi/FungusShelfBuilder.java | 2 +- .../object/procedural/fungi/FungusStemBuilder.java | 2 +- .../object/procedural/ruin/RuinBlockCanvas.java | 2 +- .../procedural/ruin/RuinDecoratorApplier.java | 2 +- .../object/procedural/ruin/RuinGenerator.java | 2 +- .../object/procedural/tree/IrisProceduralTree.java | 2 +- .../procedural/tree/ProceduralTreeGenerator.java | 2 +- .../iris/engine/object/runtime/IrisEngineData.java | 6 +++--- .../iris/engine/object/terrain/IrisGenerator.java | 2 +- .../terrain/carving/ResolvedCarvingEntry.java | 2 +- .../floating/FloatingIslandBoundarySampler.java | 4 ++-- .../terrain/floating/ResolvedFloatingChild.java | 2 +- .../arcane/iris/engine/object/value/IrisColor.java | 2 +- .../iris/engine/object/world/biome/IrisBiome.java | 2 +- .../object/world/biome/IrisBiomeGenLinks.java | 2 +- .../object/world/biome/IrisBiomeGeneratorLink.java | 2 +- .../biome/custom/IrisBiomeCustomParticle.java | 2 +- .../world/biome/custom/IrisBiomeCustomSpawn.java | 2 +- .../object/world/dimension/IrisDimension.java | 2 +- .../engine/object/world/region/IrisRegion.java | 2 +- .../arcane/iris/engine/terrain/BiomeLayers.java | 2 +- .../arcane/iris/engine/terrain/ResolvedLayer.java | 2 +- .../iris/engine/terrain/TerrainPalettes.java | 2 +- 66 files changed, 94 insertions(+), 94 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java index 721dbbb0c..ec1d1c72c 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.terrain.OreGenerator; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; diff --git a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java index 7f60b5310..f5166ba37 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.decorant.Decorator; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.spi.PlatformBlockState; 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 index 8f14ee5a9..c29157880 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.Cache; +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; @@ -87,7 +87,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { } int getCaveCeiling(int x, int z) { - long key = Cache.key(x, z); + long key = CacheKey.key(x, z); int cached = caveCeilings.get(key); if (cached != CACHE_MISS) { return cached; @@ -215,7 +215,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { } private int getSurfaceHeight(int x, int z) { - long key = Cache.key(x, z); + long key = CacheKey.key(x, z); int cached = surfaceHeights.get(key); if (cached != CACHE_MISS) { return cached; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java index 0a3a5c243..825ef326e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.engine.modifier.FloatingIslands; @@ -55,7 +55,7 @@ final class FloatingIslandSampleResolver implements IslandObjectPlacer.SamplePro @Override public @Nullable FloatingIslandSample sample(int x, int z) { - long key = Cache.key(x, z); + long key = CacheKey.key(x, z); if (resolvedSamples.contains(key)) { return sampleCache.get(key); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 05d869a6f..b24ba27e0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -24,7 +24,7 @@ import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; @@ -37,7 +37,7 @@ import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.documentation.ChunkCoordinates; @@ -75,7 +75,7 @@ public class FloatingObjectPlacing { IrisData data = engine.getData(); int minX = x << 4; int minZ = z << 4; - RNG chunkRng = new RNG(Cache.key(x, z) + engine.getSeedManager().getMantle() + 0x0FA710BEL); + RNG chunkRng = new RNG(CacheKey.key(x, z) + engine.getSeedManager().getMantle() + 0x0FA710BEL); FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(engine.getMantle(), context.getFloatingIslandBoundarySampler(), log); FloatingIslandSample.clearChunkMemo(); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 211bee07e..87f2a3f23 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -30,7 +30,7 @@ import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.util.common.data.B; -import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.mantle.MantleWriter; @@ -62,7 +62,7 @@ import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import java.io.IOException; import java.util.Locale; @@ -123,7 +123,7 @@ public class ObjectPlacing { public void place(MantleWriter writer, int x, int z, ChunkContext context) { IrisComplex complex = context.getComplex(); boolean traceRegen = isRegenTraceThread(); - RNG rng = applyNoise(x, z, Cache.key(x, z) + engine.getSeedManager().getMantle()); + RNG rng = applyNoise(x, z, CacheKey.key(x, z) + engine.getSeedManager().getMantle()); int xxx = 8 + (x << 4); int zzz = 8 + (z << 4); IrisRegion region = complex.getRegionStream().get(xxx, zzz); @@ -1428,7 +1428,7 @@ public class ObjectPlacing { public Set guess(int x, int z) { // todo The guess doesnt bring into account that the placer may return -1 - RNG rng = applyNoise(x, z, Cache.key(x, z) + engine.getSeedManager().getMantle()); + RNG rng = applyNoise(x, z, CacheKey.key(x, z) + engine.getSeedManager().getMantle()); IrisBiome biome = engine.getSurfaceBiome((x << 4) + 8, (z << 4) + 8); IrisRegion region = engine.getRegion((x << 4) + 8, (z << 4) + 8); Set v = new KSet<>(); @@ -1610,7 +1610,7 @@ public class ObjectPlacing { settingCaches.put(settingKey, columnCache); } - long columnKey = Cache.key(x, z); + long columnKey = CacheKey.key(x, z); KList anchors = columnCache.get(columnKey); if (anchors != null) { return anchors; @@ -1622,7 +1622,7 @@ public class ObjectPlacing { } private byte[] getCarvedColumn(MantleWriter writer, int x, int z, int height) { - long columnKey = Cache.key(x, z); + long columnKey = CacheKey.key(x, z); byte[] carvedColumn = carvedColumns.get(columnKey); if (carvedColumn != null && carvedColumn.length == height) { return carvedColumn; @@ -1634,7 +1634,7 @@ public class ObjectPlacing { } private int getSurfaceHeight(int x, int z) { - long columnKey = Cache.key(x, z); + long columnKey = CacheKey.key(x, z); int surfaceY = surfaceHeights.get(columnKey); if (surfaceY != Integer.MIN_VALUE) { return surfaceY; 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 index 0d3548522..119a963c1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java @@ -4,7 +4,7 @@ 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.iris.util.common.math.IrisBlockVector; +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; 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 index 5297cc4c5..f461f23f8 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -23,7 +23,7 @@ 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.iris.engine.data.cache.Cache; +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; @@ -46,7 +46,7 @@ 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.iris.util.common.math.IrisBlockVector; +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; @@ -315,7 +315,7 @@ public class StructurePlacing { CNG blob = null; CNG roll = null; if (eroded) { - RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + Cache.key(bounds[0], bounds[2])); + RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + CacheKey.key(bounds[0], bounds[2])); blob = CNG.signature(noiseRng); roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17)); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index a6fa011ca..b5f38119f 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -176,7 +176,7 @@ public class DepositPlacer extends EngineAssignedComponent { IrisDimension dimension = getDimension(); - for (art.arcane.iris.util.common.math.IrisBlockVector j : clump.getBlocks().keys()) { + for (art.arcane.volmlib.util.math.IrisBlockVector j : clump.getBlocks().keys()) { int nx = j.getBlockX() + x; int ny = j.getBlockY() + y; int nz = j.getBlockZ() + z; diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java index 1aaf2d4e5..889239fc8 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java @@ -27,8 +27,8 @@ import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.collection.KSet; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java index b1a6dce34..5330b3b93 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.deposit.DepositVariant; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; 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 index 5ca1bfa6b..ee3dc6962 100644 --- a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java +++ b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.compatibility; import art.arcane.iris.platform.bukkit.BukkitBlockResolution; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; 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 index 2579ed62b..6886115eb 100644 --- a/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java +++ b/src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.compatibility; import art.arcane.iris.platform.bukkit.BukkitBlockResolution; import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java index 076519f06..ce6ff7c59 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; +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.MinNumber; diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java index 3ca950d5a..4ad466e2f 100644 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java +++ b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java @@ -2,7 +2,7 @@ package art.arcane.iris.engine.object.loot; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; +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.MinNumber; diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java index f61e8b998..4c3ffe0bb 100644 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java +++ b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.marker; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.engine.object.material.IrisBlockData; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; 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 index 472433247..dd2e3f4bb 100644 --- a/src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java +++ b/src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java @@ -23,7 +23,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; 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 index d4b9216dd..3958db76a 100644 --- a/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java +++ b/src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java @@ -22,7 +22,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; 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 index fdb76bad9..77c6a3b3f 100644 --- 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 @@ -23,7 +23,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; 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 index 0de6b5aeb..fa69066d8 100644 --- 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 @@ -22,7 +22,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java index d8fce21f7..67ab79b97 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java @@ -3,7 +3,7 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import java.util.Arrays; import java.util.List; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java index 84513c78a..c763bfc81 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java @@ -3,7 +3,7 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; /** * Precomputed vector rotation for a single placement. diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 1ed36114b..6a4dc7e9d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -29,7 +29,7 @@ import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java index 5ca9cb784..e2b04c00b 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.anchor.PlaceMode; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.iris.util.project.noise.CNG; import com.volmit.world.BlockPosition; 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 index cb6a2e1e7..5e8e05cb5 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -27,16 +27,16 @@ 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.iris.engine.data.cache.AtomicCache; +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.iris.util.common.data.VectorMap; +import art.arcane.volmlib.util.data.VectorMap; import art.arcane.iris.util.common.math.AxisAlignedBB; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.IrisVector; -import art.arcane.iris.util.common.math.Vector3i; +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; 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 index 1cda4d051..0e6660bea 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java @@ -23,8 +23,8 @@ 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.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.Vector3i; +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; 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 index e9d6b801b..8f613a141 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java @@ -26,7 +26,7 @@ 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.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import lombok.AllArgsConstructor; 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 index be7afb455..55498896a 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java @@ -23,7 +23,7 @@ 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.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import lombok.AllArgsConstructor; import lombok.Data; 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 index f348832ad..7b840be99 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java @@ -21,10 +21,10 @@ package art.arcane.iris.engine.object.prefab; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.IrisVector; -import art.arcane.iris.util.common.math.Vector3i; +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; 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 index abd547264..ba0c7020d 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java @@ -21,9 +21,9 @@ 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.iris.util.common.data.VectorMap; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.IrisVector; +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; 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 index ff57eb6da..a479e5d3b 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java @@ -23,7 +23,7 @@ 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.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; 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 index 70ed81541..d69ea1cab 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java @@ -12,7 +12,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java index f18a45811..9a49de54a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java @@ -22,8 +22,8 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.math.IrisBlockVector; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.PaletteSpec; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java index 695d1b211..40b007f94 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java @@ -26,7 +26,7 @@ import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java index ee6c1c48d..f0f5d0d18 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java @@ -24,7 +24,7 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java index 2a7946f43..072c1029f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java index 03087c84c..f2e1c1b2d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java @@ -24,7 +24,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java index 7ee88de5a..16b468853 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java @@ -25,7 +25,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; public final class FormationBlockResolver { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java index 7bf533008..bc38eee3a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java index 8d2d5c79e..bd066d8e2 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java @@ -23,7 +23,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java index bc2f78893..80fb7e15c 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.formation; import art.arcane.iris.builtin.objects.formation.Formation; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java index 460e0cc7a..90519d6bf 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java @@ -25,7 +25,7 @@ import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java index 293c116f0..7f4581543 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java @@ -23,7 +23,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java index 2e34768d5..cdb2f1a48 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.fungi; import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java index 4f82f80a7..186c31b8b 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.procedural.fungi; import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java index abdd58932..0b6cf7003 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java index a42d2a437..f99c429e5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java @@ -22,7 +22,7 @@ import art.arcane.iris.builtin.objects.ruin.RuinDecorator; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java index b523bb2b8..35370c21f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java @@ -25,7 +25,7 @@ import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.iris.util.common.math.Vector3i; +import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java index 5f8868801..80d69facd 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java @@ -37,7 +37,7 @@ import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java index 2ff68a5a0..87ac0bcdd 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -22,7 +22,7 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.math.IrisBlockVector; +import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java index f465ec8a7..0fa145932 100644 --- a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java +++ b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.runtime; import art.arcane.iris.engine.object.entity.spawn.IrisSpawnerCooldowns; -import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; import lombok.Data; @@ -33,11 +33,11 @@ public class IrisEngineData extends IrisSpawnerCooldowns { private Long seed = null; public void removeChunk(int x, int z) { - chunks.remove(Cache.key(x, z)); + chunks.remove(CacheKey.key(x, z)); } public IrisSpawnerCooldowns getChunk(int x, int z) { - return chunks.computeIfAbsent(Cache.key(x, z), k -> new IrisSpawnerCooldowns()); + return chunks.computeIfAbsent(CacheKey.key(x, z), k -> new IrisSpawnerCooldowns()); } public void cleanup(Engine engine) { 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 index a1b940df0..82668fe25 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java @@ -21,7 +21,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index fc880344d..53b3752aa 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.util.project.noise.CNG; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java index 4e0575a6a..6b9719e15 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.data.cache.Cache; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import org.jetbrains.annotations.Nullable; @@ -112,7 +112,7 @@ public final class FloatingIslandBoundarySampler { int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); int chunkX = Math.floorDiv(x, CHUNK_SIZE); int chunkZ = Math.floorDiv(z, CHUNK_SIZE); - ParentFieldKey key = new ParentFieldKey(Cache.key(chunkX, chunkZ), width); + ParentFieldKey key = new ParentFieldKey(CacheKey.key(chunkX, chunkZ), width); return parentFields.computeIfAbsent(key, ignored -> new ParentBoundaryField(source, chunkX, chunkZ, width)); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index 518bb6fbc..f92556cd0 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -22,7 +22,7 @@ import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; 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 index 46687bc67..33b8bfad2 100644 --- a/src/main/java/art/arcane/iris/engine/object/value/IrisColor.java +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisColor.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.value; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; 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 index 4338fccef..659bec501 100644 --- 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 @@ -30,7 +30,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; 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 index 054ce6671..03ba55104 100644 --- 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 @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.world.biome; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; 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 index f7df46944..5f2cdc5ea 100644 --- 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 @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.world.biome; import art.arcane.iris.engine.object.terrain.IrisGenerator; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; 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 index 8d29d8d4f..d0d9117ea 100644 --- 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 @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.world.biome.custom; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; 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 index 64a95d57c..8abd73a04 100644 --- 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 @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.world.biome.custom; -import art.arcane.iris.engine.data.cache.AtomicCache; +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; 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 index a97edde80..327edb132 100644 --- 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 @@ -42,7 +42,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; 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 index 22f6fc0fa..e57c3b9f9 100644 --- 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 @@ -28,7 +28,7 @@ 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.iris.engine.data.cache.AtomicCache; +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; diff --git a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java index 957f84278..310c8d546 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java +++ b/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java @@ -30,7 +30,7 @@ import art.arcane.iris.builtin.terrain.WallSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisValues; import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.world.biome.IrisBiome; diff --git a/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java b/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java index 6811c89b9..d2d44d4b3 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java +++ b/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.terrain; import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.builtin.terrain.LayerBlocks; import art.arcane.iris.builtin.terrain.PaletteLayer; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.noise.CNG; diff --git a/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java index 2046a38c6..b98a20459 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java @@ -23,7 +23,7 @@ import art.arcane.iris.builtin.terrain.RockPaletteSettings; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.data.cache.AtomicCache; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.spi.PlatformBlockState; From 0d557da40fc8621d2c3413b3927aa0e5686edde5 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 15:19:53 +0200 Subject: [PATCH 065/139] builtinModulesJar fails a module that uses a VolmLib class Iris's Bukkit jar leaves out --- README.md | 4 +++- build.gradle.kts | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 928a612b6..3c3ad9e5f 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,9 @@ for further classes. The classes come from Iris core's compiled output, which th Before the jar lands in `build/libs`, `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. `check` runs 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. The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain diff --git a/build.gradle.kts b/build.gradle.kts index 1a888f0f4..daafabe83 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -70,6 +70,8 @@ val builtinModuleEntryFile = "com.volmit.IrisModule" */ val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.volmlib", "com.google.gson") val irisClasses = irisRoot.resolve("core/build/classes/java/main") +/** The VolmLib classes Iris's Bukkit jar strips; Iris's shadowJar reads the same file. A module may not use them. */ +val volmLibLeftOutFile = irisRoot.resolve("core/volmlib-left-out-of-bukkit-jar.txt") val builtinModulesBuild = layout.buildDirectory.dir("builtin-modules") val checkedJarsDirectory = layout.buildDirectory.dir("libs") @@ -131,7 +133,10 @@ val checkBuiltinModulesJar = tasks.register("checkBuiltinModulesJar") classpath = irisApiForChecks + files(irisClasses) mainClass.set("com.volmit.host.ModuleJarCheck") javaLauncher.set(javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(25)) }) - argumentProviders.add(CommandLineArgumentProvider { listOf(packaged.get().asFile.absolutePath) + exposedHostPackages }) + inputs.file(volmLibLeftOutFile) + argumentProviders.add(CommandLineArgumentProvider { + listOf(packaged.get().asFile.absolutePath, "--left-out=${volmLibLeftOutFile.absolutePath}") + exposedHostPackages + }) isIgnoreExitValue = true val problems = ByteArrayOutputStream() errorOutput = problems From d18972048cd86f1638a3475c1c146ea0041c11ab Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 18:02:53 +0200 Subject: [PATCH 066/139] Mechanical: LootResolver moves to art.arcane.iris.builtin.loot, where the loot module and the hosts that fill containers share it --- .../iris/builtin/loot/LootResolver.java | 200 ++++++++++++++++++ .../iris/engine/loot/BlockDropping.java | 2 +- .../arcane/iris/engine/loot/LootGiving.java | 2 +- .../arcane/iris/engine/loot/LootItems.java | 2 +- .../arcane/iris/engine/loot/LootTables.java | 2 +- .../iris/engine/loot/PlacementLoot.java | 2 +- .../iris/engine/spawn/EntityResolution.java | 2 +- .../iris/engine/spawn/EntitySpawning.java | 2 +- 8 files changed, 207 insertions(+), 7 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/loot/LootResolver.java diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootResolver.java b/src/main/java/art/arcane/iris/builtin/loot/LootResolver.java new file mode 100644 index 000000000..71eb99106 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/LootResolver.java @@ -0,0 +1,200 @@ +/* + * 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.builtin.loot; + +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.ToIntFunction; + +/** + * The random streams loot is drawn from and the picks made on them, shared by the loot module and the hosts that fill + * containers, so a container always holds the same loot. Changing a seed, a salt or a draw changes the loot of existing worlds. + */ +public final class LootResolver { + private static final int MAX_SCALED_SOURCE_COUNT = 256; + private static final long CONTAINER_SALT = 0x632BE59BD9B4E019L; + private static final long TABLE_SALT = 0x94D049BB133111EBL; + private static final long ENTRY_SALT = 0x9E3779B97F4A7C15L; + + private LootResolver() { + } + + public static RNG containerRng(long lootSeed, int x, int y, int z) { + return new RNG(containerSeed(lootSeed, x, y, z)); + } + + public static long containerSeed(long lootSeed, int x, int y, int z) { + long seed = mix(lootSeed ^ CONTAINER_SALT); + seed = mix(seed ^ ((long) x * 0xD6E8FEB86659FD93L)); + seed = mix(seed ^ ((long) y * 0xA5A3564E27F886A7L)); + return mix(seed ^ ((long) z * 0x8CB92BA72F3D8DD7L)); + } + + /** The random stream of one loot table at one position; {@code tableIdentity} names the table (its key, else its name). */ + public static RNG tableRng(long lootSeed, String tableIdentity, int x, int y, int z) { + return new RNG(tableSeed(lootSeed, tableIdentity, x, y, z)); + } + + public static long tableSeed(long lootSeed, String tableIdentity, int x, int y, int z) { + return mix(containerSeed(lootSeed, x, y, z) ^ stableHash(tableIdentity) ^ TABLE_SALT); + } + + public static boolean spatialOneIn( + long lootSeed, + String tableIdentity, + int entryIndex, + int x, + int y, + int z, + long rarity + ) { + if (rarity <= 1L) { + return true; + } + long roll = mix(tableSeed(lootSeed, tableIdentity, x, y, z) ^ ((long) entryIndex * ENTRY_SALT)); + return new RNG(roll).nextLong(rarity) == 0L; + } + + public static long combinedRarity(int tableRarity, int entryRarity) { + long table = Math.max(1, tableRarity); + long entry = Math.max(1, entryRarity); + if (table > Long.MAX_VALUE / entry) { + return Long.MAX_VALUE; + } + return table * entry; + } + + public static boolean oneIn(RNG rng, int rarity) { + int bound = Math.max(1, rarity); + return bound == 1 || rng.nextInt(bound) == 0; + } + + public static int inclusive(RNG rng, int first, int second) { + int lower = Math.min(first, second); + int upper = Math.max(first, second); + if (lower == upper) { + return lower; + } + long span = (long) upper - lower + 1L; + return (int) (lower + rng.nextLong(span)); + } + + public static T pickWeighted(List choices, ToIntFunction weight, RNG rng) { + long total = 0L; + for (T choice : choices) { + int value = Math.max(0, weight.applyAsInt(choice)); + total = Long.MAX_VALUE - total < value ? Long.MAX_VALUE : total + value; + } + if (total <= 0L) { + return null; + } + long pull = rng.nextLong(total); + for (T choice : choices) { + pull -= Math.max(0, weight.applyAsInt(choice)); + if (pull < 0L) { + return choice; + } + } + return null; + } + + public static void scaleSources(List sources, double multiplier, RNG rng) { + if (!Double.isFinite(multiplier) || multiplier < 0D) { + throw new IllegalArgumentException("Effective loot source multiplier must be finite and non-negative, got " + + multiplier + "."); + } + if (sources.isEmpty()) { + return; + } + if (sources.size() > MAX_SCALED_SOURCE_COUNT) { + throw new IllegalArgumentException("Loot source scaling starts above the maximum of " + + MAX_SCALED_SOURCE_COUNT + " sources: " + sources.size() + "."); + } + double scaledSize = sources.size() * multiplier; + if (!Double.isFinite(scaledSize) || scaledSize > MAX_SCALED_SOURCE_COUNT) { + throw new IllegalArgumentException("Loot source scaling exceeds the maximum of " + + MAX_SCALED_SOURCE_COUNT + " sources: " + sources.size() + " * " + multiplier + "."); + } + int target = (int) Math.round(scaledSize); + if (target == sources.size()) { + return; + } + List original = new ArrayList<>(sources); + int[] order = new int[original.size()]; + if (target < original.size()) { + shrinkSources(sources, original, order, target, rng); + return; + } + expandSources(sources, original, order, target, rng); + } + + private static void shrinkSources(List sources, List original, int[] order, int target, RNG rng) { + shuffleOrder(order, rng); + boolean[] selected = new boolean[original.size()]; + for (int index = 0; index < target; index++) { + selected[order[index]] = true; + } + sources.clear(); + for (int index = 0; index < original.size(); index++) { + if (selected[index]) { + sources.add(original.get(index)); + } + } + } + + private static void expandSources(List sources, List original, int[] order, int target, RNG rng) { + while (sources.size() < target) { + shuffleOrder(order, rng); + int additions = Math.min(target - sources.size(), original.size()); + for (int index = 0; index < additions; index++) { + sources.add(original.get(order[index])); + } + } + } + + private static void shuffleOrder(int[] order, RNG rng) { + for (int index = 0; index < order.length; index++) { + order[index] = index; + } + for (int index = 0; index < order.length - 1; index++) { + int selected = index + rng.nextInt(order.length - index); + int previous = order[index]; + order[index] = order[selected]; + order[selected] = previous; + } + } + + private static long stableHash(String value) { + long hash = 0xCBF29CE484222325L; + for (int i = 0; i < value.length(); i++) { + hash ^= value.charAt(i); + hash *= 0x100000001B3L; + } + return mix(hash); + } + + private static long mix(long value) { + long mixed = value; + mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L; + mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL; + return mixed ^ (mixed >>> 31); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index 55b501500..7dcc04598 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -24,7 +24,7 @@ import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisPlatforms; diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 1dde569ca..8b3372ecf 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.framework.PlacedObject; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.spi.IrisPlatforms; diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java index 1c2300261..3d825273f 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootItems.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -23,7 +23,7 @@ import art.arcane.iris.builtin.loot.LootEnchantment; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootSlot; import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java index c1d0cb067..5798565f4 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootTables.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -22,7 +22,7 @@ import art.arcane.iris.builtin.loot.LootMode; import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index 29db05407..09973ad96 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.object.loot.IObjectLoot; import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index f0b72ae42..f1b1f467d 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -23,7 +23,7 @@ import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.SpawnCommand; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index d55ad48ca..cccf82fd3 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -27,7 +27,7 @@ import art.arcane.iris.builtin.spawn.SpawnerSettings; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.LootResolver; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.value.IrisPosition; From 6ff5664f4ef9dfc79b304ff94cef94e1f31b0dfb Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 18:04:44 +0200 Subject: [PATCH 067/139] Mechanical: IrisApi's StructureStep is DecorationStep --- .../iris/engine/framework/structure/fit/FitStart.java | 4 ++-- .../iris/engine/framework/structure/fit/SurfaceFitting.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java index 07c9187ca..bad24142e 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java @@ -20,8 +20,8 @@ package art.arcane.iris.engine.framework.structure.fit; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.engine.framework.structure.NativeStructureFit; +import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.StructureFit; -import com.volmit.vanilla.StructureStep; import com.volmit.vanilla.TerrainAdaptation; import java.util.ArrayList; @@ -63,7 +63,7 @@ final class FitStart { return start.adaptation(); } - StructureStep step() { + DecorationStep step() { return start.step(); } diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java index baa1d1ff0..504a2cc20 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -22,7 +22,7 @@ import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import com.volmit.ModuleLog; import com.volmit.block.BlockState; -import com.volmit.vanilla.StructureStep; +import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.TemplateCells; import com.volmit.vanilla.TerrainAdaptation; import com.volmit.world.BlockPosition; @@ -114,8 +114,8 @@ final class SurfaceFitting { } } - static boolean shouldPrepareSurfaceTerrain(TerrainAdaptation adaptation, StructureStep step) { - return step == StructureStep.SURFACE_STRUCTURES + static boolean shouldPrepareSurfaceTerrain(TerrainAdaptation adaptation, DecorationStep step) { + return step == DecorationStep.SURFACE_STRUCTURES && (adaptation == TerrainAdaptation.BEARD_THIN || adaptation == TerrainAdaptation.BEARD_BOX); } From 71d0780fcb50c45749d6aee7b94d24859fce98df Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 18:16:20 +0200 Subject: [PATCH 068/139] iris:vanilla-features: importedFeatures become module settings answered through VanillaFeatures, in the built-ins jar New module iris:vanilla-features (VanillaFeaturesModule, no stages): ImportedFeaturesSettings (key importedFeatures, dimension; enabled, disabled, steps, disabledSteps as packs wrote them, steps as IrisApi DecorationStep) and the provider ImportedFeatures (generates / generatesStep / generatesFeature, same rules as IrisImportedFeatureControl). The family rule both importedFeatures and importedStructures use moves to art.arcane.iris.builtin.RegistryKeyFamily (ImportedStructures calls it). Listed in builtin-modules.txt and source-patterns.txt. Deleted: IrisImportedFeatureControl, IrisDecorationStep, NativeFeatureGenerationStatus and IrisDimension.importedFeatures. README. --- README.md | 8 +- builtin-modules.txt | 2 + source-patterns.txt | 1 + .../iris/builtin/RegistryKeyFamily.java | 57 ++++++++++ .../ImportedFeaturesSettings.java | 80 +++++++++++++ .../structure/ImportedStructures.java | 32 +----- .../vanillafeatures/ImportedFeatures.java | 67 +++++++++++ .../VanillaFeaturesModule.java | 51 +++++++++ .../object/decoration/IrisDecorationStep.java | 96 ---------------- .../IrisImportedFeatureControl.java | 107 ------------------ .../NativeFeatureGenerationStatus.java | 28 ----- .../object/world/dimension/IrisDimension.java | 3 - 12 files changed, 268 insertions(+), 264 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java create mode 100644 src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java create mode 100644 src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java diff --git a/README.md b/README.md index 3c3ad9e5f..94d9f5fed 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,11 @@ which ones its placements replace or the dimension's `importedStructures` disabl placements make, the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, PRESERVE, VACUUM, ENCASE, BORE, FORCE_CARVE, stilts) in `engine/framework/structure/fit`, written against IrisApi's `StructureFit` and `BlockAccess` only. A start carries its fit as a memo (its terrain and stilts JSON), so every -chunk it reaches and every restart fits it the same way. Object place modes are data (`PlaceMode`: height sampling, +chunk it reaches and every restart fits it the same way. `iris:vanilla-features` (`VanillaFeaturesModule`, no stages) +reads the dimension's `importedFeatures` (`ImportedFeaturesSettings`) and provides `VanillaFeatures` (`ImportedFeatures`): +whether the platform's own placed features run over the terrain and which decoration steps and features they leave out; +the family patterns of `disabled` and of `importedStructures` share one rule (`art.arcane.iris.builtin.RegistryKeyFamily`). +Object place modes are data (`PlaceMode`: height sampling, stilt, `VacuumProfile`, `PlaceTrait`s) that the placement stages ask; the pack JSON keeps the mode names. `iris:objects` also provides `SaplingGrowth` (`TreeGrowing`: the tree a sapling grows into, as placed blocks, and which objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). @@ -137,7 +141,7 @@ naming the class and what it uses. A VolmLib class that Iris's Bukkit jar strips `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. -The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and +The jar holds `iris:post`, `iris:perfection`, `iris:matter` and `iris:vanilla-features`. They are written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..b83d19049 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,5 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule +include art/arcane/iris/engine/framework/vanillafeatures/** diff --git a/source-patterns.txt b/source-patterns.txt index c42d04a72..00f98cd55 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -6,6 +6,7 @@ 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 diff --git a/src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java b/src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java new file mode 100644 index 000000000..eec55b733 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/RegistryKeyFamily.java @@ -0,0 +1,57 @@ +/* + * 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.builtin; + +import java.util.Locale; + +/** + * How the settings of Iris's built-ins name families of the platform's registry keys, such as structures and placed + * features: a pattern matches the keys equal to it and the keys it starts at a namespace, slash or underscore boundary, + * ignoring case and surrounding space. So {@code minecraft:village} matches {@code minecraft:village_plains}, + * {@code minecraft:ore} every vanilla ore, and {@code nova_structures:} a whole namespace. + */ +public final class RegistryKeyFamily { + private RegistryKeyFamily() { + } + + /** Whether the family pattern {@code pattern} matches the registry key {@code key}. */ + public static boolean matches(String pattern, String key) { + if (pattern == null || key == null) { + return false; + } + String normalizedPattern = normalize(pattern); + String normalizedKey = normalize(key); + if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { + return false; + } + if (normalizedKey.length() == normalizedPattern.length()) { + return true; + } + char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); + if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { + return true; + } + char boundary = normalizedKey.charAt(normalizedPattern.length()); + return boundary == '/' || boundary == '_'; + } + + private static String normalize(String key) { + return key.trim().toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java b/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java new file mode 100644 index 000000000..cf5bfaf2b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java @@ -0,0 +1,80 @@ +/* + * 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.builtin.vanillafeatures; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; +import com.volmit.vanilla.DecorationStep; + +import java.util.Collections; +import java.util.List; + +/** + * Whether a dimension runs the platform's own placed features over its terrain, written as + * {@code "importedFeatures": {"enabled": true, "disabledSteps": ["VEGETAL_DECORATION"]}}: the switch, and the features and + * decoration steps it leaves out. IrisApi types only. + */ +@Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation for this dimension. Placed features are ores, trees, plants, springs, geodes and every other decoration entry a biome declares. This is OFF by default: with 'enabled' false Iris generates exactly the terrain it always has and no native feature runs. With it true, every placed feature the biome's vanilla derivative declares runs over Iris terrain, in vanilla step order, on the same worldgen thread vanilla uses. Carvers are never imported - Iris has no NoiseGeneratorSettings, so there is nothing for a carver to carve against. Family matching on 'disabled' uses namespace, slash, or underscore boundaries, so 'minecraft:ore' covers every vanilla ore feature without matching unrelated names.") +@Feature(id = "iris:vanilla-features", name = "Vanilla features", key = "importedFeatures", targets = Target.DIMENSION) +public final class ImportedFeaturesSettings implements IrisFeature { + @Desc("Master switch. False (the default) means no native placed feature generates and chunk output is identical to a pack without this block at all. True runs the vanilla decoration feature pass over Iris terrain.") + private boolean enabled = false; + + @MinItems(1) + @Desc("Placed feature keys to deny explicitly, e.g. 'minecraft:ore_diamond'. A namespace:path prefix also matches, so 'minecraft:ore' denies every vanilla ore and 'minecraft:trees' denies every tree placement. Every key not matched here generates while 'enabled' is true.") + private List disabled = List.of(); + + @MinItems(1) + @Desc("Restrict feature generation to these decoration steps only. Empty (the default) means every step is eligible. Use this to import ores without importing vegetation: set it to UNDERGROUND_ORES.") + private List steps = List.of(); + + @MinItems(1) + @Desc("Decoration steps to deny. Applied after 'steps', so a step listed here never generates even if 'steps' allows it. VEGETAL_DECORATION is the usual entry for packs that grow their own trees.") + private List disabledSteps = List.of(); + + public ImportedFeaturesSettings() { + } + + /** Whether the platform's placed features run over the dimension's terrain. */ + public boolean enabled() { + return enabled; + } + + /** Family patterns of the placed features the dimension leaves out. */ + public List disabled() { + return listOrEmpty(disabled); + } + + /** The only decoration steps whose features generate; empty for every step. */ + public List steps() { + return listOrEmpty(steps); + } + + /** Decoration steps whose features never generate, whatever {@link #steps} says. */ + public List disabledSteps() { + return listOrEmpty(disabledSteps); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java index a7d215973..fd4680bfd 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.framework.structure; +import art.arcane.iris.builtin.RegistryKeyFamily; import art.arcane.iris.builtin.structure.StructureAdjustment; import art.arcane.iris.builtin.structure.StructureSetFrequency; import art.arcane.iris.builtin.structure.StructureSettings; @@ -34,7 +35,7 @@ import java.util.Optional; * What a dimension's {@link StructureSettings} say about the platform's own structures: which ones it disables, how * the starts of the others are adjusted, and how the platform sets them up. Keys match ignoring case and surrounding * space; a family pattern also matches the keys it starts at a namespace, slash or underscore boundary - * ({@link #matchesKey}). + * ({@link RegistryKeyFamily}). */ public final class ImportedStructures { private final StructureSettings settings; @@ -55,7 +56,7 @@ public final class ImportedStructures { if (normalizedKey.isEmpty()) { return false; } - return settings.disabled().stream().anyMatch(pattern -> matchesKey(pattern, key)) + return settings.disabled().stream().anyMatch(pattern -> RegistryKeyFamily.matches(pattern, key)) || settings.disabledExact().stream().map(ImportedStructures::normalize) .anyMatch(exact -> !exact.isEmpty() && exact.equals(normalizedKey)); } @@ -99,33 +100,8 @@ public final class ImportedStructures { } } - /** - * Whether the family pattern {@code pattern} matches the structure {@code key}: equal keys, or a pattern the key - * starts with that ends in, or is followed in the key by, {@code :}, {@code /} or {@code _}. So - * {@code minecraft:village} matches {@code minecraft:village_plains} and {@code nova_structures:} a whole namespace. - */ - public static boolean matchesKey(String pattern, String key) { - if (pattern == null || key == null) { - return false; - } - String normalizedPattern = normalize(pattern); - String normalizedKey = normalize(key); - if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { - return false; - } - if (normalizedKey.length() == normalizedPattern.length()) { - return true; - } - char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); - if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { - return true; - } - char boundary = normalizedKey.charAt(normalizedPattern.length()); - return boundary == '/' || boundary == '_'; - } - private static boolean matchesAny(List patterns, String key) { - return patterns.stream().anyMatch(pattern -> matchesKey(pattern, key)); + return patterns.stream().anyMatch(pattern -> RegistryKeyFamily.matches(pattern, key)); } private static NativeStructureFit asAdjustment(StructureAdjustment entry) { diff --git a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java new file mode 100644 index 000000000..0cafe0ba5 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java @@ -0,0 +1,67 @@ +/* + * 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.vanillafeatures; + +import art.arcane.iris.builtin.RegistryKeyFamily; +import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.service.VanillaFeatures; +import com.volmit.vanilla.DecorationStep; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * What a dimension's {@link ImportedFeaturesSettings} say about the platform's own placed features: whether they run, + * and which decoration steps and features they leave out. A dimension without the settings runs none. + */ +public final class ImportedFeatures implements VanillaFeatures { + private static final ImportedFeaturesSettings NONE = new ImportedFeaturesSettings(); + + @Override + public boolean generates(PackWorld world) { + return settings(world).enabled(); + } + + /** A step the API does not name is allowed unless the dimension narrowed generation to listed steps. */ + @Override + public boolean generatesStep(PackWorld world, Optional step) { + ImportedFeaturesSettings settings = settings(world); + if (step.isEmpty()) { + return settings.steps().isEmpty(); + } + if (!settings.steps().isEmpty() && !settings.steps().contains(step.get())) { + return false; + } + return !settings.disabledSteps().contains(step.get()); + } + + @Override + public boolean generatesFeature(PackWorld world, ResourceId feature) { + String key = feature.toString(); + return settings(world).disabled().stream().noneMatch(pattern -> RegistryKeyFamily.matches(pattern, key)); + } + + private static ImportedFeaturesSettings settings(PackWorld world) { + List> declared = world.settings().declared(ImportedFeaturesSettings.class); + return declared.isEmpty() ? NONE : declared.getFirst().value(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java new file mode 100644 index 000000000..035b15463 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java @@ -0,0 +1,51 @@ +/* + * 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.vanillafeatures; + +import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings; +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.service.VanillaFeatures; +import com.volmit.stage.StageGraph; + +/** + * Module {@code iris:vanilla-features}: whether the platform's own placed features (ores, trees, plants, springs) run + * over a dimension's terrain, and which steps and features they leave out, decided from the dimension's + * {@code importedFeatures} settings and answered through {@link VanillaFeatures} ({@link ImportedFeatures}). The + * platform runs the feature pass itself; the module has no stages. + */ +public final class VanillaFeaturesModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:vanilla-features", "Vanilla features", VERSION); + } + + @Override + public void install(StageGraph graph) { + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerSettings(ImportedFeaturesSettings.class); + registry.registerService(VanillaFeatures.class, new ImportedFeatures()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java deleted file mode 100644 index a2ee1d3ab..000000000 --- a/src/main/java/art/arcane/iris/engine/object/decoration/IrisDecorationStep.java +++ /dev/null @@ -1,96 +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.decoration; - -import art.arcane.iris.engine.object.annotations.Desc; - -import java.util.Locale; - -/** - * Pure-JVM mirror of Minecraft's decoration generation steps, in registry (ordinal) order. The ordinals and - * serialized names match {@code GenerationStep.Decoration} on MC 26.2 so a platform can convert either way - * without core depending on a Minecraft type. Verified against MC 26.2 GenerationStep.Decoration. - */ -@Desc("A vanilla decoration generation step. Placed features are grouped into these steps and run in this order.") -public enum IrisDecorationStep { - @Desc("Raw generation - the earliest step, before lakes.") - RAW_GENERATION("raw_generation"), - - @Desc("Lakes.") - LAKES("lakes"), - - @Desc("Local modifications such as amethyst geodes, icebergs and dripstone clusters.") - LOCAL_MODIFICATIONS("local_modifications"), - - @Desc("Underground structure features (not the structure system - features tagged as underground structures).") - UNDERGROUND_STRUCTURES("underground_structures"), - - @Desc("Surface structure features.") - SURFACE_STRUCTURES("surface_structures"), - - @Desc("Stronghold step.") - STRONGHOLDS("strongholds"), - - @Desc("Underground ores. This is the step that carries vanilla and mod ore veins.") - UNDERGROUND_ORES("underground_ores"), - - @Desc("Underground decoration such as glow lichen, sculk patches and cave vegetation.") - UNDERGROUND_DECORATION("underground_decoration"), - - @Desc("Fluid springs - the small water and lava spring features.") - FLUID_SPRINGS("fluid_springs"), - - @Desc("Vegetal decoration - trees, grass, flowers, kelp and most surface plant life.") - VEGETAL_DECORATION("vegetal_decoration"), - - @Desc("Top layer modification - freezing and snow placement.") - TOP_LAYER_MODIFICATION("top_layer_modification"); - - private final String serializedName; - - IrisDecorationStep(String serializedName) { - this.serializedName = serializedName; - } - - public String getSerializedName() { - return serializedName; - } - - /** - * Resolves a step by its vanilla ordinal. Returns null when the running Minecraft version declares more - * decoration steps than this enum knows about, which the callers treat as "unknown step, generate it". - */ - public static IrisDecorationStep byOrdinal(int ordinal) { - IrisDecorationStep[] values = values(); - return ordinal < 0 || ordinal >= values.length ? null : values[ordinal]; - } - - public static IrisDecorationStep byKey(String key) { - if (key == null || key.isBlank()) { - return null; - } - String normalized = key.trim().toLowerCase(Locale.ROOT); - for (IrisDecorationStep step : values()) { - if (step.serializedName.equals(normalized) || step.name().toLowerCase(Locale.ROOT).equals(normalized)) { - return step; - } - } - return null; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java b/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java deleted file mode 100644 index 28a572d6c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/decoration/IrisImportedFeatureControl.java +++ /dev/null @@ -1,107 +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.decoration; - -import art.arcane.iris.engine.framework.structure.ImportedStructures; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Objects; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation for this dimension (set as the dimension's 'importedFeatures' field). Placed features are ores, trees, plants, springs, geodes and every other decoration entry a biome declares. This is OFF by default: with 'enabled' false Iris generates exactly the terrain it always has and no native feature runs. With it true, every placed feature the biome's vanilla derivative declares runs over Iris terrain, in vanilla step order, on the same worldgen thread vanilla uses. Carvers are never imported - Iris has no NoiseGeneratorSettings, so there is nothing for a carver to carve against. Family matching on 'disabled' uses namespace, slash, or underscore boundaries, so 'minecraft:ore' covers every vanilla ore feature without matching unrelated names.") -@Data -public class IrisImportedFeatureControl { - @Desc("Master switch. False (the default) means no native placed feature generates and chunk output is identical to a pack without this block at all. True runs the vanilla decoration feature pass over Iris terrain.") - private boolean enabled = false; - - @ArrayType(type = String.class, min = 1) - @Desc("Placed feature keys to deny explicitly, e.g. 'minecraft:ore_diamond'. A namespace:path prefix also matches, so 'minecraft:ore' denies every vanilla ore and 'minecraft:trees' denies every tree placement. Every key not matched here generates while 'enabled' is true.") - private KList disabled = new KList<>(); - - @ArrayType(type = IrisDecorationStep.class, min = 1) - @Desc("Restrict feature generation to these decoration steps only. Empty (the default) means every step is eligible. Use this to import ores without importing vegetation: set it to UNDERGROUND_ORES.") - private KList steps = new KList<>(); - - @ArrayType(type = IrisDecorationStep.class, min = 1) - @Desc("Decoration steps to deny. Applied after 'steps', so a step listed here never generates even if 'steps' allows it. VEGETAL_DECORATION is the usual entry for packs that grow their own trees.") - private KList disabledSteps = new KList<>(); - - /** - * True when this dimension wants the native feature pass at all. Every other accessor on this class is - * meaningless while this is false, and the platform must not build any feature machinery. - */ - public boolean shouldGenerateFeatures() { - return enabled; - } - - public boolean shouldGenerateStep(IrisDecorationStep step) { - if (!enabled) { - return false; - } - KList allowed = Objects.requireNonNull( - steps, "importedFeatures.steps must not be null"); - KList denied = Objects.requireNonNull( - disabledSteps, "importedFeatures.disabledSteps must not be null"); - if (step == null) { - // A step this Iris build does not know about (newer Minecraft): allow it unless the pack - // narrowed generation to an explicit step list. - return allowed.isEmpty(); - } - if (!allowed.isEmpty() && !allowed.contains(step)) { - return false; - } - return !denied.contains(step); - } - - public boolean shouldGenerate(String placedFeatureKey) { - return resolve(placedFeatureKey, null) == NativeFeatureGenerationStatus.GENERATE_NATIVE; - } - - /** - * Resolves one placed feature against this control. A null step skips the step gate, which is what the - * key-only query does. - */ - public NativeFeatureGenerationStatus resolve(String placedFeatureKey, IrisDecorationStep step) { - if (!enabled) { - return NativeFeatureGenerationStatus.FEATURES_DISABLED; - } - if (placedFeatureKey == null || placedFeatureKey.isBlank()) { - return NativeFeatureGenerationStatus.INVALID_REGISTRY_KEY; - } - if (step != null && !shouldGenerateStep(step)) { - return NativeFeatureGenerationStatus.STEP_DISABLED; - } - KList deniedKeys = Objects.requireNonNull( - disabled, "importedFeatures.disabled must not be null"); - for (String entry : deniedKeys) { - if (ImportedStructures.matchesKey(entry, placedFeatureKey)) { - return NativeFeatureGenerationStatus.DISABLED_BY_PACK; - } - } - return NativeFeatureGenerationStatus.GENERATE_NATIVE; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java b/src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java deleted file mode 100644 index 8c828b99d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/decoration/NativeFeatureGenerationStatus.java +++ /dev/null @@ -1,28 +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.decoration; - -public enum NativeFeatureGenerationStatus { - GENERATE_NATIVE, - FEATURES_DISABLED, - STEP_DISABLED, - DISABLED_BY_PACK, - CYCLE_DEGRADED, - INVALID_REGISTRY_KEY -} 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 index 327edb132..05269765d 100644 --- 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 @@ -18,7 +18,6 @@ package art.arcane.iris.engine.object.world.dimension; -import art.arcane.iris.engine.object.decoration.IrisImportedFeatureControl; import art.arcane.iris.engine.object.image.IrisImageMap; import art.arcane.iris.engine.object.image.IrisImageMapApplication; import art.arcane.iris.engine.object.image.IrisImageMapBinding; @@ -240,8 +239,6 @@ public class IrisDimension extends IrisRegistrant { @Desc("Dimension-wide Iris structure placements, independent of biome/region placements") @ArrayType(type = IrisStructurePlacement.class, min = 1) private KList structures = new KList<>(); - @Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation (ores, trees, plants, springs, geodes) for this dimension. Disabled by default: leaving this out generates exactly the terrain Iris always has. Set 'enabled' true to run the vanilla decoration feature pass over Iris terrain. Carvers are never imported.") - private IrisImportedFeatureControl importedFeatures = new IrisImportedFeatureControl(); @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<>(); From 4f852f9c47b48735a72352592785de69d8389cb1 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 18:21:31 +0200 Subject: [PATCH 069/139] ObjectLoot, ObjectVanillaLoot and PlacementMarker: the loot and marker lists of an object placement as module-owned types of IrisApi annotations and BlockSpec --- .../arcane/iris/builtin/loot/ObjectLoot.java | 76 +++++++++++++++++ .../iris/builtin/loot/ObjectLootEntry.java | 41 +++++++++ .../iris/builtin/loot/ObjectVanillaLoot.java | 71 ++++++++++++++++ .../iris/builtin/spawn/PlacementMarker.java | 72 ++++++++++++++++ .../iris/engine/object/loot/IObjectLoot.java | 14 ---- .../engine/object/loot/IrisObjectLoot.java | 83 ------------------- .../object/loot/IrisObjectVanillaLoot.java | 57 ------------- .../object/marker/IrisObjectMarker.java | 78 ----------------- .../engine/object/placement/BlocksModule.java | 29 +++++-- .../object/placement/IrisObjectPlacement.java | 18 ++-- .../object/structure/IrisStructure.java | 4 +- 11 files changed, 291 insertions(+), 252 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java create mode 100644 src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java create mode 100644 src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java new file mode 100644 index 000000000..95ca8dae0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -0,0 +1,76 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("object-loot") +@Desc("Represents loot within this object") +public final class ObjectLoot implements ObjectLootEntry { + @MinItems(1) + @Desc("The list of blocks this loot table should apply to") + private List filter = List.of(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The loot table name") + @Required + @ResourceRef(LootTable.class) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public ObjectLoot() { + } + + /** A table for every container of the placement. */ + public ObjectLoot(String name, int weight) { + this.name = name; + this.weight = weight; + } + + @Override + public String name() { + return name; + } + + @Override + public int weight() { + return weight; + } + + @Override + public boolean exact() { + return exact; + } + + @Override + public List filter() { + return filter == null ? List.of() : Collections.unmodifiableList(filter); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java new file mode 100644 index 000000000..92a2a5d77 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java @@ -0,0 +1,41 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; + +import java.util.List; + +/** + * One loot table an object placement gives its containers: which table, how often it is picked among the placement's + * tables, and which of the object's containers it is for. + */ +public interface ObjectLootEntry { + /** The table: a key of the pack's loot tables, or a key of the platform's. */ + String name(); + + /** How often the table is picked among equals; a table with no weight is never picked. */ + int weight(); + + /** Whether the table applies to the exact state of the blocks in {@link #filter}, not to every state of their kind of block. */ + boolean exact(); + + /** The blocks the table is for; none means every container the placement holds. */ + List filter(); +} diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java new file mode 100644 index 000000000..45351c4d1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java @@ -0,0 +1,71 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("object-vanilla-loot") +@Desc("Represents vanilla loot within this object") +public final class ObjectVanillaLoot implements ObjectLootEntry { + @MinItems(1) + @Desc("The list of blocks this loot table should apply to") + private List filter = List.of(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The vanilla loot table key") + @Required + @Ref(Reference.LOOT_TABLE) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public ObjectVanillaLoot() { + } + + @Override + public String name() { + return name; + } + + @Override + public int weight() { + return weight; + } + + @Override + public boolean exact() { + return exact; + } + + @Override + public List filter() { + return filter == null ? List.of() : Collections.unmodifiableList(filter); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java new file mode 100644 index 000000000..435cc4af5 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -0,0 +1,72 @@ +/* + * 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.builtin.spawn; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** Blocks of an object placement that get a {@link SpawnMarker}, an entry of the placement's {@code markers}. */ +@Snippet("object-marker") +@Desc("Find blocks to mark") +public final class PlacementMarker { + @MinItems(1) + @Required + @Desc("Find block types to mark") + private List mark = List.of(); + @MinNumber(1) + @MaxNumber(16) + @Desc("The maximum amount of markers to place. Use these sparingly!") + private int maximumMarkers = 8; + @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") + private boolean exact = false; + @Required + @ResourceRef(SpawnMarker.class) + @Desc("The marker to add") + private String marker; + + public PlacementMarker() { + } + + /** The blocks that get a marker. */ + public List mark() { + return mark == null ? List.of() : Collections.unmodifiableList(mark); + } + + public int maximumMarkers() { + return maximumMarkers; + } + + public boolean exact() { + return exact; + } + + /** The key of the {@link SpawnMarker} to place. */ + public String marker() { + return marker; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java deleted file mode 100644 index 07d0f6859..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IObjectLoot.java +++ /dev/null @@ -1,14 +0,0 @@ -package art.arcane.iris.engine.object.loot; - -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; - -public interface IObjectLoot { - KList getFilter(); - KList getFilter(IrisData manager); - boolean isExact(); - String getName(); - int getWeight(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java deleted file mode 100644 index ce6ff7c59..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectLoot.java +++ /dev/null @@ -1,83 +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.loot; - -import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.core.loader.IrisData; -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.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.B; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Snippet("object-loot") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents loot within this object") -@Data -public class IrisObjectLoot implements IObjectLoot { - private final transient AtomicCache> filterCache = new AtomicCache<>(); - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The list of blocks this loot table should apply to") - private KList filter = new KList<>(); - @Desc("Exactly match the block data or not") - private boolean exact = false; - @Desc("The loot table name") - @Required - @RegistryListResource(LootTable.class) - private String name; - @Desc("The weight of this loot table being chosen") - @MinNumber(1) - private int weight = 1; - - public KList getFilter(IrisData rdata) { - return filterCache.aquire(() -> - { - KList b = new KList<>(); - - for (IrisBlockData i : filter) { - PlatformBlockState bx = i.getBlockData(rdata); - - if (bx != null) { - b.add(bx); - } - } - - return b; - }); - } - - public boolean matchesFilter(IrisData manager, PlatformBlockState data) { - for (PlatformBlockState filterState : getFilter(manager)) { - if (B.matches(filterState, data)) return true; - } - return false; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java b/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java deleted file mode 100644 index 4ad466e2f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/loot/IrisObjectVanillaLoot.java +++ /dev/null @@ -1,57 +0,0 @@ -package art.arcane.iris.engine.object.loot; - -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.core.loader.IrisData; -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.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListFunction; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.annotations.functions.LootTableKeyFunction; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Snippet("object-vanilla-loot") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents vanilla loot within this object") -@Data -public class IrisObjectVanillaLoot implements IObjectLoot { - private final transient AtomicCache> filterCache = new AtomicCache<>(); - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The list of blocks this loot table should apply to") - private KList filter = new KList<>(); - @Desc("Exactly match the block data or not") - private boolean exact = false; - @Desc("The vanilla loot table key") - @Required - @RegistryListFunction(LootTableKeyFunction.class) - private String name; - @Desc("The weight of this loot table being chosen") - @MinNumber(1) - private int weight = 1; - - public KList getFilter(IrisData rdata) { - return filterCache.aquire(() -> - { - KList b = new KList<>(); - - for (IrisBlockData i : filter) { - PlatformBlockState bx = i.getBlockData(rdata); - - if (bx != null) { - b.add(bx); - } - } - - return b; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java b/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java deleted file mode 100644 index 4c3ffe0bb..000000000 --- a/src/main/java/art/arcane/iris/engine/object/marker/IrisObjectMarker.java +++ /dev/null @@ -1,78 +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.marker; - -import art.arcane.iris.builtin.spawn.SpawnMarker; -import art.arcane.iris.engine.object.material.IrisBlockData; -import art.arcane.iris.core.loader.IrisData; -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.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import art.arcane.iris.spi.PlatformBlockState; -import lombok.experimental.Accessors; - -@Snippet("object-marker") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Find blocks to mark") -@Data -public class IrisObjectMarker { - private final transient AtomicCache> findData = new AtomicCache<>(); - @ArrayType(min = 1, type = IrisBlockData.class) - @Required - @Desc("Find block types to mark") - private KList mark = new KList<>(); - @MinNumber(1) - @MaxNumber(16) - @Desc("The maximum amount of markers to place. Use these sparingly!") - private int maximumMarkers = 8; - @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") - private boolean exact = false; - @Required - @RegistryListResource(SpawnMarker.class) - @Desc("The marker to add") - private String marker; - - public KList getMark(IrisData rdata) { - return findData.aquire(() -> - { - KList b = new KList<>(); - - for (IrisBlockData i : mark) { - PlatformBlockState bx = i.getBlockData(rdata); - - if (bx != null) { - b.add(bx); - } - } - - return b; - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index d04debcb6..437bb3b55 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -28,8 +28,8 @@ import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.core.modules.BlockEntities; import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.builtin.spawn.PlacementMarker; import art.arcane.iris.builtin.spawn.SpawnMarker; -import art.arcane.iris.engine.object.marker.IrisObjectMarker; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectShaping; import art.arcane.iris.engine.object.prefab.TileData; @@ -39,6 +39,8 @@ import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; import com.volmit.ModuleInfo; import com.volmit.object.ObjectBlock; import com.volmit.placement.PlacedBlock; @@ -204,27 +206,36 @@ public final class BlocksModule implements IrisModule { PlacementWorld world = new PlacementWorld(context.access(), placement.states()); RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; - for (IrisObjectMarker markerConfig : config.getMarkers()) { - SpawnMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker()); + for (PlacementMarker markerConfig : config.getMarkers()) { + SpawnMarker marker = SpawnResources.marker(placement.data().getPackResources(), markerConfig.marker()); int markerSalt = salt++; if (marker == null) { continue; } - KList candidates = candidates(written, markerConfig, markerConfig.getMark(placement.data()), placement); - int remaining = markerConfig.getMaximumMarkers(); + KList candidates = candidates(written, markerConfig, markTargets(markerConfig, placement), placement); + int remaining = markerConfig.maximumMarkers(); for (BlockPosition position : candidates.shuffleCopy(markerRandom.nextParallelRNG(markerSalt))) { if (remaining <= 0) { break; } if (!marker.emptyAbove() || hasAirAbove(world, position)) { - context.access().marker(ObjectMarkers.of(position, markerConfig.getMarker())); + context.access().marker(ObjectMarkers.of(position, markerConfig.marker())); remaining--; } } } } - private static KList candidates(WrittenBlocks written, IrisObjectMarker markerConfig, + private static KList markTargets(PlacementMarker markerConfig, IrisPlacement placement) { + KList targets = new KList<>(); + for (BlockSpec spec : markerConfig.mark()) { + BlockState state = placement.data().getPackResources().blocks().resolve(spec); + targets.add(placement.states().toPlatform(state)); + } + return targets; + } + + private static KList candidates(WrittenBlocks written, PlacementMarker markerConfig, KList targets, IrisPlacement placement) { KList candidates = new KList<>(); for (PlacedBlock block : written.blocks()) { @@ -236,8 +247,8 @@ public final class BlocksModule implements IrisModule { return candidates; } - private static boolean marks(IrisObjectMarker markerConfig, PlatformBlockState target, PlatformBlockState state) { - return markerConfig.isExact() + private static boolean marks(PlacementMarker markerConfig, PlatformBlockState target, PlatformBlockState state) { + return markerConfig.exact() ? target.matches(state) : IrisObjectShaping.materialKey(target).equals(IrisObjectShaping.materialKey(state)); } 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 index 2a7c4583c..7af65552d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -27,9 +27,9 @@ 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.engine.object.loot.IrisObjectLoot; -import art.arcane.iris.engine.object.loot.IrisObjectVanillaLoot; -import art.arcane.iris.engine.object.marker.IrisObjectMarker; +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; @@ -117,9 +117,9 @@ public class IrisObjectPlacement { @MinNumber(0) @Desc("When bore is enabled, expand max-y of the cuboid it removes") private int boreExtendMaxY = 0; - @ArrayType(min = 1, type = IrisObjectMarker.class) + @ArrayType(min = 1, type = PlacementMarker.class) @Desc("Add markers to blocks in this object") - private KList markers = new KList<>(); + private KList markers = new KList<>(); @MaxNumber(64) @MinNumber(-1) @Desc("When bore is enabled, lower min-y of the cuboid it removes") @@ -167,12 +167,12 @@ public class IrisObjectPlacement { private IrisObjectTranslate translate = new IrisObjectTranslate(); @Desc("Scale Objects") private IrisObjectScale scale = new IrisObjectScale(); - @ArrayType(min = 1, type = IrisObjectLoot.class) + @ArrayType(min = 1, type = ObjectLoot.class) @Desc("The loot tables to apply to these objects") - private KList loot = new KList<>(); - @ArrayType(min = 1, type = IrisObjectVanillaLoot.class) + 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<>(); + 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...") 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 index 77865a878..9c14ab28b 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -22,7 +22,7 @@ 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.engine.object.loot.IrisObjectLoot; +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; @@ -138,7 +138,7 @@ public class IrisStructure extends IrisRegistrant { } for (String lootTable : loot) { if (lootTable != null && !lootTable.isBlank()) { - placement.getLoot().add(new IrisObjectLoot().setName(lootTable).setWeight(1)); + placement.getLoot().add(new ObjectLoot(lootTable, 1)); } } return placement; From 347c69b0a2d3697f130b639ed76e2111a83a7e1b Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 18:21:31 +0200 Subject: [PATCH 070/139] LiveWorld and SpawnCooldowns: what the loot and spawn services ask a running world, as values; the saved cooldowns no longer read spawner files --- .../art/arcane/iris/builtin/LiveWorld.java | 136 ++++++++++++++++++ .../art/arcane/iris/builtin/package-info.java | 2 +- .../iris/builtin/spawn/SpawnCooldowns.java | 47 ++++++ .../entity/spawn/IrisSpawnerCooldowns.java | 12 +- .../engine/object/runtime/IrisEngineData.java | 10 +- 5 files changed, 196 insertions(+), 11 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/LiveWorld.java create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java diff --git a/src/main/java/art/arcane/iris/builtin/LiveWorld.java b/src/main/java/art/arcane/iris/builtin/LiveWorld.java new file mode 100644 index 000000000..d52bc1d0f --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/LiveWorld.java @@ -0,0 +1,136 @@ +/* + * 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.builtin; + +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; +import art.arcane.iris.builtin.spawn.SpawnCooldowns; +import com.volmit.IrisFeature; +import com.volmit.resource.ResourceId; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * What Iris's own services ask a world that is running, outside any chunk stage: the layout and the objects at a block + * as they are now, the platform's weather and loot tables, and the data Iris keeps with the world. A chunk stage reads + * the layout through its {@link com.volmit.world.TerrainSampler}; a service has no chunk, so it asks here. + * + *

X and Z are world coordinates; Y is the height above the dimension's bottom, as everywhere in IrisApi. + * Safe to use from any thread. Reached through {@link #of(PackWorld)}. + */ +public interface LiveWorld { + /** The live view of {@code world}, which must be a world Iris generates. */ + static LiveWorld of(PackWorld world) { + if (world instanceof Source source) { + return source.liveWorld(); + } + throw new IllegalArgumentException("Built-in modules work in worlds Iris generates, not " + world); + } + + /** Iris's worlds answer for their live view. */ + interface Source { + LiveWorld liveWorld(); + } + + /** The platform's block Y of height 0, the dimension's bottom: a position's height plus this is its Y in the platform. */ + int bottomY(); + + /** The pack biome at the column's surface. */ + ResourceId surfaceBiome(int x, int z); + + /** The pack biome at the block when it lies in a cave biome, else the surface biome. */ + ResourceId caveBiome(int x, int y, int z); + + /** What the surface biome of the column is for: land, sea, shore or cave. */ + BiomeKind surfaceKind(int x, int z); + + /** The terrain's height at the column, before anything was placed on it. */ + double terrainHeight(int x, int z); + + /** The height of the highest block placed in the column, with the terrain and what objects and structures added. */ + int highestBlock(int x, int z, boolean ignoreFluid); + + /** + * The settings of {@code type} that the dimension, the region or a biome declares for the block, as they are + * decoded for generation; empty when that level declares none. + */ + Optional settings(Class type, Level level, int x, int y, int z); + + /** The time and weather of the world, or empty when the world has no platform world yet. */ + Optional sky(); + + /** Whether the world is a studio world. */ + boolean studio(); + + /** The keys of the loot tables the platform has, such as {@code minecraft:chests/simple_dungeon}. They do not change while the world runs. */ + Set platformLootTables(); + + /** The floors of the caves marked in the chunk, none on a platform that cannot read them. */ + List caveFloors(int chunkX, int chunkZ); + + /** The loot the object placed at the block defines, or empty when no object placement covers the block. */ + Optional objectLoots(int x, int y, int z); + + /** The cooldowns of the world's spawners. */ + SpawnCooldowns spawnCooldowns(); + + /** Where the layout is asked: the dimension, the region of the column, or one of its biomes. */ + enum Level { + DIMENSION, + REGION, + /** The biome at the column's surface. */ + SURFACE_BIOME, + /** The biome at the block: a cave biome below the surface, the surface biome above. */ + BIOME, + /** The cave biome at the block, the surface biome when it has none. */ + CAVE_BIOME + } + + /** What a biome is for, which decides the spawners that fit it. */ + enum BiomeKind { + LAND, SEA, SHORE, CAVE + } + + /** The world's time of day in ticks, whether it is storming and whether it thunders. */ + record Sky(long time, boolean storming, boolean thundering) { + } + + /** + * The loot an object placement gives its containers. + * + * @param packTables tables of the pack + * @param platformTables tables of the platform + * @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes + */ + record ObjectLoots(List packTables, List platformTables, boolean overridesGlobalLoot) { + public ObjectLoots { + packTables = List.copyOf(packTables); + platformTables = List.copyOf(platformTables); + } + + /** Whether the placement names any table. */ + public boolean defined() { + return !packTables.isEmpty() || !platformTables.isEmpty(); + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 4e62e77b1..d05b405cd 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -29,7 +29,7 @@ *

* Besides those, it holds what the compiled-in built-ins and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.IrisSeed}), and per-world state several of them use + * ({@link art.arcane.iris.builtin.IrisSeed}, {@link art.arcane.iris.builtin.LiveWorld}), and per-world state several of them use * ({@link art.arcane.iris.builtin.terrain.LayerBlocks}). Keep them few: each is a promise. *

* Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java new file mode 100644 index 000000000..ca17005ee --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.spawn; + +import java.util.function.ToLongFunction; + +/** + * When spawners last fired, which Iris keeps with the world's data so that a spawner's rates hold across restarts. Rates + * count per spawner, by the key the pack names it by, in the world and in each chunk. Reached through + * {@link art.arcane.iris.builtin.LiveWorld#spawnCooldowns()}. + */ +public interface SpawnCooldowns { + /** Whether the spawner may fire in the world again, {@code intervalMilliseconds} after it last did. */ + boolean canSpawn(String spawner, long intervalMilliseconds); + + /** Notes that the spawner fired in the world now. */ + void spawned(String spawner); + + /** Whether the spawner may fire in the chunk again, {@code intervalMilliseconds} after it last did there. */ + boolean canSpawnInChunk(int chunkX, int chunkZ, String spawner, long intervalMilliseconds); + + /** Notes that the spawner fired in the chunk now. */ + void spawnedInChunk(int chunkX, int chunkZ, String spawner); + + /** + * Forgets the cooldowns that ran out and those of spawners the pack no longer has, so the world's data does not grow. + * + * @param intervalMilliseconds the interval of the world rate of a spawner by its key, or a negative number for a spawner the pack lacks + */ + void forgetExpired(ToLongFunction intervalMilliseconds); +} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java index 7b12a24b6..1f0965cec 100644 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java +++ b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java @@ -1,12 +1,11 @@ package art.arcane.iris.engine.object.entity.spawn; -import art.arcane.iris.builtin.spawn.Spawner; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; import lombok.EqualsAndHashCode; import lombok.NonNull; +import java.util.function.ToLongFunction; + @EqualsAndHashCode public class IrisSpawnerCooldowns { private final KMap cooldowns = new KMap<>(); @@ -19,10 +18,11 @@ public class IrisSpawnerCooldowns { }); } - public void cleanup(Engine engine) { + /** Forgets the cooldowns that ran out and those of spawners {@code intervalMilliseconds} does not know (a negative interval). */ + public void cleanup(ToLongFunction intervalMilliseconds) { cooldowns.values().removeIf(cd -> { - Spawner spawner = SpawnResources.spawner(engine.getData(), cd.getSpawner()); - return spawner == null || cd.canSpawn(spawner.maximumRate().interval()); + long interval = intervalMilliseconds.applyAsLong(cd.getSpawner()); + return interval < 0 || cd.canSpawn(interval); }); } diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java index 0fa145932..2db085788 100644 --- a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java +++ b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java @@ -20,11 +20,12 @@ package art.arcane.iris.engine.object.runtime; import art.arcane.iris.engine.object.entity.spawn.IrisSpawnerCooldowns; import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.framework.Engine; import art.arcane.volmlib.util.collection.KMap; import lombok.Data; import lombok.EqualsAndHashCode; +import java.util.function.ToLongFunction; + @Data @EqualsAndHashCode(callSuper = true) public class IrisEngineData extends IrisSpawnerCooldowns { @@ -40,11 +41,12 @@ public class IrisEngineData extends IrisSpawnerCooldowns { return chunks.computeIfAbsent(CacheKey.key(x, z), k -> new IrisSpawnerCooldowns()); } - public void cleanup(Engine engine) { - super.cleanup(engine); + @Override + public void cleanup(ToLongFunction intervalMilliseconds) { + super.cleanup(intervalMilliseconds); chunks.values().removeIf(chunk -> { - chunk.cleanup(engine); + chunk.cleanup(intervalMilliseconds); return chunk.isEmpty(); }); } From 48ff0908e28953c65355bd77ad49e69f59689594 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 10 Oct 2026 18:21:31 +0200 Subject: [PATCH 071/139] iris:loot and iris:spawn onto the module surface and into iris-builtins.jar: no engine, IrisData, IrisPlatforms or Bukkit types; the validator checks the decoded tables and references --- README.md | 15 +- builtin-modules.txt | 4 + .../iris/engine/loot/BlockDropping.java | 25 +- .../arcane/iris/engine/loot/LootGiving.java | 75 ++-- .../arcane/iris/engine/loot/LootModule.java | 4 + .../iris/engine/loot/LootResources.java | 10 +- .../arcane/iris/engine/loot/LootTables.java | 65 ++-- .../iris/engine/loot/LootValidator.java | 323 +++++++----------- .../iris/engine/loot/PlacementLoot.java | 50 ++- .../iris/engine/loot/ResolvedBlockDrop.java | 7 +- .../iris/engine/object/value/IRare.java | 18 - .../iris/engine/spawn/AmbientEffecting.java | 32 +- .../iris/engine/spawn/EntityResolution.java | 13 +- .../iris/engine/spawn/EntitySpawning.java | 159 ++++----- .../iris/engine/spawn/RarityWeighting.java | 53 +++ .../iris/engine/spawn/SpawnConditions.java | 12 +- .../arcane/iris/engine/spawn/SpawnModule.java | 2 + .../iris/engine/spawn/SpawnResources.java | 38 +-- .../arcane/iris/engine/spawn/SpawnerGate.java | 50 +-- 19 files changed, 445 insertions(+), 510 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java diff --git a/README.md b/README.md index 3c3ad9e5f..01abf7153 100644 --- a/README.md +++ b/README.md @@ -137,10 +137,12 @@ naming the class and what it uses. A VolmLib class that Iris's Bukkit jar strips `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. -The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and +The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot` and `iris:spawn`. They are written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain -sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. -Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting +sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks; +the loot and spawn services, which have no chunk to ask, ask `LiveWorld` (below). Without the jar a pack's world has no +loot, block drops, entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and `effects` are +not read. Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting `iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, `iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to @@ -149,5 +151,10 @@ when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, wh `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the same) and `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same -layers, and a layer's noise is built once per world by whichever asks first). `iris:post` reads its switches +layers, and a layer's noise is built once per world by whichever asks first), `LiveWorld` (what the loot and spawn services ask a +running world, outside any chunk stage: the layout and settings at a block, the platform's weather and loot tables, the +objects' loot and the spawner cooldowns Iris saves with the world; values only, implemented by Iris's worlds like `IrisSeed`), +`loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and +marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`, which the modules +register as held types, because Iris's `IrisObjectPlacement` holds them). `iris:post` reads its switches (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. \ No newline at end of file diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..d72e0bd5a 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,7 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.loot.LootModule +include art/arcane/iris/engine/loot/** +module art.arcane.iris.engine.spawn.SpawnModule +include art/arcane/iris/engine/spawn/** diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index 7dcc04598..d0c477bde 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -18,16 +18,12 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.LiveWorld; +import art.arcane.iris.builtin.LiveWorld.Level; import art.arcane.iris.builtin.loot.BlockDrop; import art.arcane.iris.builtin.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootEntry; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.builtin.loot.LootResolver; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.spi.IrisPlatforms; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; import com.volmit.service.BlockDrops; @@ -45,19 +41,17 @@ import java.util.concurrent.ConcurrentMap; public final class BlockDropping implements BlockDrops { @Override public Result drops(PackWorld world, Broken broken) { - Engine engine = IrisPackWorld.of(world).engine(); + LiveWorld live = LiveWorld.of(world); int x = broken.position().x(); int y = broken.position().y(); int z = broken.position().z(); - String brokenKey = IrisPlatforms.get().registries().block(broken.block().key()).key(); + String brokenKey = world.resources().blocks().resolve(broken.block()).key(); ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops()); - IrisBiome biome = engine.getBiome(x, y, z); - List providers = dropsFor(biome, brokenKey, resolved, world); + List providers = dropsFor(live, Level.BIOME, x, y, z, brokenKey, resolved, world); if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) { - IrisRegion region = engine.getRegion(x, z); - providers.addAll(dropsFor(region, brokenKey, resolved, world)); - providers.addAll(dropsFor(engine.getDimension(), brokenKey, resolved, world)); + providers.addAll(dropsFor(live, Level.REGION, x, y, z, brokenKey, resolved, world)); + providers.addAll(dropsFor(live, Level.DIMENSION, x, y, z, brokenKey, resolved, world)); } LootItems items = new LootItems(world.resources().items(), false); @@ -79,9 +73,10 @@ public final class BlockDropping implements BlockDrops { } } - private static List dropsFor(IrisRegistrant owner, String brokenKey, ResolvedDrops resolved, PackWorld world) { + private static List dropsFor(LiveWorld live, Level level, int x, int y, int z, String brokenKey, + ResolvedDrops resolved, PackWorld world) { List matching = new ArrayList<>(); - for (BlockDrop drop : owner.getModuleSettings().find(BlockDropSettings.class).map(BlockDropSettings::drops).orElse(List.of())) { + for (BlockDrop drop : live.settings(BlockDropSettings.class, level, x, y, z).map(BlockDropSettings::drops).orElse(List.of())) { ResolvedBlockDrop candidate = resolved.of(drop, world); if (candidate.dropsFor(brokenKey)) { matching.add(candidate); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 8b3372ecf..3f245d70a 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -18,14 +18,11 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.LiveWorld; +import art.arcane.iris.builtin.LiveWorld.ObjectLoots; import art.arcane.iris.builtin.loot.LootResolver; -import art.arcane.iris.engine.framework.PlacedObject; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.builtin.loot.LootTable; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; import com.volmit.service.Loot; @@ -33,7 +30,7 @@ import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.List; -import java.util.Set; +import java.util.Optional; /** * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the @@ -43,76 +40,48 @@ import java.util.Set; public final class LootGiving implements Loot { @Override public List tables(PackWorld world, Site site) { - Engine engine = engine(world); + LiveWorld live = LiveWorld.of(world); int x = site.position().x(); int z = site.position().z(); int relativeY = site.position().y(); - int worldY = relativeY + engine.getMinHeight(); - RNG rng = LootResolver.containerRng(lootSeed(engine), x, worldY, z); + int worldY = relativeY + live.bottomY(); + RNG rng = LootResolver.containerRng(lootSeed(world), x, worldY, z); List sources = new ArrayList<>(); boolean objectLootDefined = site.nativeLootDefined(); - IrisObjectPlacement placement = site.container() == null ? null : placementAt(engine, x, relativeY, z); - if (placement != null) { - objectLootDefined = objectLootDefined || placement.getLoot().isNotEmpty() || placement.getVanillaLoot().isNotEmpty(); - Source picked = placementLoot(world, engine).pick(placement.getVanillaLoot(), placement.getLoot(), platformState(site), rng, x, worldY, z); + Optional objectLoots = site.container() == null ? Optional.empty() : live.objectLoots(x, relativeY, z); + if (objectLoots.isPresent()) { + objectLootDefined = objectLootDefined || objectLoots.get().defined(); + Source picked = placementLoot(world, live).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(), + site.container(), rng, x, worldY, z); if (picked != null) { sources.add(picked); - if (placement.isOverrideGlobalLoot()) { + if (objectLoots.get().overridesGlobalLoot()) { return sources; } } } - LootTables.resolveEnvironmentSources(sources, engine, rng, x, relativeY, z, objectLootDefined, Table::new); + LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined, Table::new); return sources; } @Override public List items(PackWorld world, Site site, String key) { - Engine engine = engine(world); - LootTable table = LootResources.table(engine.getData(), key); + LootTable table = LootResources.table(world.resources(), key); if (table == null) { return List.of(); } - int worldY = site.position().y() + engine.getMinHeight(); + int worldY = site.position().y() + LiveWorld.of(world).bottomY(); return new LootItems(world.resources().items(), site.debug()) - .draw(key, table, lootSeed(engine), site.position().x(), worldY, site.position().z()); + .draw(key, table, lootSeed(world), site.position().x(), worldY, site.position().z()); } - private static PlacementLoot placementLoot(PackWorld world, Engine engine) { - PlatformLootTables platformTables = world.state(PlatformLootTables.class, ignored -> new PlatformLootTables()); - return new PlacementLoot(engine.getData(), platformTables::keys, lootSeed(engine), world.log()); + private static PlacementLoot placementLoot(PackWorld world, LiveWorld live) { + return new PlacementLoot(world.resources(), live::platformLootTables, lootSeed(world), world.log()); } - private static IrisObjectPlacement placementAt(Engine engine, int x, int relativeY, int z) { - PlacedObject placed = engine.getObjectPlacement(x, relativeY, z); - return placed == null ? null : placed.getPlacement(); - } - - private static PlatformBlockState platformState(Site site) { - return IrisPlatforms.get().registries().block(site.container().key()); - } - - private static long lootSeed(Engine engine) { - return engine.getSeedManager().getLoot(); - } - - private static Engine engine(PackWorld world) { - return IrisPackWorld.of(world).engine(); - } - - /** The loot table keys of the platform, which do not change while a world runs. */ - private static final class PlatformLootTables { - private volatile Set keys; - - private Set keys() { - Set known = keys; - if (known == null) { - known = PlacementLoot.platformTableKeys(); - keys = known; - } - return known; - } + private static long lootSeed(PackWorld world) { + return IrisSeed.LOOT.of(world); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index aa2041db9..d3e2696e3 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -20,6 +20,8 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootSettings; +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -49,6 +51,8 @@ public final class LootModule implements IrisModule { public void register(FeatureRegistry registry) { registry.registerSettings(LootSettings.class); registry.registerSettings(BlockDropSettings.class); + registry.registerHeldType(ObjectLoot.class); + registry.registerHeldType(ObjectVanillaLoot.class); LootResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new LootValidator()); registry.registerService(Loot.class, new LootGiving()); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootResources.java b/src/main/java/art/arcane/iris/engine/loot/LootResources.java index b21985205..d0085a58f 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootResources.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootResources.java @@ -19,8 +19,7 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackResources; +import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; @@ -46,11 +45,10 @@ public final class LootResources { return List.of(TABLES); } - public static LootTable table(IrisData data, String key) { + public static LootTable table(PackResources resources, String key) { if (key == null || key.isBlank()) { return null; } - IrisPackResources resources = data.getPackResources(); try { return resources.find(TABLES.key(resources.idOf(key))).orElse(null); } catch (IllegalStateException failedToLoad) { @@ -59,7 +57,7 @@ public final class LootResources { } /** The key of every loot table of the pack, in key order. */ - public static List tableKeys(IrisData data) { - return data.getPackResources().ids(TABLES.type()).stream().map(ResourceId::path).toList(); + public static List tableKeys(PackResources resources) { + return resources.ids(TABLES.type()).stream().map(ResourceId::path).toList(); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java index 5798565f4..d40014994 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootTables.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -18,14 +18,13 @@ package art.arcane.iris.engine.loot; +import art.arcane.iris.builtin.LiveWorld; +import art.arcane.iris.builtin.LiveWorld.Level; import art.arcane.iris.builtin.loot.LootMode; -import art.arcane.iris.builtin.loot.LootSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.builtin.loot.LootResolver; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.volmlib.util.math.RNG; +import com.volmit.world.PackWorld; import java.util.List; import java.util.Objects; @@ -64,9 +63,9 @@ public final class LootTables { return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity); } - /** The loot settings a dimension, region or biome declares; the defaults, which add nothing, when it declares none. */ - public static LootSettings settingsOf(IrisRegistrant owner) { - return owner.getModuleSettings().find(LootSettings.class).orElseGet(LootSettings::new); + /** The loot settings the level declares at the block; the defaults, which add nothing, when it declares none. */ + private static LootSettings settingsAt(LiveWorld live, Level level, int x, int relativeY, int z) { + return live.settings(LootSettings.class, level, x, relativeY, z).orElseGet(LootSettings::new); } /** @@ -76,7 +75,7 @@ public final class LootTables { */ public static void resolveEnvironmentSources( List sources, - Engine engine, + PackWorld world, RNG rng, int x, int relativeY, @@ -84,31 +83,25 @@ public final class LootTables { boolean objectLootDefined, Function mapper ) { - IrisRegion region = engine.getComplex().getRegionStream().get(x, z); - IrisBiome surfaceBiome = engine.getComplex().getTrueBiomeStream().get(x, z); - double terrainHeight = engine.getComplex().getHeightStream().get(x, z); - IrisBiome contextualBiome = relativeY < terrainHeight - ? engine.getCaveBiome(x, relativeY, z) - : surfaceBiome; - if (contextualBiome == null) { - contextualBiome = surfaceBiome; - } + LiveWorld live = LiveWorld.of(world); + boolean belowSurface = relativeY < live.terrainHeight(x, z); + boolean distinctContextualBiome = belowSurface && !live.caveBiome(x, relativeY, z).equals(live.surfaceBiome(x, z)); - LootSettings dimensionLoot = settingsOf(engine.getDimension()); - LootSettings regionLoot = settingsOf(region); - LootSettings surfaceLoot = settingsOf(surfaceBiome); - boolean distinctContextualBiome = !sameBiome(surfaceBiome, contextualBiome); + LootSettings dimensionLoot = settingsAt(live, Level.DIMENSION, x, relativeY, z); + LootSettings regionLoot = settingsAt(live, Level.REGION, x, relativeY, z); + LootSettings surfaceLoot = settingsAt(live, Level.SURFACE_BIOME, x, relativeY, z); double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier(); - if (distinctContextualBiome) { - multiplier *= settingsOf(contextualBiome).multiplier(); + LootSettings contextualLoot = distinctContextualBiome ? settingsAt(live, Level.CAVE_BIOME, x, relativeY, z) : null; + if (contextualLoot != null) { + multiplier *= contextualLoot.multiplier(); } boolean fallback = !objectLootDefined; - injectReference(sources, dimensionLoot, engine, mapper, fallback); - injectReference(sources, regionLoot, engine, mapper, fallback); - injectReference(sources, surfaceLoot, engine, mapper, fallback); - if (distinctContextualBiome) { - injectReference(sources, settingsOf(contextualBiome), engine, mapper, fallback); + injectReference(sources, dimensionLoot, world, mapper, fallback); + injectReference(sources, regionLoot, world, mapper, fallback); + injectReference(sources, surfaceLoot, world, mapper, fallback); + if (contextualLoot != null) { + injectReference(sources, contextualLoot, world, mapper, fallback); } LootResolver.scaleSources(sources, multiplier, rng); } @@ -133,25 +126,15 @@ public final class LootTables { sources.addAll(additions); } - static boolean sameBiome(IrisBiome first, IrisBiome second) { - if (first == second) { - return true; - } - if (first == null || second == null) { - return false; - } - return Objects.equals(first.getLoadKey(), second.getLoadKey()); - } - private static void injectReference( List sources, LootSettings loot, - Engine engine, + PackWorld world, Function mapper, boolean fallback ) { List additions = loot.tables().stream() - .filter(key -> LootResources.table(engine.getData(), key) != null) + .filter(key -> LootResources.table(world.resources(), key) != null) .map(mapper) .filter(Objects::nonNull) .toList(); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java index cb4fef3d0..bebef35dd 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -18,269 +18,210 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.core.modules.IrisValidationContext; -import art.arcane.iris.core.pack.PackIntegerChecks; -import art.arcane.iris.core.pack.PackValidationIo; +import art.arcane.iris.builtin.loot.LootEnchantment; import art.arcane.iris.builtin.loot.LootEntry; +import art.arcane.iris.builtin.loot.LootMode; import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.validation.Problem; import com.volmit.validation.Subject; import com.volmit.validation.ValidationContext; import com.volmit.validation.Validator; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.util.ArrayList; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.function.BiFunction; /** * Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot - * reference of a dimension, region or biome names a table the pack has. The files are read as written, like the pack - * validator's other file checks, so a malformed table is reported rather than failing the load. + * reference of a dimension, region or biome names a table the pack has. It checks the tables and settings as they + * decoded; a file that is not valid JSON, or holds a value of the wrong type, is reported by the load that reads it. */ public final class LootValidator implements Validator { - private static final List LOOT_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); private static final String JSON_EXTENSION = ".json"; + private static final String LEVEL_FOLDER_SEPARATOR = "/"; @Override public void validate(ValidationContext pack) { - check(IrisValidationContext.of(pack).data().getDataFolder()).forEach(pack::report); + checkTables(pack.resources()).forEach(pack::report); + checkReferences(pack).forEach(pack::report); } - /** What is wrong with the loot tables and loot references of the pack in {@code packFolder}. */ - public static List check(File packFolder) { + private static List checkTables(PackResources resources) { List problems = new ArrayList<>(); - if (packFolder == null || !packFolder.isDirectory()) { - return problems; - } - - File lootFolder = new File(packFolder, LootResources.TABLES.folder()); - Set lootKeys = keysOf(lootFolder); - checkTables(lootFolder, problems); - for (String folderName : LOOT_HOST_FOLDERS) { - checkReferences(new File(packFolder, folderName), folderName, lootKeys, problems); - } - return problems; - } - - private static void checkTables(File lootFolder, List problems) { - if (!lootFolder.isDirectory()) { - return; - } - List lootFiles = PackValidationIo.listJsonRecursive(lootFolder); - lootFiles.sort(Comparator.comparing(File::getPath)); - for (File lootFile : lootFiles) { - String lootKey = PackValidationIo.deriveKey(lootFolder, lootFile); + for (ResourceId id : resources.ids(LootTable.class)) { + String lootKey = id.path(); List errors = new ArrayList<>(); - JSONObject table = readTable(lootFile, lootKey, errors); + LootTable table = readTable(resources, id, lootKey, errors); if (table != null) { validateLootTable(lootKey, table, errors); } report(problems, Problem::error, Subject.file(LootResources.TABLES.folder() + "/" + lootKey + JSON_EXTENSION), errors); } + return problems; } - private static void checkReferences(File resourceFolder, String folderName, Set lootKeys, List problems) { - if (!resourceFolder.isDirectory()) { - return; - } - List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); - resourceFiles.sort(Comparator.comparing(File::getPath)); - for (File resourceFile : resourceFiles) { - JSONObject resource = PackValidationIo.readJson(resourceFile); - if (resource == null || !resource.has("loot")) { - continue; - } - String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); + private static List checkReferences(ValidationContext pack) { + Set lootIds = Set.copyOf(pack.resources().ids(LootTable.class)); + List problems = new ArrayList<>(); + List> declared = new ArrayList<>(pack.settings().declared(LootSettings.class)); + declared.sort(Comparator.comparing(Entry::level).thenComparing(Entry::source)); + for (Entry entry : declared) { + String resourceKey = keyOf(entry); List errors = new ArrayList<>(); List warnings = new ArrayList<>(); - validateLootReference(hostType(folderName), resourceKey, resource.opt("loot"), lootKeys, errors, warnings); - Subject subject = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION); + validateLootReference(pack.resources(), hostType(entry.level()), resourceKey, entry.value(), lootIds, errors, warnings); + Subject subject = Subject.file(folderOf(entry.level()) + "/" + resourceKey + JSON_EXTENSION); report(problems, Problem::error, subject, errors); report(problems, Problem::warning, subject, warnings); } + return problems; } - private static void report(List problems, java.util.function.BiFunction severity, + private static void report(List problems, BiFunction severity, Subject subject, List messages) { for (String message : messages) { problems.add(severity.apply(subject, message)); } } - private static Set keysOf(File folder) { - Set keys = new HashSet<>(); - if (!folder.isDirectory()) { - return keys; - } - for (File file : PackValidationIo.listJsonRecursive(folder)) { - String key = PackValidationIo.deriveKey(folder, file); - if (key != null && !key.isBlank()) { - keys.add(key); - } - } - return keys; - } - - private static JSONObject readTable(File file, String key, List errors) { + private static LootTable readTable(PackResources resources, ResourceId id, String key, List errors) { try { - return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); - } catch (IOException | RuntimeException e) { - String reason = e.getMessage(); - if (reason == null || reason.isBlank()) { - reason = e.getClass().getSimpleName(); - } - errors.add("Loot table '" + key + "' has invalid JSON: " + reason); + return resources.find(LootResources.TABLES.key(id)).orElse(null); + } catch (IllegalStateException failedToLoad) { + errors.add("Loot table '" + key + "' cannot be read; the log says what is wrong with the file."); return null; } } - private static String hostType(String folderName) { - return switch (folderName) { - case "dimensions" -> "Dimension"; - case "regions" -> "Region"; - case "biomes" -> "Biome"; - default -> "Resource"; + /** The key of the dimension, region or biome that declared {@code entry}: its source id is {@code :/}. */ + private static String keyOf(Entry entry) { + String path = entry.source().path(); + return path.substring(path.indexOf(LEVEL_FOLDER_SEPARATOR) + 1); + } + + private static String hostType(Target level) { + return switch (level) { + case DIMENSION -> "Dimension"; + case REGION -> "Region"; + case BIOME -> "Biome"; + case OBJECT_PLACEMENT -> "Resource"; }; } - private static void validateLootTable(String lootKey, JSONObject table, List blockingErrors) { - String path = "Loot table '" + lootKey + "'"; - Integer rarity = PackIntegerChecks.integerField(table, "rarity", 1, path, blockingErrors); - Integer minimumPicked = PackIntegerChecks.integerField(table, "minPicked", 1, path, blockingErrors); - Integer maximumPicked = PackIntegerChecks.integerField(table, "maxPicked", 5, path, blockingErrors); - Integer maximumTries = PackIntegerChecks.integerField(table, "maxTries", 10, path, blockingErrors); - PackIntegerChecks.requireMinimum(path + ".rarity", rarity, 1, blockingErrors); - PackIntegerChecks.requireMinimum(path + ".minPicked", minimumPicked, 0, blockingErrors); - PackIntegerChecks.requireMinimum(path + ".maxPicked", maximumPicked, 1, blockingErrors); - PackIntegerChecks.requireMinimum(path + ".maxTries", maximumTries, 1, blockingErrors); - PackIntegerChecks.requireMaximum(path + ".minPicked", minimumPicked, LootTable.MAX_PICKED, blockingErrors); - PackIntegerChecks.requireMaximum(path + ".maxPicked", maximumPicked, LootTable.MAX_PICKED, blockingErrors); - PackIntegerChecks.requireMaximum(path + ".maxTries", maximumTries, LootTable.MAX_TRIES, blockingErrors); - PackIntegerChecks.requireOrdered(path + ".minPicked", minimumPicked, path + ".maxPicked", maximumPicked, blockingErrors); + private static String folderOf(Target level) { + return switch (level) { + case DIMENSION -> "dimensions"; + case REGION -> "regions"; + case BIOME -> "biomes"; + case OBJECT_PLACEMENT -> "placements"; + }; + } - JSONArray entries = table.optJSONArray("loot"); - if (entries == null || entries.length() == 0) { + private static void validateLootTable(String lootKey, LootTable table, List blockingErrors) { + String path = "Loot table '" + lootKey + "'"; + requireMinimum(path + ".rarity", table.rarity(), 1, blockingErrors); + requireMinimum(path + ".minPicked", table.minPicked(), 0, blockingErrors); + requireMinimum(path + ".maxPicked", table.maxPicked(), 1, blockingErrors); + requireMinimum(path + ".maxTries", table.maxTries(), 1, blockingErrors); + requireMaximum(path + ".minPicked", table.minPicked(), LootTable.MAX_PICKED, blockingErrors); + requireMaximum(path + ".maxPicked", table.maxPicked(), LootTable.MAX_PICKED, blockingErrors); + requireMaximum(path + ".maxTries", table.maxTries(), LootTable.MAX_TRIES, blockingErrors); + requireOrdered(path + ".minPicked", table.minPicked(), path + ".maxPicked", table.maxPicked(), blockingErrors); + + List entries = table.loot(); + if (entries.isEmpty()) { blockingErrors.add(path + ".loot must be a non-empty array."); return; } - for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) { - JSONObject entry = entries.optJSONObject(entryIndex); - String entryPath = path + ".loot[" + entryIndex + "]"; - if (entry == null) { - blockingErrors.add(entryPath + " must be an object."); - continue; - } - String type = entry.optString("type", "").trim(); - if (type.isEmpty()) { - blockingErrors.add(entryPath + ".type must not be blank."); - } - Integer entryRarity = PackIntegerChecks.integerField(entry, "rarity", 1, entryPath, blockingErrors); - Integer minimumAmount = PackIntegerChecks.integerField(entry, "minAmount", 1, entryPath, blockingErrors); - Integer maximumAmount = PackIntegerChecks.integerField(entry, "maxAmount", 1, entryPath, blockingErrors); - PackIntegerChecks.requireMinimum(entryPath + ".rarity", entryRarity, 1, blockingErrors); - PackIntegerChecks.requireMinimum(entryPath + ".minAmount", minimumAmount, 1, blockingErrors); - PackIntegerChecks.requireMinimum(entryPath + ".maxAmount", maximumAmount, 1, blockingErrors); - PackIntegerChecks.requireMaximum(entryPath + ".minAmount", minimumAmount, LootEntry.MAX_AMOUNT, blockingErrors); - PackIntegerChecks.requireMaximum(entryPath + ".maxAmount", maximumAmount, LootEntry.MAX_AMOUNT, blockingErrors); - PackIntegerChecks.requireOrdered(entryPath + ".minAmount", minimumAmount, - entryPath + ".maxAmount", maximumAmount, blockingErrors); - validateLootEnchantments(entryPath, entry.opt("enchantments"), blockingErrors); + for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) { + validateLootEntry(path + ".loot[" + entryIndex + "]", entries.get(entryIndex), blockingErrors); } } - private static void validateLootEnchantments(String entryPath, Object rawEnchantments, - List blockingErrors) { - if (rawEnchantments == null || rawEnchantments == JSONObject.NULL) { + private static void validateLootEntry(String entryPath, LootEntry entry, List blockingErrors) { + if (entry == null) { + blockingErrors.add(entryPath + " must be an object."); return; } - if (!(rawEnchantments instanceof JSONArray enchantments)) { - blockingErrors.add(entryPath + ".enchantments must be an array."); - return; + if (entry.type().trim().isEmpty()) { + blockingErrors.add(entryPath + ".type must not be blank."); } - for (int enchantmentIndex = 0; enchantmentIndex < enchantments.length(); enchantmentIndex++) { - JSONObject enchantment = enchantments.optJSONObject(enchantmentIndex); - String enchantmentPath = entryPath + ".enchantments[" + enchantmentIndex + "]"; - if (enchantment == null) { - blockingErrors.add(enchantmentPath + " must be an object."); - continue; - } - if (enchantment.optString("enchantment", "").isBlank()) { - blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); - } - Integer minimumLevel = PackIntegerChecks.integerField(enchantment, "minLevel", 1, enchantmentPath, blockingErrors); - Integer maximumLevel = PackIntegerChecks.integerField(enchantment, "maxLevel", 1, enchantmentPath, blockingErrors); - PackIntegerChecks.requireMinimum(enchantmentPath + ".minLevel", minimumLevel, 1, blockingErrors); - PackIntegerChecks.requireMinimum(enchantmentPath + ".maxLevel", maximumLevel, 1, blockingErrors); - PackIntegerChecks.requireOrdered(enchantmentPath + ".minLevel", minimumLevel, - enchantmentPath + ".maxLevel", maximumLevel, blockingErrors); - if (enchantment.has("chance")) { - Object rawChance = enchantment.opt("chance"); - if (!(rawChance instanceof Number number) - || !Double.isFinite(number.doubleValue()) - || number.doubleValue() < 0D - || number.doubleValue() > 1D) { - blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1."); - } - } + requireMinimum(entryPath + ".rarity", entry.rarity(), 1, blockingErrors); + requireMinimum(entryPath + ".minAmount", entry.minAmount(), 1, blockingErrors); + requireMinimum(entryPath + ".maxAmount", entry.maxAmount(), 1, blockingErrors); + requireMaximum(entryPath + ".minAmount", entry.minAmount(), LootEntry.MAX_AMOUNT, blockingErrors); + requireMaximum(entryPath + ".maxAmount", entry.maxAmount(), LootEntry.MAX_AMOUNT, blockingErrors); + requireOrdered(entryPath + ".minAmount", entry.minAmount(), entryPath + ".maxAmount", entry.maxAmount(), blockingErrors); + + List enchantments = entry.enchantments(); + for (int enchantmentIndex = 0; enchantmentIndex < enchantments.size(); enchantmentIndex++) { + validateEnchantment(entryPath + ".enchantments[" + enchantmentIndex + "]", enchantments.get(enchantmentIndex), blockingErrors); } } - private static void validateLootReference(String resourceType, String resourceKey, Object rawLoot, - Set lootKeys, List blockingErrors, List warnings) { + private static void validateEnchantment(String enchantmentPath, LootEnchantment enchantment, List blockingErrors) { + if (enchantment == null) { + blockingErrors.add(enchantmentPath + " must be an object."); + return; + } + String name = enchantment.enchantment(); + if (name == null || name.isBlank()) { + blockingErrors.add(enchantmentPath + ".enchantment must not be blank."); + } + requireMinimum(enchantmentPath + ".minLevel", enchantment.minLevel(), 1, blockingErrors); + requireMinimum(enchantmentPath + ".maxLevel", enchantment.maxLevel(), 1, blockingErrors); + requireOrdered(enchantmentPath + ".minLevel", enchantment.minLevel(), + enchantmentPath + ".maxLevel", enchantment.maxLevel(), blockingErrors); + double chance = enchantment.chance(); + if (!Double.isFinite(chance) || chance < 0D || chance > 1D) { + blockingErrors.add(enchantmentPath + ".chance must be a finite number from 0 to 1."); + } + } + + private static void validateLootReference(PackResources resources, String resourceType, String resourceKey, LootSettings reference, + Set lootIds, List blockingErrors, List warnings) { String path = resourceType + " '" + resourceKey + "'.loot"; - if (!(rawLoot instanceof JSONObject reference)) { - blockingErrors.add(path + " must be an object."); - return; + double multiplier = reference.multiplier(); + if (!Double.isFinite(multiplier) || multiplier < 0D || multiplier > LootSettings.MAX_MULTIPLIER) { + blockingErrors.add(path + ".multiplier must be a finite number from 0 to " + (int) LootSettings.MAX_MULTIPLIER + "."); } - boolean clearMode = false; - if (reference.has("mode")) { - Object rawMode = reference.opt("mode"); - if (!(rawMode instanceof String mode) - || !Set.of("ADD", "CLEAR", "REPLACE", "FALLBACK").contains(mode)) { - blockingErrors.add(path + ".mode must be ADD, CLEAR, REPLACE, or FALLBACK."); - } else { - clearMode = "CLEAR".equals(mode); - } - } - if (reference.has("multiplier")) { - Object rawMultiplier = reference.opt("multiplier"); - if (!(rawMultiplier instanceof Number multiplier) - || !Double.isFinite(multiplier.doubleValue()) - || multiplier.doubleValue() < 0D - || multiplier.doubleValue() > LootSettings.MAX_MULTIPLIER) { - blockingErrors.add(path + ".multiplier must be a finite number from 0 to " - + (int) LootSettings.MAX_MULTIPLIER + "."); - } - } - if (!reference.has("tables")) { - return; - } - JSONArray tables = reference.optJSONArray("tables"); - if (tables == null) { - blockingErrors.add(path + ".tables must be an array."); - return; - } - if (clearMode && tables.length() > 0) { - warnings.add(path + " uses mode CLEAR and lists " + tables.length() + List tables = reference.tables(); + if (reference.mode() == LootMode.CLEAR && !tables.isEmpty()) { + warnings.add(path + " uses mode CLEAR and lists " + tables.size() + " table(s); CLEAR clears parent tables and contributes no tables of its own, so these entries are dead. Use REPLACE to substitute them."); } - for (int tableIndex = 0; tableIndex < tables.length(); tableIndex++) { - Object rawTableKey = tables.opt(tableIndex); - if (!(rawTableKey instanceof String tableKey) || tableKey.isBlank()) { + for (int tableIndex = 0; tableIndex < tables.size(); tableIndex++) { + String tableKey = tables.get(tableIndex); + if (tableKey == null || tableKey.isBlank()) { blockingErrors.add(path + ".tables[" + tableIndex + "] must name a loot table."); - } else if (!lootKeys.contains(tableKey)) { - blockingErrors.add(path + ".tables[" + tableIndex - + "] references missing loot table '" + tableKey + "'."); + } else if (!lootIds.contains(resources.idOf(tableKey))) { + blockingErrors.add(path + ".tables[" + tableIndex + "] references missing loot table '" + tableKey + "'."); } } } + + private static void requireMinimum(String fieldPath, int value, int minimum, List blockingErrors) { + if (value < minimum) { + blockingErrors.add(fieldPath + " must be at least " + minimum + "."); + } + } + + private static void requireMaximum(String fieldPath, int value, int maximum, List blockingErrors) { + if (value > maximum) { + blockingErrors.add(fieldPath + " must be at most " + maximum + "."); + } + } + + private static void requireOrdered(String minimumPath, int minimum, String maximumPath, int maximum, List blockingErrors) { + if (minimum > maximum) { + blockingErrors.add(minimumPath + " must not exceed " + maximumPath + "."); + } + } } diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index 09973ad96..0e91f6e0f 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.builtin.loot.LootResolver; -import art.arcane.iris.engine.object.loot.IObjectLoot; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.builtin.loot.ObjectLootEntry; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.resource.PackResources; import com.volmit.service.Loot; import java.util.ArrayList; @@ -43,32 +43,27 @@ final class PlacementLoot { private static final char NAMESPACE_SEPARATOR = ':'; private static final char PROPERTIES_START = '['; - private final IrisData data; + private final PackResources resources; private final Supplier> platformTables; private final long lootSeed; private final ModuleLog log; /** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */ - PlacementLoot(IrisData data, Supplier> platformTables, long lootSeed, ModuleLog log) { - this.data = data; + PlacementLoot(PackResources resources, Supplier> platformTables, long lootSeed, ModuleLog log) { + this.resources = resources; this.platformTables = platformTables; this.lootSeed = lootSeed; this.log = log; } - /** The platform's loot table keys, which a placement may name, in the form a placement names them. */ - static Set platformTableKeys() { - return Set.copyOf(IrisPlatforms.get().registries().lootTableKeys()); - } - /** * The table a placement, whose platform tables are {@code platformLoot} and whose pack tables are {@code packLoot}, * gives {@code container}, a storage chest, at the spot {@code x}, {@code worldY}, {@code z}; null when it gives * it none. */ - Loot.Source pick(List platformLoot, List packLoot, PlatformBlockState container, + Loot.Source pick(List platformLoot, List packLoot, BlockState container, RNG rng, int x, int worldY, int z) { - Candidates candidates = new Candidates(container); + Candidates candidates = new Candidates(resources.blocks().resolve(container)); add(candidates, platformLoot, name -> platformSource(name, x, worldY, z)); add(candidates, packLoot, this::packSource); List pool = candidates.pool(); @@ -76,22 +71,22 @@ final class PlacementLoot { return picked == null ? null : picked.source(); } - private void add(Candidates candidates, List entries, Function sourceOf) { - for (IObjectLoot entry : entries) { - if (entry == null || entry.getWeight() <= 0) { + private void add(Candidates candidates, List entries, Function sourceOf) { + for (ObjectLootEntry entry : entries) { + if (entry == null || entry.weight() <= 0) { continue; } - Loot.Source source = sourceOf.apply(entry.getName()); + Loot.Source source = sourceOf.apply(entry.name()); if (source == null) { - log.warn("Couldn't find loot table " + entry.getName()); + log.warn("Couldn't find loot table " + entry.name()); continue; } - candidates.add(entry, data, new Candidate(source, entry.getWeight())); + candidates.add(entry, resources, new Candidate(source, entry.weight())); } } private Loot.Source packSource(String key) { - return LootResources.table(data, key) == null ? null : new Loot.Table(key); + return LootResources.table(resources, key) == null ? null : new Loot.Table(key); } private Loot.Source platformSource(String name, int x, int worldY, int z) { @@ -121,21 +116,22 @@ final class PlacementLoot { private final List basic = new ArrayList<>(); private final List global = new ArrayList<>(); - private Candidates(PlatformBlockState container) { + private Candidates(BlockState container) { this.containerKey = container.key(); this.containerMaterial = materialOf(containerKey); } - void add(IObjectLoot entry, IrisData data, Candidate candidate) { - List filter = entry.getFilter(data); + void add(ObjectLootEntry entry, PackResources resources, Candidate candidate) { + List filter = entry.filter(); if (filter.isEmpty()) { global.add(candidate); return; } - for (PlatformBlockState filterState : filter) { - if (entry.isExact() && filterState.key().equals(containerKey)) { + for (BlockSpec filterSpec : filter) { + String filterKey = resources.blocks().resolve(filterSpec).key(); + if (entry.exact() && filterKey.equals(containerKey)) { exact.add(candidate); - } else if (!entry.isExact() && materialOf(filterState.key()).equals(containerMaterial)) { + } else if (!entry.exact() && materialOf(filterKey).equals(containerMaterial)) { basic.add(candidate); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java b/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java index d42367c31..a33b046b6 100644 --- a/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java +++ b/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java @@ -19,8 +19,6 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.loot.BlockDrop; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; @@ -45,10 +43,7 @@ final class ResolvedBlockDrop { static ResolvedBlockDrop of(BlockDrop drop, BlockRegistry blocks) { Set keys = new LinkedHashSet<>(); for (BlockSpec spec : drop.blocks()) { - PlatformBlockState state = IrisPlatforms.get().registries().block(blocks.resolve(spec).key()); - if (state != null) { - keys.add(comparable(state.key(), drop.exactBlocks())); - } + keys.add(comparable(blocks.resolve(spec).key(), drop.exactBlocks())); } return new ResolvedBlockDrop(drop, keys); } 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 index 04f8a27ba..09cfcb19d 100644 --- a/src/main/java/art/arcane/iris/engine/object/value/IRare.java +++ b/src/main/java/art/arcane/iris/engine/object/value/IRare.java @@ -93,23 +93,5 @@ public interface IRare { return v instanceof IRare ? Math.max(1, ((IRare) v).getRarity()) : 1; } - /** - * Expands a candidate list into a rarity-weighted list: each entry appears totalRarity/rarity - * times, so picking uniformly from the result applies rarity exactly once. Both the Bukkit and - * modded entity spawners select through this expansion; rarity must never be applied a second - * time per spawn position. - */ - static KList expandWeighted(List possibilities) { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for (T i : possibilities) { - totalRarity += get(i); - } - for (T i : possibilities) { - rarityTypes.addMultiple(i, totalRarity / get(i)); - } - return rarityTypes; - } - int getRarity(); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java index f1af6b1c4..370847e79 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -18,14 +18,13 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.LiveWorld; +import art.arcane.iris.builtin.LiveWorld.Level; +import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EffectCommands; import art.arcane.iris.builtin.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.SpawnCommand; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.math.RNG; import com.volmit.entity.EntitySpec; import com.volmit.service.AmbientEffects; @@ -34,6 +33,7 @@ import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** * How {@code iris:spawn} plays the ambient effects of regions and biomes: the region's effects, then the biome's, each @@ -42,32 +42,32 @@ import java.util.List; public final class AmbientEffecting implements AmbientEffects { @Override public List due(PackWorld world, BlockPosition at) { - Engine engine = IrisPackWorld.of(world).engine(); + LiveWorld live = LiveWorld.of(world); EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers()); - PlatformWorld platformWorld = engine.getWorld().platformWorld(); + Optional sky = live.sky(); List due = new ArrayList<>(); - addDue(due, effectsOf(engine.getRegion(at.x(), at.z())), timers, platformWorld); - addDue(due, effectsOf(engine.getBiome(at.x(), at.y(), at.z())), timers, platformWorld); + addDue(due, effectsOf(live, Level.REGION, at), timers, sky); + addDue(due, effectsOf(live, Level.BIOME, at), timers, sky); return due; } - private static List effectsOf(IrisRegistrant owner) { - return owner.getModuleSettings().find(EffectSettings.class).map(EffectSettings::effects).orElse(List.of()); + private static List effectsOf(LiveWorld live, Level level, BlockPosition at) { + return live.settings(EffectSettings.class, level, at.x(), at.y(), at.z()).map(EffectSettings::effects).orElse(List.of()); } - private static void addDue(List due, List effects, EffectTimers timers, PlatformWorld world) { + private static void addDue(List due, List effects, EffectTimers timers, Optional sky) { for (AmbientEffect effect : effects) { if (timers.shouldPlayNow(effect)) { - due.add(play(effect, world)); + due.add(play(effect, sky)); } } } - private static Effect play(AmbientEffect effect, PlatformWorld world) { + private static Effect play(AmbientEffect effect, Optional sky) { Sound sound = effect.sound() == null ? null : soundOf(effect); Particles particles = effect.particleEffect() == null ? null : particlesOf(effect); - return new Effect(sound, particles, commandsOf(effect.commandRegistry(), world), potionOf(effect)); + return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect)); } private static Sound soundOf(AmbientEffect effect) { @@ -92,7 +92,7 @@ public final class AmbientEffecting implements AmbientEffects { altX, altY, altZ, effect.extra()); } - private static List commandsOf(EffectCommands registry, PlatformWorld world) { + private static List commandsOf(EffectCommands registry, Optional sky) { List commands = new ArrayList<>(); if (registry == null) { return commands; @@ -102,7 +102,7 @@ public final class AmbientEffecting implements AmbientEffects { double offsetY = commandOffset(registry.commandOffsetY(), registry.commandRandomAltY()); double offsetZ = commandOffset(registry.commandOffsetZ(), registry.commandRandomAltZ()); for (SpawnCommand command : registry.rawCommands()) { - if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) { + if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) { commands.add(new Command(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay()), offsetX, offsetY, offsetZ)); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index f1b1f467d..e934f61c3 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.loot.ItemAttributeModifier; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.spawn.AmbientEffect; @@ -25,7 +26,6 @@ import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.loot.LootItems; -import art.arcane.iris.spi.PlatformWorld; import art.arcane.volmlib.util.math.RNG; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemAttribute; @@ -33,6 +33,7 @@ import com.volmit.item.ItemDrop; import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** * Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris @@ -43,13 +44,13 @@ final class EntityResolution { private static final long LEASH_HOLDER_STREAM = 234548L; private final LootItems items; - private final PlatformWorld world; + private final Optional sky; private final EffectTimers timers; - /** @param world the world the entity appears in, whose time and weather decide which of its commands run */ - EntityResolution(LootItems items, PlatformWorld world, EffectTimers timers) { + /** @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world */ + EntityResolution(LootItems items, Optional sky, EffectTimers timers) { this.items = items; - this.world = world; + this.sky = sky; this.timers = timers; } @@ -121,7 +122,7 @@ final class EntityResolution { private List commandsOf(EntityDefinition entity) { List commands = new ArrayList<>(); for (SpawnCommand command : entity.rawCommands()) { - if (SpawnConditions.allow(command.timeBlock(), command.weather(), world)) { + if (sky.isPresent() && SpawnConditions.allow(command.timeBlock(), command.weather(), sky.get())) { commands.add(new EntitySpec.Command(command.commands(), command.delay(), command.repeat(), command.repeatDelay())); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index cccf82fd3..f5ba8f655 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -18,29 +18,25 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.LiveWorld; +import art.arcane.iris.builtin.LiveWorld.Level; +import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.EntitySpawn; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.SpawnSurface; import art.arcane.iris.builtin.spawn.Spawner; import art.arcane.iris.builtin.spawn.SpawnerSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.loot.LootItems; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner; -import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.slices.MarkerMatter; +import art.arcane.volmlib.util.scheduling.ChronoLatch; import com.volmit.config.Range; import com.volmit.entity.EntitySpec; +import com.volmit.resource.PackResources; import com.volmit.service.EntitySpawns; import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; @@ -63,13 +59,15 @@ public final class EntitySpawning implements EntitySpawns { private static final String CAVE_FLOOR_MARKER = "cave_floor"; private static final String CAVE_CEILING_MARKER = "cave_ceiling"; private static final int AIR_ABOVE_MARKER = 1; + private static final long COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS = 60_000L; + private static final int LAYOUT_QUESTION_HEIGHT = 0; @Override public Optional plan(PackWorld world, Site site) { - Engine engine = engine(world); + forgetExpiredCooldowns(world); return switch (site) { - case Chunk chunk -> planChunk(world, engine, chunk); - case Marker marker -> planMarker(world, engine, marker); + case Chunk chunk -> planChunk(world, chunk); + case Marker marker -> planMarker(world, marker); }; } @@ -78,19 +76,19 @@ public final class EntitySpawning implements EntitySpawns { if (count <= 0) { return; } - Spawner spawner = SpawnResources.spawner(engine(world).getData(), plan.spawner()); + Spawner spawner = SpawnResources.spawner(world.resources(), plan.spawner()); if (spawner != null) { - SpawnerGate.spawned(plan.spawner(), spawner, engine(world), plan.chunkX(), plan.chunkZ()); + SpawnerGate.spawned(plan.spawner(), spawner, LiveWorld.of(world), plan.chunkX(), plan.chunkZ()); } } @Override public Optional entity(PackWorld world, String key) { - EntityDefinition entity = SpawnResources.entity(engine(world).getData(), key); + EntityDefinition entity = SpawnResources.entity(world.resources(), key); if (entity == null) { return Optional.empty(); } - return Optional.of(resolution(world, engine(world)).resolve(entity, entityRandom(world).rng())); + return Optional.of(resolution(world).resolve(entity, entityRandom(world).rng())); } @Override @@ -98,15 +96,14 @@ public final class EntitySpawning implements EntitySpawns { if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) { return Optional.empty(); } - Engine engine = engine(world); - SpawnMarker marker = SpawnResources.marker(engine.getData(), tag); + SpawnMarker marker = SpawnResources.marker(world.resources(), tag); if (marker == null) { return Optional.empty(); } List spawners = new ArrayList<>(); for (String key : marker.spawners()) { - if (SpawnResources.spawner(engine.getData(), key) == null) { + if (SpawnResources.spawner(world.resources(), key) == null) { world.log().error("Cannot load spawner: " + key + " for marker " + tag, null); continue; } @@ -115,69 +112,78 @@ public final class EntitySpawning implements EntitySpawns { return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange())); } - private Optional planChunk(PackWorld world, Engine engine, Chunk chunk) { - Predicate canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), engine, chunk.chunkX(), chunk.chunkZ()); + /** Drops the cooldowns that ran out, now and then: the world's data keeps them across restarts. */ + private static void forgetExpiredCooldowns(PackWorld world) { + CooldownCleanup cleanup = world.state(CooldownCleanup.class, ignored -> new CooldownCleanup()); + if (!cleanup.due()) { + return; + } + PackResources resources = world.resources(); + LiveWorld.of(world).spawnCooldowns().forgetExpired(key -> { + Spawner spawner = SpawnResources.spawner(resources, key); + return spawner == null ? -1L : spawner.maximumRate().interval(); + }); + } + + private Optional planChunk(PackWorld world, Chunk chunk) { + LiveWorld live = LiveWorld.of(world); + Predicate canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), live, chunk.chunkX(), chunk.chunkZ()); int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); - IrisBiome centreBiome = engine.getSurfaceBiome(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); - IrisRegion region = engine.getRegion(blockX, blockZ); - IrisBiome biome = engine.getSurfaceBiome(blockX, blockZ); + LiveWorld.BiomeKind centreKind = live.surfaceKind(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); List candidates = Stream.concat( - shuffled(engine, engine.getDimension()).stream() - .filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreBiome)), + shuffled(world, live, Level.DIMENSION, blockX, blockZ).stream() + .filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreKind)), Stream.concat( - shuffled(engine, region).stream().filter(canSpawn), - shuffled(engine, biome).stream().filter(canSpawn))) + shuffled(world, live, Level.REGION, blockX, blockZ).stream().filter(canSpawn), + shuffled(world, live, Level.SURFACE_BIOME, blockX, blockZ).stream().filter(canSpawn))) .filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk()) .toList(); List spawns = candidates.stream().flatMap(keyed -> spawnsOf(keyed, chunk.initial())).collect(Collectors.toList()); - Candidate chosen = IRare.expandWeighted(spawns).getRandom(); + Candidate chosen = RarityWeighting.expand(spawns, Candidate::rarity).getRandom(); if (chosen == null) { return Optional.empty(); } - return planChunkSpawn(world, engine, chunk, chosen); + return planChunkSpawn(world, live, chunk, chosen); } - private Optional planChunkSpawn(PackWorld world, Engine engine, Chunk chunk, Candidate chosen) { + private Optional planChunkSpawn(PackWorld world, LiveWorld live, Chunk chunk, Candidate chosen) { EntitySpawn spawn = chosen.spawn(); int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); List attempts = new ArrayList<>(); for (int i = 0; i < count; i++) { int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); - BlockPosition at = spawnPosition(engine, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); + BlockPosition at = spawnPosition(live, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); if (at != null) { - addAttempt(attempts, world, engine, chosen, at, true); + addAttempt(attempts, world, chosen, at, true); } } return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(chosen.key(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); } /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ - private static BlockPosition spawnPosition(Engine engine, Spawner spawner, int chunkX, int chunkZ, int x, int z) { - int height = engine.getHeight(x, z, true); - int heightWithFluid = engine.getHeight(x, z, false); + private static BlockPosition spawnPosition(LiveWorld live, Spawner spawner, int chunkX, int chunkZ, int x, int z) { + int height = live.highestBlock(x, z, true); + int heightWithFluid = live.highestBlock(x, z, false); return switch (spawner.group()) { case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); - case CAVE -> caveSpawnPosition(engine, chunkX, chunkZ); + case CAVE -> caveSpawnPosition(live, chunkX, chunkZ); case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); }; } - static BlockPosition caveSpawnPosition(Engine engine, int chunkX, int chunkZ) { - if (J.isFolia()) { - return null; - } - KList floors = engine.getMantle().findMarkers(chunkX, chunkZ, MarkerMatter.CAVE_FLOOR); - IrisPosition floor = floors.getRandom(RNG.r); - return floor == null ? null : new BlockPosition(floor.getX(), floor.getY() - engine.getMinHeight() + AIR_ABOVE_MARKER, floor.getZ()); + static BlockPosition caveSpawnPosition(LiveWorld live, int chunkX, int chunkZ) { + KList floors = new KList<>(live.caveFloors(chunkX, chunkZ)); + BlockPosition floor = floors.getRandom(RNG.r); + return floor == null ? null : new BlockPosition(floor.x(), floor.y() + AIR_ABOVE_MARKER, floor.z()); } - private Optional planMarker(PackWorld world, Engine engine, Marker marker) { - Spawner spawner = SpawnResources.spawner(engine.getData(), marker.spawner()); - SpawnMarker spawnMarker = SpawnResources.marker(engine.getData(), marker.marker()); + private Optional planMarker(PackWorld world, Marker marker) { + Spawner spawner = SpawnResources.spawner(world.resources(), marker.spawner()); + SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker()); if (spawner == null) { return Optional.empty(); } @@ -186,12 +192,13 @@ public final class EntitySpawning implements EntitySpawns { if (candidates.isEmpty()) { return Optional.empty(); } - EntitySpawn spawn = IRare.expandWeighted(candidates.stream().map(RareSpawn::new).toList()).getRandom().spawn(); + EntitySpawn spawn = RarityWeighting.expand(candidates, EntitySpawn::rarity).getRandom(); BlockPosition position = marker.position(); int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); - if (!SpawnerGate.canSpawn(marker.spawner(), spawner, engine, chunkX, chunkZ)) { + LiveWorld live = LiveWorld.of(world); + if (!SpawnerGate.canSpawn(marker.spawner(), spawner, live, chunkX, chunkZ)) { return Optional.empty(); } @@ -203,7 +210,7 @@ public final class EntitySpawning implements EntitySpawns { List attempts = new ArrayList<>(); BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); for (int i = 0; i < count; i++) { - addAttempt(attempts, world, engine, new Candidate(marker.spawner(), spawner, spawn), above, false); + addAttempt(attempts, world, new Candidate(marker.spawner(), spawner, spawn), above, false); } return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts)); } @@ -212,22 +219,23 @@ public final class EntitySpawning implements EntitySpawns { return marker.exhaustionChance() > RNG.r.nextDouble(); } - private void addAttempt(List attempts, PackWorld world, Engine engine, Candidate candidate, BlockPosition at, boolean checkSurface) { - EntityDefinition entity = SpawnResources.entity(engine.getData(), candidate.spawn().entity()); + private void addAttempt(List attempts, PackWorld world, Candidate candidate, BlockPosition at, boolean checkSurface) { + EntityDefinition entity = SpawnResources.entity(world.resources(), candidate.spawn().entity()); if (entity == null) { world.log().debug(" You are trying to spawn an entity that does not exist!"); return; } Range light = candidate.spawner().allowedLightLevels(); - EntitySpec spec = resolution(world, engine).resolve(entity, entityRandom(world).rng()); + EntitySpec spec = resolution(world).resolve(entity, entityRandom(world).rng()); attempts.add(new Attempt(at, spec, surfaceOf(entity.surface()), (int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface)); } - private static EntityResolution resolution(PackWorld world, Engine engine) { - LootItems items = new LootItems(world.resources().items(), engine.isStudio()); - return new EntityResolution(items, engine.getWorld().platformWorld(), world.state(EffectTimers.class, ignored -> new EffectTimers())); + private static EntityResolution resolution(PackWorld world) { + LiveWorld live = LiveWorld.of(world); + LootItems items = new LootItems(world.resources().items(), live.studio()); + return new EntityResolution(items, live.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers())); } private static EntityRandom entityRandom(PackWorld world) { @@ -238,10 +246,11 @@ public final class EntitySpawning implements EntitySpawns { return Surface.valueOf(surface.name()); } - /** The spawners an area lists, in a random order. */ - private static List shuffled(Engine engine, IrisRegistrant owner) { - List keys = owner.getModuleSettings().find(SpawnerSettings.class).map(SpawnerSettings::spawners).orElse(List.of()); - return new KList<>(SpawnResources.spawners(engine.getData(), keys)).shuffleCopy(RNG.r); + /** The spawners the dimension, region or surface biome at the column lists, in a random order. */ + private static List shuffled(PackWorld world, LiveWorld live, Level level, int x, int z) { + List keys = live.settings(SpawnerSettings.class, level, x, LAYOUT_QUESTION_HEIGHT, z) + .map(SpawnerSettings::spawners).orElse(List.of()); + return new KList<>(SpawnResources.spawners(world.resources(), keys)).shuffleCopy(RNG.r); } private static Stream spawnsOf(KeyedSpawner keyed, boolean initial) { @@ -250,35 +259,31 @@ public final class EntitySpawning implements EntitySpawns { } /** A spawn of a spawner, which picks as often as the spawn's rarity says. */ - private record Candidate(String key, Spawner spawner, EntitySpawn spawn) implements IRare { - @Override - public int getRarity() { + private record Candidate(String key, Spawner spawner, EntitySpawn spawn) { + int rarity() { return spawn.rarity(); } } - /** A spawn that picks as often as its rarity says. */ - private record RareSpawn(EntitySpawn spawn) implements IRare { - @Override - public int getRarity() { - return spawn.rarity(); - } - } - - private static Engine engine(PackWorld world) { - return IrisPackWorld.of(world).engine(); - } - /** The random stream entities are made from, seeded from the world like Iris always seeded it; one per world. */ private static final class EntityRandom { private final RNG rng; private EntityRandom(PackWorld world) { - this.rng = new RNG(IrisPackWorld.of(world).engine().getSeedManager().getEntity()); + this.rng = new RNG(IrisSeed.ENTITY.of(world)); } private RNG rng() { return rng; } } + + /** When the world's spawner cooldowns were last tidied. */ + private static final class CooldownCleanup { + private final ChronoLatch latch = new ChronoLatch(COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS); + + private boolean due() { + return latch.flip(); + } + } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java b/src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java new file mode 100644 index 000000000..6e700e3cf --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/RarityWeighting.java @@ -0,0 +1,53 @@ +/* + * 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.spawn; + +import art.arcane.volmlib.util.collection.KList; + +import java.util.List; +import java.util.function.ToIntFunction; + +/** + * Applies rarity to a pick: each possibility appears in the expansion as often as its rarity says, so picking one at + * random from the expansion picks the rarer ones less often. Spawner choices go through this once; rarity must never be + * applied a second time per spawn position. + */ +final class RarityWeighting { + private static final int MINIMUM_RARITY = 1; + + private RarityWeighting() { + } + + /** Each of {@code possibilities} repeated total/rarity times, where a rarity below 1 counts as 1. */ + static KList expand(List possibilities, ToIntFunction rarity) { + KList expanded = new KList<>(); + int totalRarity = 0; + for (T possibility : possibilities) { + totalRarity += rarityOf(possibility, rarity); + } + for (T possibility : possibilities) { + expanded.addMultiple(possibility, totalRarity / rarityOf(possibility, rarity)); + } + return expanded; + } + + private static int rarityOf(T possibility, ToIntFunction rarity) { + return Math.max(MINIMUM_RARITY, rarity.applyAsInt(possibility)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java index f7616adef..a7c565c79 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java @@ -18,11 +18,11 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.spawn.SpawnTimeBlock; import art.arcane.iris.builtin.spawn.SpawnWeather; -import art.arcane.iris.spi.PlatformWorld; -/** The time of day and the weather a command or spawner of the pack asks for, checked against a world. */ +/** The time of day and the weather a command or spawner of the pack asks for, checked against a world's sky. */ final class SpawnConditions { private static final double TICKS_PER_HOUR = 1000D; private static final double HOURS_AT_TIME_ZERO = 6; @@ -31,12 +31,12 @@ final class SpawnConditions { private SpawnConditions() { } - static boolean allow(SpawnTimeBlock time, SpawnWeather weather, PlatformWorld world) { - return time.contains(hourOf(world)) && weather.matches(world.isStorming(), world.isThundering()); + static boolean allow(SpawnTimeBlock time, SpawnWeather weather, Sky sky) { + return time.contains(hourOf(sky)) && weather.matches(sky.storming(), sky.thundering()); } /** The world's time of day as a clock hour: tick 0 is 6 in the morning. */ - static double hourOf(PlatformWorld world) { - return ((world.getTime() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY; + static double hourOf(Sky sky) { + return ((sky.time() / TICKS_PER_HOUR) + HOURS_AT_TIME_ZERO) % HOURS_PER_DAY; } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index e219c7b2f..96e08b52f 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.builtin.spawn.PlacementMarker; import art.arcane.iris.builtin.spawn.SpawnerSettings; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; @@ -50,6 +51,7 @@ public final class SpawnModule implements IrisModule { public void register(FeatureRegistry registry) { registry.registerSettings(SpawnerSettings.class); registry.registerSettings(EffectSettings.class); + registry.registerHeldType(PlacementMarker.class); SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); registry.registerService(AmbientEffects.class, new AmbientEffecting()); diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java index fa12eefd2..b90cd5232 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java @@ -21,8 +21,7 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.Spawner; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackResources; +import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; @@ -57,23 +56,23 @@ public final class SpawnResources { return List.of(SPAWNERS, ENTITIES, MARKERS); } - public static Spawner spawner(IrisData data, String key) { - return find(data, SPAWNERS, key); + public static Spawner spawner(PackResources resources, String key) { + return find(resources, SPAWNERS, key); } - public static EntityDefinition entity(IrisData data, String key) { - return find(data, ENTITIES, key); + public static EntityDefinition entity(PackResources resources, String key) { + return find(resources, ENTITIES, key); } - public static SpawnMarker marker(IrisData data, String key) { - return find(data, MARKERS, key); + public static SpawnMarker marker(PackResources resources, String key) { + return find(resources, MARKERS, key); } /** The spawners of the pack named by {@code keys}, in order, without the ones the pack lacks. */ - public static List spawners(IrisData data, List keys) { + public static List spawners(PackResources resources, List keys) { List spawners = new ArrayList<>(); for (String key : keys) { - Spawner spawner = spawner(data, key); + Spawner spawner = spawner(resources, key); if (spawner != null) { spawners.add(new KeyedSpawner(key, spawner)); } @@ -82,25 +81,24 @@ public final class SpawnResources { } /** The key of every entity of the pack, in key order. */ - public static List entityKeys(IrisData data) { - return keys(data, ENTITIES); + public static List entityKeys(PackResources resources) { + return keys(resources, ENTITIES); } /** The key of every spawner of the pack, in key order. */ - public static List spawnerKeys(IrisData data) { - return keys(data, SPAWNERS); + public static List spawnerKeys(PackResources resources) { + return keys(resources, SPAWNERS); } /** The key of every marker of the pack, in key order. */ - public static List markerKeys(IrisData data) { - return keys(data, MARKERS); + public static List markerKeys(PackResources resources) { + return keys(resources, MARKERS); } - private static T find(IrisData data, ResourceKind kind, String key) { + private static T find(PackResources resources, ResourceKind kind, String key) { if (key == null || key.isBlank()) { return null; } - IrisPackResources resources = data.getPackResources(); try { return resources.find(kind.key(resources.idOf(key))).orElse(null); } catch (IllegalStateException failedToLoad) { @@ -109,7 +107,7 @@ public final class SpawnResources { } /** 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 data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); + private static List keys(PackResources resources, ResourceKind kind) { + return resources.ids(kind.type()).stream().map(ResourceId::path).toList(); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java index 74bbfb95b..1327251af 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java @@ -18,34 +18,36 @@ package art.arcane.iris.engine.spawn; +import art.arcane.iris.builtin.LiveWorld; +import art.arcane.iris.builtin.LiveWorld.BiomeKind; +import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.spawn.SpawnRate; +import art.arcane.iris.builtin.spawn.SpawnCooldowns; import art.arcane.iris.builtin.spawn.Spawner; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.spi.PlatformWorld; + +import java.util.Optional; /** * Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not - * more often than its rates allow. The rates count in the engine's persisted data, by the key the pack names the - * spawner by. + * more often than its rates allow. The rates count in the world's data, by the key the pack names the spawner by. */ final class SpawnerGate { private SpawnerGate() { } - /** Whether a spawner of this group fires in {@code biome}. */ - static boolean suits(Spawner spawner, IrisBiome biome) { + /** Whether a spawner of this group fires in a biome of {@code kind}. */ + static boolean suits(Spawner spawner, BiomeKind kind) { return switch (spawner.group()) { - case NORMAL -> switch (biome.getInferredType()) { + case NORMAL -> switch (kind) { case SHORE, SEA, CAVE -> false; case LAND -> true; }; case CAVE -> true; - case UNDERWATER -> switch (biome.getInferredType()) { + case UNDERWATER -> switch (kind) { case SHORE, LAND, CAVE -> false; case SEA -> true; }; - case BEACH -> switch (biome.getInferredType()) { + case BEACH -> switch (kind) { case SHORE -> true; case LAND, CAVE, SEA -> false; }; @@ -53,45 +55,45 @@ final class SpawnerGate { } /** Whether the world is in the time and weather the spawner asks for. */ - static boolean suits(Spawner spawner, PlatformWorld world) { - return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), world); + static boolean suits(Spawner spawner, Sky sky) { + return SpawnConditions.allow(spawner.timeBlock(), spawner.weather(), sky); } /** Whether the spawner may fire in the chunk now. */ - static boolean canSpawn(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) { - if (!canSpawn(key, spawner, engine)) { + static boolean canSpawn(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) { + if (!canSpawn(key, spawner, live)) { return false; } SpawnRate rate = spawner.maximumRatePerChunk(); - return rate.isInfinite() || engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).canSpawn(rate.interval()); + return rate.isInfinite() || live.spawnCooldowns().canSpawnInChunk(chunkX, chunkZ, key, rate.interval()); } /** Counts a spawn of the spawner in the chunk against its rates. */ - static void spawned(String key, Spawner spawner, Engine engine, int chunkX, int chunkZ) { - spawned(key, spawner, engine); + static void spawned(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) { + spawned(key, spawner, live); if (spawner.maximumRatePerChunk().isInfinite()) { return; } - engine.getEngineData().getChunk(chunkX, chunkZ).getCooldown(key).spawn(); + live.spawnCooldowns().spawnedInChunk(chunkX, chunkZ, key); } - private static boolean canSpawn(String key, Spawner spawner, Engine engine) { - PlatformWorld world = engine.getWorld().platformWorld(); - if (world == null || !suits(spawner, world)) { + private static boolean canSpawn(String key, Spawner spawner, LiveWorld live) { + Optional sky = live.sky(); + if (sky.isEmpty() || !suits(spawner, sky.get())) { return false; } SpawnRate rate = spawner.maximumRate(); - return rate.isInfinite() || engine.getEngineData().getCooldown(key).canSpawn(rate.interval()); + return rate.isInfinite() || live.spawnCooldowns().canSpawn(key, rate.interval()); } - private static void spawned(String key, Spawner spawner, Engine engine) { + private static void spawned(String key, Spawner spawner, LiveWorld live) { if (spawner.maximumRate().isInfinite()) { return; } - engine.getEngineData().getCooldown(key).spawn(); + live.spawnCooldowns().spawned(key); } } From b59538ca6f0af4e3b2f02823f0c6bed2436cf667 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:01:13 +0200 Subject: [PATCH 072/139] iris:deposit ported onto IrisApi and listed in the built-ins jar --- builtin-modules.txt | 4 + .../art/arcane/iris/builtin/IrisSeed.java | 2 +- .../iris/engine/modifier/DepositClump.java | 70 +++ .../iris/engine/modifier/DepositModule.java | 8 +- .../iris/engine/modifier/DepositPlacer.java | 488 ++++++++++-------- .../iris/engine/modifier/ResolvedDeposit.java | 136 +++-- .../modifier/ResolvedDepositVariant.java | 45 +- 7 files changed, 453 insertions(+), 300 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/modifier/DepositClump.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..7691fee17 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,7 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.modifier.DepositModule +include art/arcane/iris/engine/modifier/DepositPlacer*.class +include art/arcane/iris/engine/modifier/DepositClump*.class +include art/arcane/iris/engine/modifier/ResolvedDeposit*.class diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeed.java b/src/main/java/art/arcane/iris/builtin/IrisSeed.java index 9e589b67e..9f141f2d8 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisSeed.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeed.java @@ -27,7 +27,7 @@ import com.volmit.world.PackWorld; * from {@link PackWorld#seed()}. */ public enum IrisSeed { - BIOME, CARVE, COMPONENT, DECORATOR, DEPOSIT, ENTITY, LOOT, MANTLE, POST, TERRAIN; + BIOME, CARVE, COMPLEX, COMPONENT, DECORATOR, DEPOSIT, ENTITY, LOOT, MANTLE, POST, TERRAIN; /** This seed of {@code world}, which must be a world Iris generates. */ public long of(PackWorld world) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositClump.java b/src/main/java/art/arcane/iris/engine/modifier/DepositClump.java new file mode 100644 index 000000000..4f72c2a5a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositClump.java @@ -0,0 +1,70 @@ +/* + * 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.modifier; + +import art.arcane.volmlib.util.data.VectorMap; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; + +/** + * The blocks of one deposit clump, around its centre. Blocks are kept in a {@link VectorMap} of positions relative to the centre, + * which is how Iris always held a clump, so a clump's blocks come in the same order and a chunk's deposits draw the same random + * numbers. + */ +final class DepositClump { + private final int width; + private final int height; + private final int depth; + private final Vector3i center; + private final VectorMap blocks = new VectorMap<>(); + + DepositClump(int width, int height, int depth) { + this.width = width; + this.height = height; + this.depth = depth; + this.center = new Vector3i(width / 2, height / 2, depth / 2); + } + + /** How many blocks wide the clump's box is, along X. */ + int width() { + return width; + } + + Vector3i center() { + return center; + } + + /** The clump's blocks by their position relative to its centre. */ + VectorMap blocks() { + return blocks; + } + + /** Puts {@code block} at {@code x}, {@code y}, {@code z} counted from the corner of the clump's box. */ + void setFromCorner(int x, int y, int z, BlockState block) { + if (x >= width || y >= height || z >= depth) { + throw new IllegalArgumentException(x + " " + y + " " + z + " exceeds limit of " + width + " " + height + " " + depth); + } + blocks.put(new IrisBlockVector(x - center.getX(), y - center.getY(), z - center.getZ()), block); + } + + /** Puts {@code block} on the centre, which is where a one block clump has its block. */ + void setCentre(BlockState block) { + blocks.put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), block); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index 668755e37..64b521cf8 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -24,7 +24,6 @@ import art.arcane.iris.builtin.deposit.DepositSettings; import art.arcane.iris.builtin.deposit.DepositVariantSettings; import art.arcane.iris.builtin.deposit.OreFrequencySettings; import art.arcane.iris.builtin.deposit.OreSizeSettings; -import art.arcane.iris.core.modules.IrisChunk; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -45,7 +44,6 @@ import java.util.List; public final class DepositModule implements IrisModule { private static final String VERSION = "built-in"; private static final int CHUNK_CENTRE = 7; - private static final int CHUNK_SHIFT = 4; @Override public ModuleInfo info() { @@ -69,13 +67,11 @@ public final class DepositModule implements IrisModule { } private static void place(ChunkStageContext context, List> inChunk) { - IrisChunk chunk = IrisChunk.current(); List generators = generatorsAtCentre(context.settings(), context.originX(), context.originZ()); - if (generators.isEmpty() || chunk.bypassesMantleStages()) { + if (generators.isEmpty()) { return; } - chunk.state(DepositPlacer.class, DepositPlacer::new).generate(generators, chunk.blocks(), - chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, chunk.multicore(), chunk.context()); + DepositPlacer.of(context.world()).generate(context, generators); } /** Every level's generators at the centre column of the chunk whose first block is {@code originX}, {@code originZ}, in level order. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index b5f38119f..f611b34f8 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,9 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositHeightDistribution; import art.arcane.iris.builtin.deposit.DepositPlacementScope; @@ -25,213 +25,341 @@ import art.arcane.iris.builtin.deposit.DepositVariant; import art.arcane.iris.builtin.deposit.DepositVariantSettings; import art.arcane.iris.builtin.deposit.OreFrequencySettings; import art.arcane.iris.builtin.deposit.OreSizeSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedComponent; -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.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.volmlib.util.data.HeightMap; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.iris.engine.modifier.ResolvedDeposit.BiomeIdentity; +import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.iris.util.common.parallel.BurstExecutor; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; +import com.volmit.FeatureAttachment.Target; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.MantleLayer; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKey; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.function.Supplier; /** - * Places deposit clumps into one chunk for {@link DepositModule}: one per engine runtime, holding the deposit - * stream's random and each generator made ready for this engine ({@link ResolvedDeposit}: resolved blocks and clump - * shapes). Each generator gets its own random, derived from the chunk and its position in the list. + * Places deposit clumps into one chunk for {@link DepositModule}: one per world, holding the deposit stream's random and each + * generator made ready for this world ({@link ResolvedDeposit}: resolved blocks and clump shapes). Each generator gets its own + * random, derived from the chunk and its position in the list, and the generators of a chunk run one after the other. */ -public class DepositPlacer extends EngineAssignedComponent { - private final RNG rng; +final class DepositPlacer { private static final double UNCHANGED_ORE_MULTIPLIER = 1D; + private static final int CHUNK_SHIFT = 4; + private static final int CHUNK_WIDTH = 16; + private static final long CHUNK_X_SEED_FACTOR = 341873128712L; + private static final long CHUNK_Z_SEED_FACTOR = 132897987541L; + private static final int DEFAULT_SURFACE_CLEARANCE = 7; + private static final BlockState BEDROCK = new BlockState("minecraft:bedrock"); + private final RNG rng; + private final BlockRegistry registry; + private final PackResources resources; + private final ModuleLog log; + private final boolean tunesOres; + private final boolean remapsOres; private final Map resolved = new ConcurrentHashMap<>(); private final Map variants = new ConcurrentHashMap<>(); + private final Map> biomeIdentities = new ConcurrentHashMap<>(); - public DepositPlacer(Engine engine) { - super(engine, "Deposit"); - rng = new RNG(getEngine().getSeedManager().getDeposit()); + DepositPlacer(PackWorld world) { + this.rng = new RNG(IrisSeed.DEPOSIT.of(world)); + this.resources = world.resources(); + this.registry = resources.blocks(); + this.log = world.log(); + this.tunesOres = declares(world, OreFrequencySettings.class) || declares(world, OreSizeSettings.class); + this.remapsOres = declares(world, DepositVariantSettings.class); } - /** Runs {@code generators}, in order, on the chunk at chunk coordinates {@code x}, {@code z}. */ - public void generate(List generators, Hunk terrain, int x, int z, boolean multicore, - ChunkContext context) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - generateDeposits(generators, terrain, x, z, multicore, context); - getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); + /** The world's deposit placer, kept in its state store. */ + static DepositPlacer of(PackWorld world) { + return world.state(DepositPlacer.class, DepositPlacer::new); } - private void generateDeposits(List generators, Hunk terrain, int x, int z, - boolean multicore, ChunkContext context) { - BurstExecutor burst = burst().burst(multicore); + /** Whether any level of the pack declares {@code settings}; a world that declares none never asks a biome for them. */ + private static boolean declares(PackWorld world, Class settings) { + return !world.settings().declared(settings).isEmpty(); + } - long seed = x * 341873128712L + z * 132897987541L; + /** Runs {@code generators}, in order, on the chunk of {@code context}. */ + void generate(ChunkStageContext context, List generators) { + Placing placing = new Placing(context); + int chunkX = context.originX() >> CHUNK_SHIFT; + int chunkZ = context.originZ() >> CHUNK_SHIFT; + long seed = chunkX * CHUNK_X_SEED_FACTOR + chunkZ * CHUNK_Z_SEED_FACTOR; long mask = 0; - MantleChunk chunk = getEngine().getMantle().getMantle().getChunk(x, z).use(); - try { - for (DepositGenerator k : generators) { - long finalSeed = seed * ++mask; - burst.queue(() -> generate(k, chunk, terrain, rng.nextParallelRNG(finalSeed), x, z, false, context)); - } - } finally { - // complete() must run before release() even when queueing throws — already - // submitted burst tasks must never write into a released chunk. - try { - burst.complete(); - } finally { - chunk.release(); - } + for (DepositGenerator generator : generators) { + long finalSeed = seed * ++mask; + placing.generate(generator, rng.nextParallelRNG(finalSeed)); } } - public void generate(DepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, ChunkContext context) { - generate(k, chunk, data, rng, cx, cz, safe, null, context); + private ResolvedDeposit resolved(DepositGenerator generator) { + return resolved.computeIfAbsent(generator, ignored -> new ResolvedDeposit(generator, rng.getSeed(), registry)); } - public void generate(DepositGenerator k, MantleChunk chunk, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he, ChunkContext context) { - ResolvedDeposit deposit = resolved(k); - if (k.spawnChance() < rng.d()) - return; + private Optional identityOf(ResourceId biome) { + return biomeIdentities.computeIfAbsent(biome, id -> resources.find(new ResourceKey<>(id, PackBiome.class)) + .map(found -> new BiomeIdentity(id.path(), found.platformBiome().toString(), found.vanillaBiome().toString()))); + } - for (int l = 0; l < rng.i(k.minPerChunk(), k.maxPerChunk() + 1); l++) { - if (k.perClumpSpawnChance() < rng.d()) - continue; + /** Places deposits into one chunk, with the views of its invocation. */ + private final class Placing { + private final Hunk blocks; + private final TerrainSampler terrain; + private final FeatureSettings settings; + private final MantleLayer caverns; + private final int originX; + private final int originZ; + private final int worldHeight; + private final int minWorldY; + private final int[] surfaceHeights = new int[CHUNK_WIDTH * CHUNK_WIDTH]; + private boolean surfaceKnown; + private final Map airStates = new IdentityHashMap<>(); + private final Map replaceableStates = new IdentityHashMap<>(); + private final Map> suitedOres = new IdentityHashMap<>(); - IrisObject clump = deposit.clump(rng); + Placing(ChunkStageContext context) { + this.blocks = context.hunk(BlockState.class); + this.terrain = context.terrain(); + this.settings = context.settings(); + this.caverns = context.mantle().caverns(); + this.originX = context.originX(); + this.originZ = context.originZ(); + this.worldHeight = blocks.getHeight(); + this.minWorldY = terrain.minWorldY(); + } - int dim = clump.getW(); - int min = dim / 2; - int max = (int) (16D - dim / 2D); + void generate(DepositGenerator k, RNG rng) { + ResolvedDeposit deposit = resolved(k); + if (k.spawnChance() < rng.d()) + return; - if (min > max || min < 0 || max > 15) { - min = 6; - max = 9; - } + for (int l = 0; l < rng.i(k.minPerChunk(), k.maxPerChunk() + 1); l++) { + if (k.perClumpSpawnChance() < rng.d()) + continue; - int x = rng.i(min, max + 1); - int z = rng.i(min, max + 1); - int terrainSurface = getDepositTerrainSurface(cx, cz, x, z, he, context); - int height = k.placementScope() == DepositPlacementScope.TERRAIN - ? depositSurfaceLimit(terrainSurface, k.surfaceClearance()) - : getEngine().getHeight() - 1; + DepositClump clump = deposit.clump(rng); - if (height < 0) { - continue; - } + int dim = clump.width(); + int min = dim / 2; + int max = (int) (16D - dim / 2D); - int y = sampleHeight( - k.heightDistribution(), rng, k.minHeight(), k.maxHeight(), - Math.min(height, getEngine().getHeight() - 1)); - if (y == Integer.MIN_VALUE) { - continue; - } + if (min > max || min < 0 || max > 15) { + min = 6; + max = 9; + } - boolean clippedHeight = k.heightDistribution() == DepositHeightDistribution.CLIPPED_UNIFORM; - if (clippedHeight && y > height - 2) - continue; + int x = rng.i(min, max + 1); + int z = rng.i(min, max + 1); + int terrainSurface = terrainSurface(x, z); + int height = k.placementScope() == DepositPlacementScope.TERRAIN + ? depositSurfaceLimit(terrainSurface, k.surfaceClearance()) + : worldHeight - 1; - int biomeY = Math.max(0, Math.min(getEngine().getHeight() - 1, y)); - boolean oreDeposit = deposit.isOre(); - IrisBiome surfaceBiome = context.getBiome().get(x, z); - IrisBiome depositBiome = oreDeposit || k.usesCaveBiomeFilter() - ? getEngine().getCaveBiome((cx << 4) + x, biomeY, (cz << 4) + z) - : null; - if (!deposit.matchesBiome(surfaceBiome, depositBiome)) { - continue; - } + if (height < 0) { + continue; + } - if (oreDeposit) { - if (depositBiome != null) { - double frequencyMultiplier = oreFrequencyMultiplier(depositBiome); - if (frequencyMultiplier < 1D - && !passesOreFrequency(frequencyMultiplier, rng.d())) { - continue; - } + int y = sampleHeight( + k.heightDistribution(), rng, k.minHeight(), k.maxHeight(), + Math.min(height, worldHeight - 1)); + if (y == Integer.MIN_VALUE) { + continue; + } - double sizeMultiplier = oreSizeMultiplier(depositBiome); - if (sizeMultiplier != 1D) { - IrisObject scaledClump = deposit.clump(rng, sizeMultiplier); - int scaledDimension = scaledClump.getW(); - x = clampDepositCenter(x, scaledDimension, 16); - if (clippedHeight) { - y = clampDepositCenter(y, scaledDimension, getEngine().getHeight()); + boolean clippedHeight = k.heightDistribution() == DepositHeightDistribution.CLIPPED_UNIFORM; + if (clippedHeight && y > height - 2) + continue; + + int biomeY = Math.max(0, Math.min(worldHeight - 1, y)); + boolean oreDeposit = deposit.isOre(); + Supplier biomes = biomesAt(x, biomeY, z); + if (!deposit.matchesBiome(() -> identityOf(biomes.get().surfaceBiome()).orElse(null), + () -> biomes.get().caveBiome().flatMap(id -> identityOf(id)).orElse(null))) { + continue; + } + + if (oreDeposit && tunesOres) { + Optional caveBiome = biomes.get().caveBiome(); + if (caveBiome.isPresent()) { + double frequencyMultiplier = oreFrequencyMultiplier(caveBiome.get()); + if (frequencyMultiplier < 1D + && !passesOreFrequency(frequencyMultiplier, rng.d())) { + continue; + } + + double sizeMultiplier = oreSizeMultiplier(caveBiome.get()); + if (sizeMultiplier != 1D) { + DepositClump scaledClump = deposit.clump(rng, sizeMultiplier); + int scaledDimension = scaledClump.width(); + x = clampDepositCenter(x, scaledDimension, 16); + if (clippedHeight) { + y = clampDepositCenter(y, scaledDimension, worldHeight); + } + z = clampDepositCenter(z, scaledDimension, 16); + clump = scaledClump; } - z = clampDepositCenter(z, scaledDimension, 16); - clump = scaledClump; } } + + placeClump(k, deposit, clump, rng, x, y, z); } + } - IrisDimension dimension = getDimension(); - - for (art.arcane.volmlib.util.math.IrisBlockVector j : clump.getBlocks().keys()) { + private void placeClump(DepositGenerator k, ResolvedDeposit deposit, DepositClump clump, RNG rng, int x, int y, int z) { + for (IrisBlockVector j : clump.blocks().keys()) { int nx = j.getBlockX() + x; int ny = j.getBlockY() + y; int nz = j.getBlockZ() + z; - if (nx > 15 || nx < 0 || ny >= getEngine().getHeight() || ny < 0 || nz < 0 || nz > 15) { + if (nx > 15 || nx < 0 || ny >= worldHeight || ny < 0 || nz < 0 || nz > 15) { continue; } - int columnSurface = getDepositTerrainSurface(cx, cz, nx, nz, he, context); + int columnSurface = terrainSurface(nx, nz); if (!placementSurfaceAllows( k.placementScope(), ny, columnSurface, k.surfaceClearance())) { continue; } - PlatformBlockState current = data.get(nx, ny, nz); - if (!canReplaceDepositTarget(current)) { + BlockState current = blocks.get(nx, ny, nz); + if (!canReplaceTarget(current)) { continue; } if (!deposit.canReplace(current)) { continue; } - if (!k.replaceBedrock() && IrisProceduralBlocks.materialKey(current).equals("minecraft:bedrock")) { + if (!k.replaceBedrock() && current.material().equals(BEDROCK.material())) { continue; } if (shouldDiscardExposed( - k.discardChanceOnAirExposure(), rng.d(), isAdjacentToAir(data, nx, ny, nz))) { + k.discardChanceOnAirExposure(), rng.d(), isAdjacentToAir(blocks, nx, ny, nz, this::isAir))) { continue; } - if (chunk.get(nx, ny, nz, MatterCavern.class) == null) { - PlatformBlockState ore = clump.getBlocks().get(j); - PlatformBlockState remapped = resolveDepositVariant( - cx, cz, nx, ny, nz, ore, dimension, context); - PlatformBlockState finalBlock = remapped != null + if (caverns.get(originX + nx, ny, originZ + nz) == null) { + BlockState ore = clump.blocks().get(j); + BlockState remapped = remapped(nx, ny, nz, ore); + BlockState finalBlock = remapped != null ? remapped - : B.toDeepSlateOre(current, ore); - data.set(nx, ny, nz, finalBlock); + : oreSuiting(current, ore); + blocks.set(nx, ny, nz, finalBlock); } } } - } - private ResolvedDeposit resolved(DepositGenerator generator) { - return resolved.computeIfAbsent(generator, ignored -> ResolvedDeposit.of(generator, getEngine())); - } + /** Asks the host for the biomes of the column only if a filter or an ore tuning reads them, and only once. */ + private Supplier biomesAt(int localX, int y, int localZ) { + BiomeSample[] sample = new BiomeSample[1]; + return () -> { + if (sample[0] == null) { + sample[0] = terrain.biome(originX + localX, y, originZ + localZ); + } + return sample[0]; + }; + } - private int getDepositTerrainSurface( - int cx, int cz, int localX, int localZ, HeightMap heightMap, - ChunkContext context) { - return heightMap != null - ? heightMap.getHeight((cx << 4) + localX, (cz << 4) + localZ) - : context.getRoundedHeight(localX, localZ); + /** {@code ore}, or the variant of it that suits the rock it replaces; the platform knows the variants, so each pair is asked once. */ + private BlockState oreSuiting(BlockState rock, BlockState ore) { + return suitedOres.computeIfAbsent(rock, known -> new IdentityHashMap<>()) + .computeIfAbsent(ore, known -> registry.oreFor(rock, known)); + } + + private boolean isAir(BlockState state) { + return airStates.computeIfAbsent(state, known -> registry.hasTrait(known, BlockTrait.AIR)); + } + + private boolean canReplaceTarget(BlockState state) { + return replaceableStates.computeIfAbsent(state, known -> canReplaceDepositTarget(registry, known)); + } + + /** The height of the terrain at a column of the chunk, as the stages before the deposits see it. */ + private int terrainSurface(int localX, int localZ) { + if (!surfaceKnown) { + for (int x = 0; x < CHUNK_WIDTH; x++) { + for (int z = 0; z < CHUNK_WIDTH; z++) { + surfaceHeights[x * CHUNK_WIDTH + z] = (int) Math.round(terrain.surfaceY(originX + x, originZ + z)); + } + } + surfaceKnown = true; + } + return surfaceHeights[localX * CHUNK_WIDTH + localZ]; + } + + private BlockState remapped(int localX, int localY, int localZ, BlockState ore) { + if (!remapsOres) { + return null; + } + int worldX = originX + localX; + int worldZ = originZ + localZ; + int worldY = absoluteWorldY(minWorldY, localY); + + Optional caveBiome = terrain.biome(worldX, localY, worldZ).caveBiome(); + if (caveBiome.isPresent()) { + BlockState match = matchDepositVariant(settings.declaredBy(caveBiome.get(), DepositVariantSettings.class), ore, worldY); + if (match != null) { + return match; + } + } + + BlockState match = matchDepositVariant(levelSettings(Target.REGION, worldX, worldZ), ore, worldY); + if (match != null) { + return match; + } + + return matchDepositVariant(levelSettings(Target.DIMENSION, worldX, worldZ), ore, worldY); + } + + private Optional levelSettings(Target level, int worldX, int worldZ) { + return settings.at(DepositVariantSettings.class, worldX, worldZ).stream() + .filter(entry -> entry.level() == level) + .map(Entry::value) + .findFirst(); + } + + private BlockState matchDepositVariant(Optional owner, BlockState ore, int y) { + for (DepositVariant declared : owner.map(DepositVariantSettings::variants).orElse(List.of())) { + ResolvedDepositVariant variant = variants.computeIfAbsent(declared, rule -> new ResolvedDepositVariant(rule, registry, log)); + if (!variant.appliesAt(y)) { + continue; + } + + BlockState swapped = variant.remapOrNull(ore); + if (swapped != null) { + return swapped; + } + } + + return null; + } + + private double oreFrequencyMultiplier(ResourceId caveBiome) { + return settings.declaredBy(caveBiome, OreFrequencySettings.class).map(OreFrequencySettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); + } + + private double oreSizeMultiplier(ResourceId caveBiome) { + return settings.declaredBy(caveBiome, OreSizeSettings.class).map(OreSizeSettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); + } } static int depositSurfaceLimit(int surfaceY) { - return depositSurfaceLimit(surfaceY, 7); + return depositSurfaceLimit(surfaceY, DEFAULT_SURFACE_CLEARANCE); } static int depositSurfaceLimit(int surfaceY, int surfaceClearance) { @@ -252,8 +380,8 @@ public class DepositPlacer extends EngineAssignedComponent { return minHeight + localY; } - static boolean canReplaceDepositTarget(PlatformBlockState state) { - return state != null && !state.isAir() && !state.isFluid(); + static boolean canReplaceDepositTarget(BlockRegistry registry, BlockState state) { + return state != null && !registry.hasTrait(state, BlockTrait.AIR) && !registry.hasTrait(state, BlockTrait.FLUID); } static int sampleHeight( @@ -285,23 +413,22 @@ public class DepositPlacer extends EngineAssignedComponent { return adjacentToAir && chance > 0D && sample < Math.min(1D, chance); } - static boolean isAdjacentToAir(Hunk data, int x, int y, int z) { - return isAirAt(data, x - 1, y, z) - || isAirAt(data, x + 1, y, z) - || isAirAt(data, x, y - 1, z) - || isAirAt(data, x, y + 1, z) - || isAirAt(data, x, y, z - 1) - || isAirAt(data, x, y, z + 1); + static boolean isAdjacentToAir(Hunk data, int x, int y, int z, Predicate isAir) { + return isAirAt(data, x - 1, y, z, isAir) + || isAirAt(data, x + 1, y, z, isAir) + || isAirAt(data, x, y - 1, z, isAir) + || isAirAt(data, x, y + 1, z, isAir) + || isAirAt(data, x, y, z - 1, isAir) + || isAirAt(data, x, y, z + 1, isAir); } - private static boolean isAirAt(Hunk data, int x, int y, int z) { + private static boolean isAirAt(Hunk data, int x, int y, int z, Predicate isAir) { if (x < 0 || x >= data.getWidth() || y < 0 || y >= data.getHeight() || z < 0 || z >= data.getDepth()) { return false; } - PlatformBlockState state = data.getRaw(x, y, z); - return state == null || state.isAir(); + return isAir.test(data.get(x, y, z)); } static boolean passesOreFrequency(double multiplier, double sample) { @@ -313,63 +440,4 @@ public class DepositPlacer extends EngineAssignedComponent { int maximum = (int) (limit - dimension / 2D); return Math.max(minimum, Math.min(center, maximum)); } - - private PlatformBlockState resolveDepositVariant(int cx, int cz, int nx, int localY, int nz, PlatformBlockState ore, IrisDimension dimension, ChunkContext context) { - int worldX = (cx << 4) + nx; - int worldZ = (cz << 4) + nz; - int worldY = absoluteWorldY(getEngine().getMinHeight(), localY); - - IrisBiome biome = getEngine().getCaveBiome(worldX, localY, worldZ); - if (biome != null) { - PlatformBlockState match = matchDepositVariant(biome, ore, worldY); - if (match != null) { - return match; - } - } - - IrisRegion region = context.getRegion().get(nx, nz); - if (region != null) { - PlatformBlockState match = matchDepositVariant(region, ore, worldY); - if (match != null) { - return match; - } - } - - if (dimension != null) { - PlatformBlockState match = matchDepositVariant(dimension, ore, worldY); - if (match != null) { - return match; - } - } - - return null; - } - - private PlatformBlockState matchDepositVariant(IrisRegistrant owner, PlatformBlockState ore, int y) { - for (DepositVariant declared : variantsOf(owner)) { - ResolvedDepositVariant variant = variants.computeIfAbsent(declared, ResolvedDepositVariant::new); - if (!variant.appliesAt(y)) { - continue; - } - - PlatformBlockState swapped = variant.remapOrNull(ore); - if (swapped != null) { - return swapped; - } - } - - return null; - } - - private static List variantsOf(IrisRegistrant owner) { - return owner.getModuleSettings().find(DepositVariantSettings.class).map(DepositVariantSettings::variants).orElse(List.of()); - } - - private static double oreFrequencyMultiplier(IrisBiome biome) { - return biome.getModuleSettings().find(OreFrequencySettings.class).map(OreFrequencySettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); - } - - private static double oreSizeMultiplier(IrisBiome biome) { - return biome.getModuleSettings().find(OreSizeSettings.class).map(OreSizeSettings::multiplier).orElse(UNCHANGED_ORE_MULTIPLIER); - } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java index 889239fc8..4ca78c01b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java @@ -15,35 +15,31 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.deposit.DepositBiomeScope; import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositShape; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -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.volmlib.util.collection.KSet; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.resource.ResourceId; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; /** - * One {@link DepositGenerator} made ready for one engine: its palette resolved to the platform's blocks, whether it is - * an ore deposit, the blocks it may replace, and the clump shapes it places, built once per size. What the settings - * describe stays in the settings; everything that needs the platform, the pack or the world seed is here. + * One {@link DepositGenerator} made ready for one world: its palette resolved to blocks, whether it is an ore deposit, the blocks + * it may replace, and the clump shapes it places, built once per size. What the settings describe stays in the settings; + * everything that needs the pack or the world seed is here. */ final class ResolvedDeposit { private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; @@ -57,27 +53,18 @@ final class ResolvedDeposit { private final DepositGenerator generator; private final long depositSeed; - private final List palette; + private final List palette; private final boolean ore; - private final Set replaceableMaterials; - private final Map> clumps = new ConcurrentHashMap<>(); + private final Set replaceableMaterials; + private final Map> clumps = new ConcurrentHashMap<>(); - /** @param palette the generator's palette as the platform's blocks, in order */ - ResolvedDeposit(DepositGenerator generator, long depositSeed, List palette) { + /** @param registry the pack's blocks, which resolve the generator's palette and the blocks it may replace */ + ResolvedDeposit(DepositGenerator generator, long depositSeed, BlockRegistry registry) { this.generator = generator; this.depositSeed = depositSeed; - this.palette = List.copyOf(palette); - this.ore = palette.stream().anyMatch(PlatformBlockState::isOre); - this.replaceableMaterials = replaceableMaterials(generator.replaceableBlocks()); - } - - /** {@code generator} ready for {@code engine}: its blocks resolved through the pack, clumps seeded from the world's deposit seed. */ - static ResolvedDeposit of(DepositGenerator generator, Engine engine) { - BlockRegistry blocks = engine.getData().getPackResources().blocks(); - List palette = generator.palette().stream() - .map(spec -> B.getState(blocks.resolve(spec).key())) - .toList(); - return new ResolvedDeposit(generator, engine.getSeedManager().getDeposit(), palette); + this.palette = generator.palette().stream().map(registry::resolve).toList(); + this.ore = palette.stream().anyMatch(block -> registry.hasTrait(block, BlockTrait.ORE)); + this.replaceableMaterials = replaceableMaterials(registry, generator.replaceableBlocks()); } DepositGenerator generator() { @@ -90,13 +77,19 @@ final class ResolvedDeposit { } /** Whether the deposit may replace {@code state}: any block when it names none, otherwise only the named ones. */ - boolean canReplace(PlatformBlockState state) { - return generator.replaceableBlocks().isEmpty() || replaceableMaterials.contains(IrisProceduralBlocks.materialKey(state)); + boolean canReplace(BlockState state) { + return generator.replaceableBlocks().isEmpty() || replaceableMaterials.contains(state.material()); } - /** Whether the biome the generator's scope picks passes its include and exclude filters. */ - boolean matchesBiome(IrisBiome surfaceBiome, IrisBiome caveBiome) { - IrisBiome selected = generator.biomeScope() == DepositBiomeScope.SURFACE ? surfaceBiome : caveBiome; + /** + * Whether the biome the generator's scope picks passes its include and exclude filters. The biomes are asked for only when + * the generator has a filter, and a biome that is none (a dimension without cave biomes) matches no key. + */ + boolean matchesBiome(Supplier surfaceBiome, Supplier caveBiome) { + if (generator.includedBiomes().isEmpty() && generator.excludedBiomes().isEmpty()) { + return true; + } + BiomeIdentity selected = (generator.biomeScope() == DepositBiomeScope.SURFACE ? surfaceBiome : caveBiome).get(); if (!generator.includedBiomes().isEmpty() && !matchesAnyBiome(selected, generator.includedBiomes())) { return false; } @@ -104,12 +97,12 @@ final class ResolvedDeposit { } /** One clump to place, picked with {@code rng}. */ - IrisObject clump(RNG rng) { + DepositClump clump(RNG rng) { return clump(rng, generator.minSize(), generator.maxSize(), 0L); } /** One clump to place with every size scaled by {@code sizeMultiplier}, as a biome's ore size tuning asks. */ - IrisObject clump(RNG rng, double sizeMultiplier) { + DepositClump clump(RNG rng, double sizeMultiplier) { if (sizeMultiplier == 1D) { return clump(rng); } @@ -119,13 +112,13 @@ final class ResolvedDeposit { return clump(rng, minSize, maxSize, sizeSeed); } - private IrisObject clump(RNG rng, int minSize, int maxSize, long sizeSeed) { + private DepositClump clump(RNG rng, int minSize, int maxSize, long sizeSeed) { if (generator.shape() != DepositShape.IRIS) { return configuredClump(rng, minSize, maxSize); } - List variants = clumps.computeIfAbsent(new ClumpSizes(minSize, maxSize), sizes -> { + List variants = clumps.computeIfAbsent(new ClumpSizes(minSize, maxSize), sizes -> { RNG variantRng = new RNG(depositSeed + stableClumpSalt() + sizeSeed); - List built = new ArrayList<>(); + List built = new ArrayList<>(); for (int i = 0; i < generator.varience(); i++) { built.add(irisClump(variantRng.nextParallelRNG(VARIANT_SEED_STEP * i + VARIANT_SEED_OFFSET), sizes.minSize(), sizes.maxSize())); } @@ -155,7 +148,7 @@ final class ResolvedDeposit { hash = mix(hash, Double.doubleToLongBits(generator.perClumpSpawnChance())); hash = mix(hash, Double.doubleToLongBits(generator.discardChanceOnAirExposure())); hash = mix(hash, palette.size()); - for (PlatformBlockState block : palette) { + for (BlockState block : palette) { hash = mixString(hash, block == null ? null : block.key()); } hash = mix(hash, generator.varience()); @@ -193,7 +186,7 @@ final class ResolvedDeposit { return mixed; } - private IrisObject configuredClump(RNG rng, int minSize, int maxSize) { + private DepositClump configuredClump(RNG rng, int minSize, int maxSize) { int size = rng.i(minSize, maxSize + 1); return switch (generator.shape()) { case VANILLA_ELLIPSOID -> vanillaEllipsoid(rng, size); @@ -203,9 +196,9 @@ final class ResolvedDeposit { } /** Minecraft's ordinary ore vein: a chain of overlapping ellipsoids whose reach grows with {@code size}. */ - IrisObject vanillaEllipsoid(RNG rng, int size) { + DepositClump vanillaEllipsoid(RNG rng, int size) { if (size <= 0) { - return new IrisObject(1, 1, 1); + return new DepositClump(1, 1, 1); } float angle = rng.nextFloat() * (float) Math.PI; @@ -286,11 +279,11 @@ final class ResolvedDeposit { } } - return objectFromCells(cells, rng); + return clumpFromCells(cells, rng); } /** Minecraft's scattered ore: up to {@code size} candidate offsets, the later ones further from the centre. */ - IrisObject vanillaScattered(RNG rng, int size) { + DepositClump vanillaScattered(RNG rng, int size) { KSet cells = new KSet<>(); int candidates = rng.nextInt(Math.max(0, size) + 1); for (int i = 0; i < candidates; i++) { @@ -300,12 +293,12 @@ final class ResolvedDeposit { Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude), Math.round((rng.nextFloat() - rng.nextFloat()) * magnitude))); } - return objectFromCells(cells, rng); + return clumpFromCells(cells, rng); } - private IrisObject objectFromCells(KSet cells, RNG rng) { + private DepositClump clumpFromCells(KSet cells, RNG rng) { if (cells.isEmpty()) { - return new IrisObject(1, 1, 1); + return new DepositClump(1, 1, 1); } int minX = Integer.MAX_VALUE; @@ -326,25 +319,24 @@ final class ResolvedDeposit { int extentX = Math.max(Math.abs(minX), Math.abs(maxX)); int extentY = Math.max(Math.abs(minY), Math.abs(maxY)); int extentZ = Math.max(Math.abs(minZ), Math.abs(maxZ)); - IrisObject object = new IrisObject(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1); + DepositClump clump = new DepositClump(extentX * 2 + 1, extentY * 2 + 1, extentZ * 2 + 1); for (BlockPosition cell : cells) { - object.setUnsigned(cell.getX() + extentX, cell.getY() + extentY, cell.getZ() + extentZ, nextBlock(rng)); + clump.setFromCorner(cell.getX() + extentX, cell.getY() + extentY, cell.getZ() + extentZ, nextBlock(rng)); } - return object; + return clump; } /** The traditional Iris clump: a cube just large enough for the block count, filled at random cells. */ - private IrisObject irisClump(RNG rng, int minSize, int maxSize) { + private DepositClump irisClump(RNG rng, int minSize, int maxSize) { int remaining = rng.i(minSize, maxSize + 1); if (remaining == 1) { - IrisObject single = new IrisObject(1, 1, 1); - Vector3i center = single.getCenter(); - single.getBlocks().put(new IrisBlockVector(center.getX(), center.getY(), center.getZ()), nextBlock(rng)); + DepositClump single = new DepositClump(1, 1, 1); + single.setCentre(nextBlock(rng)); return single; } int dimension = Math.min(MAX_CLUMP_DIMENSION, (int) Math.ceil(Math.cbrt(remaining))); - IrisObject clump = new IrisObject(dimension, dimension, dimension); + DepositClump clump = new DepositClump(dimension, dimension, dimension); if (remaining >= dimension * dimension * dimension) { fillCube(clump, dimension, rng); return clump; @@ -357,45 +349,47 @@ final class ResolvedDeposit { continue; } remaining--; - clump.setUnsigned(cell.getX(), cell.getY(), cell.getZ(), nextBlock(rng)); + clump.setFromCorner(cell.getX(), cell.getY(), cell.getZ(), nextBlock(rng)); } return clump; } - private void fillCube(IrisObject clump, int dimension, RNG rng) { + private void fillCube(DepositClump clump, int dimension, RNG rng) { for (int z = 0; z < dimension; z++) { for (int y = 0; y < dimension; y++) { for (int x = 0; x < dimension; x++) { - clump.setUnsigned(x, y, z, nextBlock(rng)); + clump.setFromCorner(x, y, z, nextBlock(rng)); } } } } - private PlatformBlockState nextBlock(RNG rng) { + private BlockState nextBlock(RNG rng) { return palette.get(rng.i(0, palette.size())); } - private static Set replaceableMaterials(List keys) { - Set materials = new KSet<>(); + /** The materials of the blocks the pack names that this platform knows; a block it does not know replaces nothing. */ + private static Set replaceableMaterials(BlockRegistry registry, List keys) { + Set materials = new HashSet<>(); for (String key : keys) { - PlatformBlockState state = B.getStateOrNull(key, false); - if (state != null) { - materials.add(IrisProceduralBlocks.materialKey(state)); + try { + materials.add(registry.resolve(key).material()); + } catch (IllegalArgumentException unknownBlock) { + continue; } } return materials; } - private static boolean matchesAnyBiome(IrisBiome biome, List configuredBiomes) { + private static boolean matchesAnyBiome(BiomeIdentity biome, List configuredBiomes) { if (biome == null) { return false; } for (String configured : configuredBiomes) { String namespaced = configured.contains(":") ? configured : MINECRAFT_NAMESPACE + configured; - if (configured.equals(biome.getLoadKey()) - || namespaced.equals(biome.getDerivativeKey()) - || namespaced.equals(biome.getVanillaDerivativeKey())) { + if (configured.equals(biome.key()) + || namespaced.equals(biome.platformBiome()) + || namespaced.equals(biome.vanillaBiome())) { return true; } } @@ -405,4 +399,8 @@ final class ResolvedDeposit { /** The sizes one set of clump variants is built for: the generator's own, or scaled by a biome's ore tuning. */ record ClumpSizes(int minSize, int maxSize) { } + + /** What a deposit's biome filter compares: the pack key of a biome, the platform biome it is written as and the one vanilla sees. */ + record BiomeIdentity(String key, String platformBiome, String vanillaBiome) { + } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java index 5330b3b93..86da0bc29 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java @@ -15,17 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.deposit.DepositVariant; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.resource.ResourceId; import java.util.HashMap; import java.util.Map; +import java.util.Optional; /** * One {@link DepositVariant} made ready: its source and replacement block ids resolved to the platform's blocks, built once on @@ -33,10 +34,14 @@ import java.util.Map; */ final class ResolvedDepositVariant { private final DepositVariant settings; - private final AtomicCache> remapped = new AtomicCache<>(); + private final BlockRegistry registry; + private final ModuleLog log; + private final AtomicCache> remapped = new AtomicCache<>(); - ResolvedDepositVariant(DepositVariant settings) { + ResolvedDepositVariant(DepositVariant settings, BlockRegistry registry, ModuleLog log) { this.settings = settings; + this.registry = registry; + this.log = log; } boolean appliesAt(int worldY) { @@ -44,23 +49,35 @@ final class ResolvedDepositVariant { } /** The block {@code ore} is rewritten to, or null when the rule does not remap its material. */ - PlatformBlockState remapOrNull(PlatformBlockState ore) { + BlockState remapOrNull(BlockState ore) { if (ore == null || settings.remap().isEmpty()) { return null; } - return remapped.aquire(this::resolveRemap).get(IrisProceduralBlocks.materialKey(ore)); + return remapped.aquire(this::resolveRemap).get(ore.material()); } - private Map resolveRemap() { - Map resolved = new HashMap<>(); + private Map resolveRemap() { + Map resolved = new HashMap<>(); for (Map.Entry entry : settings.remap().entrySet()) { - PlatformBlockState source = B.getStateOrNull(entry.getKey(), false); - PlatformBlockState target = B.getStateOrNull(entry.getValue(), true); - if (source == null || target == null) { + Optional source = known(entry.getKey(), false); + Optional target = known(entry.getValue(), true); + if (source.isEmpty() || target.isEmpty()) { continue; } - resolved.put(IrisProceduralBlocks.materialKey(source), target); + resolved.put(source.get().material(), target.get()); } return resolved; } + + /** The block the platform has under {@code key}; a replacement it lacks is reported once. */ + private Optional known(String key, boolean reportMissing) { + try { + return Optional.of(registry.resolve(key)); + } catch (IllegalArgumentException unknownBlock) { + if (reportMissing) { + log.warnOnce("deposit-variant-block:" + key, "Deposit variant replaces ores with " + key + ", which this server does not have"); + } + return Optional.empty(); + } + } } From 75f3504ae7b902cddc81a291976a4a38feb49667 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:06:14 +0200 Subject: [PATCH 073/139] iris:structure answers the new structure services and keeps its locator indexes in world state StructureLocator.placed and VanillaStructures.startedStructures/locatableStarts/locateStart are answered from the module's placement index. The Caffeine caches and their invalidate() are gone: each world builds its index once in its state store, and a pack reload starts a new world. StructureReachability moves to Iris core, its only reader. --- source-patterns.txt | 1 - .../framework/IrisStructureLocator.java | 40 +++--- .../framework/StructureReachability.java | 127 ------------------ .../structure/StructureLocating.java | 10 +- .../structure/StructureVanillaStructures.java | 47 ++++++- .../mantle/components/StructureModule.java | 17 +-- 6 files changed, 81 insertions(+), 161 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureReachability.java diff --git a/source-patterns.txt b/source-patterns.txt index 00f98cd55..78bd0fcb1 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -10,7 +10,6 @@ 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/StructureReachability.java art/arcane/iris/engine/framework/StructurePlacementScope.java art/arcane/iris/engine/framework/StructurePlacementGrid.java art/arcane/iris/engine/framework/StructurePlacementMarker.java diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index dbfd240ee..f40dc0d7f 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -40,8 +40,6 @@ import art.arcane.iris.engine.object.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.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; import com.volmit.ModuleLog; import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; @@ -59,7 +57,7 @@ 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. * - * A per-engine index of placed keys is cached so {@code /locate} and {@code /iris goto} skip + * 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 @@ -75,9 +73,6 @@ public final class IrisStructureLocator { 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 Cache INDEX_CACHE = Caffeine.newBuilder().weakKeys().build(); - private static final Cache LOCATABLE_INDEX_CACHE = - Caffeine.newBuilder().weakKeys().build(); private static final PlacementIndex EMPTY_INDEX = new PlacementIndex( Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptyList()); @@ -99,6 +94,28 @@ public final class IrisStructureLocator { 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; @@ -168,13 +185,6 @@ public final class IrisStructureLocator { return index(engine).suppressedVanillaSources.contains(normalize(vanillaKey)); } - public static void invalidate(Engine engine) { - if (engine != null) { - INDEX_CACHE.invalidate(engine); - LOCATABLE_INDEX_CACHE.invalidate(engine); - } - } - public static boolean startsInChunk(Engine engine, String key, int cx, int cz) { if (!isPlaced(engine, key)) { return false; @@ -1057,14 +1067,14 @@ public final class IrisStructureLocator { if (engine.getData() == null || engine.getDimension() == null) { throw new IllegalStateException("Iris structure index requires a fully bound engine and dimension"); } - return INDEX_CACHE.get(engine, ignored -> build(engine)); + return engine.getGeneration().state(PlacementIndex.class, IrisStructureLocator::build); } private static LocatableIndex locatableIndex(Engine engine) { if (engine == null) { return EMPTY_LOCATABLE_INDEX; } - return LOCATABLE_INDEX_CACHE.get(engine, ignored -> buildLocatableIndex(engine)); + return engine.getGeneration().state(LocatableIndex.class, IrisStructureLocator::buildLocatableIndex); } private static LocatableIndex buildLocatableIndex(Engine engine) { diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureReachability.java b/src/main/java/art/arcane/iris/engine/framework/StructureReachability.java deleted file mode 100644 index 15910aa36..000000000 --- a/src/main/java/art/arcane/iris/engine/framework/StructureReachability.java +++ /dev/null @@ -1,127 +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.world.IrisWorld; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.volmlib.util.collection.KList; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; - -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Objects; -import java.util.Set; - -/** - * Determines which vanilla/datapack structures can ever generate in a world, using the same biome - * gate vanilla applies: a structure is reachable when its biome filter intersects the set of vanilla - * biomes the pack actually produces (its {@code possibleBiomes}). Structures whose required biomes are - * never produced cannot generate and must not be scanned for by {@code /locate} or {@code /iris find} - * (an unbounded scan for an absent biome is what stalls the server). - * - *

The reachable set is fixed per live engine/world and is rebuilt after hotload. - */ -public final class StructureReachability { - private static final Cache> REACHABLE_CACHE = Caffeine.newBuilder().weakKeys().build(); - - private StructureReachability() { - } - - public static Set reachableKeys(Engine engine) { - Engine activeEngine = Objects.requireNonNull(engine, "Structure reachability requires an engine"); - if (activeEngine.getData() == null) { - throw new IllegalStateException("Structure reachability requires a bound pack data loader"); - } - return REACHABLE_CACHE.get(activeEngine, ignored -> build(activeEngine)); - } - - public static boolean isReachable(Engine engine, String structureKey) { - String normalizedStructureKey = normalizeStructureKey(structureKey); - return reachableKeys(engine).contains(normalizedStructureKey); - } - - public static void invalidate(Engine engine) { - if (engine == null) { - return; - } - REACHABLE_CACHE.invalidate(engine); - } - - private static Set build(Engine engine) { - IrisWorld world = engine.getWorld(); - if (world == null) { - throw new IllegalStateException("Structure reachability requires a bound Iris world"); - } - if (world.platformWorld() == null) { - throw new IllegalStateException("Structure reachability requires a bound platform world"); - } - Set reachable = new LinkedHashSet<>(); - for (String key : IrisPlatforms.get().structureHooks().reachableStructureKeys(world.platformWorld())) { - if (key == null || key.isBlank()) { - throw new IllegalStateException("Platform structure reachability returned a blank registry key"); - } - reachable.add(key.toLowerCase(Locale.ROOT)); - } - return Collections.unmodifiableSet(reachable); - } - - /** - * The vanilla biome keys (e.g. {@code minecraft:taiga}) from a structure's filter that the pack - * does not produce. An empty list means the structure is reachable. Used by the structure verify - * diagnostic to explain why a structure cannot generate. - */ - public static KList missingBiomeKeys(Engine engine, String structureKey) { - KList missing = new KList<>(); - Engine activeEngine = Objects.requireNonNull(engine, "Structure biome diagnostics require an engine"); - String normalizedStructureKey = normalizeStructureKey(structureKey); - IrisWorld world = activeEngine.getWorld(); - if (world == null) { - throw new IllegalStateException("Structure biome diagnostics require a bound Iris world"); - } - if (world.platformWorld() == null) { - throw new IllegalStateException("Structure biome diagnostics require a bound platform world"); - } - Set possible = new LinkedHashSet<>(); - for (String key : IrisPlatforms.get().structureHooks().possibleBiomeKeys(world.platformWorld())) { - if (key == null || key.isBlank()) { - throw new IllegalStateException("Platform structure biome query returned a blank possible-biome key"); - } - possible.add(key.toLowerCase(Locale.ROOT)); - } - for (String biomeKey : IrisPlatforms.get().structureHooks().structureBiomeKeys(normalizedStructureKey)) { - if (biomeKey == null || biomeKey.isBlank()) { - throw new IllegalStateException("Platform structure biome query returned a blank required-biome key for " - + normalizedStructureKey); - } - if (!possible.contains(biomeKey.toLowerCase(Locale.ROOT))) { - missing.add(biomeKey); - } - } - return missing; - } - - private static String normalizeStructureKey(String structureKey) { - if (structureKey == null || structureKey.isBlank()) { - throw new IllegalArgumentException("Registered structure key must not be blank"); - } - return structureKey.trim().toLowerCase(Locale.ROOT); - } -} 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 index 3f45eb15b..a3842ec4f 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java @@ -32,8 +32,9 @@ 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}. Vanilla structures that Iris places through native placements are not among them; the - * host's vanilla structure handling finds those. + * {@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. */ public final class StructureLocating implements StructureLocator { @Override @@ -46,6 +47,11 @@ public final class StructureLocating implements StructureLocator { return IrisStructureLocator.locatableEditableKeys(engine(world)); } + @Override + public Set placed(PackWorld world) { + return IrisStructureLocator.placedKeysAndAliases(engine(world)); + } + @Override public LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks) { Engine engine = engine(world); 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 index ccaf5a5a4..c34c209ad 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java @@ -28,6 +28,7 @@ import art.arcane.iris.engine.framework.structure.fit.StructureFitting; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.structure.vanilla.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; @@ -38,16 +39,22 @@ 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}). + * 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 { /** @@ -68,7 +75,7 @@ public final class StructureVanillaStructures implements VanillaStructures { @Override public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { - Engine engine = IrisPackWorld.of(context.world()).engine(); + Engine engine = engine(context.world()); return NativeStartPlanner.plansAt(engine, chunkX, chunkZ).stream() .map(plan -> start(plan, engine.getMinHeight())) .toList(); @@ -103,6 +110,42 @@ public final class StructureVanillaStructures implements VanillaStructures { 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 IrisPackWorld.of(world).engine(); + } + + 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) { IrisStructurePlacement placement = plan.placement(); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index e97c60212..4d3c5bcdb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -24,9 +24,7 @@ import art.arcane.iris.builtin.structure.StructureStilts; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.StructureLocating; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.framework.structure.StructureValidator; @@ -34,7 +32,6 @@ import art.arcane.iris.engine.framework.structure.StructureVanillaStructures; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; -import com.volmit.ModuleLifecycle; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.service.StructureLocator; @@ -42,7 +39,6 @@ import com.volmit.service.VanillaStructures; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; import com.volmit.vanilla.JigsawOverrides; -import com.volmit.world.PackWorld; /** * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear @@ -52,8 +48,8 @@ import com.volmit.world.PackWorld; * The module owns the pack's structures, jigsaw pools and jigsaw pieces as resource kinds * ({@link StructureResources}), read from the folders packs have always used, and checks them with * {@link StructureValidator} wherever Iris validates a pack. It lets Iris find its structures through - * {@link StructureLocating}, and forgets a world's structure index when the world stops, which includes every reload of - * the pack's structure files. + * {@link StructureLocating}; a world's structure index lives in the world's state, so a reload of the pack's structure + * files, which starts a new world, builds it again. *

* It decides over the platform's own structures through its {@link VanillaStructures} provider * ({@link StructureVanillaStructures}): the dimension's {@code importedStructures} settings disable, move, fit and set @@ -61,7 +57,7 @@ import com.volmit.world.PackWorld; * {@code nativeStructures} grids say and fit them into the terrain. It describes the fit settings Iris's structure * placements hold. */ -public final class StructureModule implements IrisModule, ModuleLifecycle { +public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; private ModuleLog log; @@ -84,19 +80,12 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new StructureValidator()); registry.registerService(StructureLocator.class, new StructureLocating()); - registry.registerLifecycle(this); registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); registry.registerHeldType(StructureTerrain.class); registry.registerHeldType(StructureStilts.class); registry.registerHeldType(JigsawOverrides.class); } - /** The structure index is still kept per engine rather than in the world's state, so a stopping world drops it. */ - @Override - public void worldStopped(PackWorld world) { - IrisStructureLocator.invalidate(IrisPackWorld.of(world).engine()); - } - private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); placing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); From 703f206248308e55c7625cbfe4a090ad430dda73 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:07:13 +0200 Subject: [PATCH 074/139] iris:carve moves into the built-ins jar: caves, applying, carving bands and profile sampler on IrisApi, VolmLib and the builtin facades (MatterMantle, CaveDressing); caveLavaHeight and upperDimensionCarving become carve settings --- builtin-modules.txt | 21 + .../art/arcane/iris/builtin/CaveDressing.java | 88 ++ .../art/arcane/iris/builtin/MatterMantle.java | 59 + .../builtin/carve/CaveLavaHeightSettings.java | 49 + .../carve/UpperDimensionCarvingSettings.java | 43 + .../StructureCaveAnchorResolver.java | 3 +- .../engine/mantle/components/CarveWorld.java | 29 + .../engine/mantle/components/CaveCarving.java | 303 ++--- .../components/CaveFieldModuleState.java | 20 +- .../mantle/components/IrisCaveCarver3D.java | 525 ++++---- .../mantle/components/ObjectPlacing.java | 3 +- .../iris/engine/modifier/CarveColumnMask.java | 95 ++ .../iris/engine/modifier/CarveModule.java | 84 +- .../iris/engine/modifier/CarveWallBuffer.java | 166 +++ .../iris/engine/modifier/CaveApplying.java | 1147 ++++++++--------- .../iris/engine/modifier/CaveBiomeBands.java | 36 +- .../iris/engine/modifier/CaveBiomeCache.java | 99 ++ .../engine/modifier/CaveBlockClasses.java | 89 ++ .../engine/modifier/IrisCarveScratch.java | 223 +--- .../object/terrain/carving/CarvingBands.java | 71 - .../terrain/carving/CarvingResolver.java | 269 ++-- ...leSampler.java => CaveProfileSampler.java} | 81 +- .../terrain/carving/DeclaredByLevel.java | 83 ++ .../terrain/carving/DeclaredCaveProfiles.java | 52 + .../terrain/carving/ResolvedCarvingEntry.java | 33 +- .../terrain/carving/ResolvedCaveProfile.java | 123 -- .../floating/FloatingIslandSample.java | 8 +- .../floating/ResolvedFloatingChild.java | 14 +- .../object/world/dimension/IrisDimension.java | 6 - 29 files changed, 2046 insertions(+), 1776 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/CaveDressing.java create mode 100644 src/main/java/art/arcane/iris/builtin/MatterMantle.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java rename src/main/java/art/arcane/iris/engine/object/terrain/carving/{IrisCaveProfileSampler.java => CaveProfileSampler.java} (63%) create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..550a80810 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,24 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.modifier.CarveModule +include art/arcane/iris/engine/modifier/CaveApplying*.class +include art/arcane/iris/engine/modifier/CaveBiomeBands*.class +include art/arcane/iris/engine/modifier/CaveBiomeCache.class +include art/arcane/iris/engine/modifier/CaveBlockClasses.class +include art/arcane/iris/engine/modifier/CarveColumnMask.class +include art/arcane/iris/engine/modifier/CarveWallBuffer*.class +include art/arcane/iris/engine/modifier/IrisCarveScratch.class +include art/arcane/iris/engine/mantle/components/CarveOrphanSweep*.class +include art/arcane/iris/engine/mantle/components/CarveWorld.class +include art/arcane/iris/engine/mantle/components/CaveCarveScratch*.class +include art/arcane/iris/engine/mantle/components/CaveCarving*.class +include art/arcane/iris/engine/mantle/components/CaveFieldModuleState.class +include art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan*.class +include art/arcane/iris/engine/mantle/components/IrisCaveCarver3D*.class +include art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan*.class +include art/arcane/iris/engine/object/terrain/carving/CarvingResolver*.class +include art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler*.class +include art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.class +include art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.class +include art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.class diff --git a/src/main/java/art/arcane/iris/builtin/CaveDressing.java b/src/main/java/art/arcane/iris/builtin/CaveDressing.java new file mode 100644 index 000000000..14afe16e0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/CaveDressing.java @@ -0,0 +1,88 @@ +/* + * 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.builtin; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; + +/** + * What a cave's floor, ceiling and walls get from the rest of Iris's terrain and decoration: the blocks of a biome's layers + * and wall, its decorators and the fluid of the dimension's palette. Those features keep their workers per world and are + * ported on their own; until they are modules this narrow interface is the one thing {@code iris:carve} needs from them, in + * IrisApi's types, and Iris's worlds implement it ({@link Source}). + * + *

Transitional: when {@code iris:terrain} and {@code iris:decorant} are modules of the same jar, {@code iris:carve} asks + * their classes directly and this interface goes. + * + *

The methods that give a block take the {@code chunk} hunk the block is for. A block read from here and written to that + * hunk keeps the identity of a content plugin's custom block, as it did when the layers wrote the platform's states themselves. + */ +public interface CaveDressing { + /** The dressing of {@code world}, which must be a world Iris generates. */ + static CaveDressing of(PackWorld world) { + if (world instanceof Source source) { + return source.caveDressing(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** Iris's worlds answer for their dressing. */ + interface Source { + CaveDressing caveDressing(); + } + + /** Whether the dimension's fluid palette gives a fluid (water, lava) at the column; false where it gives none. */ + boolean fluidPresentAt(int x, int z); + + /** The block the dimension's fluid palette gives at the column; null where it gives none. */ + BlockState fluidAt(Hunk chunk, int x, int z); + + /** The block the biome's wall gives at the position; null where the biome has no wall or the layer gives none. */ + BlockState wall(Hunk chunk, ResourceId biome, RNG rng, int x, int y, int z); + + /** The blocks the biome's surface layers stack up to at the column, top first, at most {@code depth} of them. */ + List floorLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY); + + /** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code depth} of them. */ + List ceilingLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY); + + /** Whether the biome has a decorator for {@code part}. */ + boolean hasDecorators(ResourceId biome, DecorationPart part); + + /** + * Decorates a cave's floor in the column at {@code chunk}'s {@code localX}, {@code localZ} (world {@code x}, {@code z}) above + * the block at {@code floorY}, with the biome's decorators for {@link DecorationPart#NONE}, in a space {@code airThickness} high. + */ + void decorateFloor(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness); + + /** Decorates a cave's ceiling the same way, from the block at {@code ceilingY} down, with the decorators for {@link DecorationPart#CEILING}. */ + void decorateCeiling(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness); + + /** + * {@code layer}, the block a layer wants in the place of the ore {@code existing}, as the deepslate or the stone variant + * of the ore that fits the rock {@code existing} is; {@code layer} itself where it has no variant. + */ + BlockState deepSlateOre(Hunk chunk, BlockState existing, BlockState layer); +} diff --git a/src/main/java/art/arcane/iris/builtin/MatterMantle.java b/src/main/java/art/arcane/iris/builtin/MatterMantle.java new file mode 100644 index 000000000..34ae03f93 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/MatterMantle.java @@ -0,0 +1,59 @@ +/* + * 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.builtin; + +import art.arcane.volmlib.util.mantle.runtime.MantleChunk; +import art.arcane.volmlib.util.matter.Matter; +import com.volmit.host.ReadOnlyMantle; +import com.volmit.mantle.Mantle; + +/** + * Iris's mantle as the matter slices it stores, for the built-ins whose data the platform and the rest of Iris read as + * slices rather than through a {@link com.volmit.mantle.MantleLayer}: caves ({@code MatterCavern}) and markers. The + * slices are VolmLib's own types, which a pack module may use as well; Iris's worlds implement this next to + * {@link Mantle}, and {@link #of(Mantle)} reaches it from an invocation's mantle. + * + *

Heights are as the mantle stores them: above the dimension's bottom. A chunk the invocation reaches is pinned for + * as long as the invocation runs; callers neither release it nor keep it afterwards. + */ +public interface MatterMantle { + /** + * The matter side of {@code mantle}, which must be a mantle Iris hands to its stages. A chunk stage's mantle is read-only + * to the stage; the matter behind it is not, and a built-in chunk stage that writes markers into it (the caves' floors and + * ceilings) is why this reaches through. + */ + static MatterMantle of(Mantle mantle) { + if (mantle instanceof ReadOnlyMantle readOnly) { + return of(readOnly.host()); + } + if (mantle instanceof MatterMantle matter) { + return matter; + } + throw new IllegalArgumentException("Built-in modules write Iris's own mantle, not " + mantle); + } + + /** The mantle chunk at chunk coordinates {@code chunkX}, {@code chunkZ}, or null outside what the invocation reaches. */ + MantleChunk chunk(int chunkX, int chunkZ); + + /** + * The mantle chunk at those coordinates if the world holds it in memory, wherever it is, or null. It is never loaded + * or created for the call and not pinned, so read it at once and do not keep it. + */ + MantleChunk loadedChunk(int chunkX, int chunkZ); +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java new file mode 100644 index 000000000..4355cbb47 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java @@ -0,0 +1,49 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** A dimension's {@code caveLavaHeight}, written as the bare number. */ +@Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") +@Feature(id = "iris:carve/lava-height", name = "Cave lava height", key = "caveLavaHeight", root = "height", targets = Target.DIMENSION) +public final class CaveLavaHeightSettings implements IrisFeature { + public static final int DEFAULT_HEIGHT = 8; + + @MinNumber(0) + @MaxNumber(318) + @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") + private int height = DEFAULT_HEIGHT; + + public CaveLavaHeightSettings() { + } + + public CaveLavaHeightSettings(int height) { + this.height = height; + } + + public int height() { + return height; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java new file mode 100644 index 000000000..741aaa382 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.carve; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** A dimension's {@code upperDimensionCarving}, written as the bare boolean. */ +@Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") +@Feature(id = "iris:carve/upper-dimension", name = "Upper dimension carving", key = "upperDimensionCarving", root = "enabled", targets = Target.DIMENSION) +public final class UpperDimensionCarvingSettings implements IrisFeature { + @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") + private boolean enabled = false; + + public UpperDimensionCarvingSettings() { + } + + public UpperDimensionCarvingSettings(boolean enabled) { + this.enabled = enabled; + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java index 599b4bd88..5f8620d76 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +++ b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java @@ -1,5 +1,6 @@ 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.engine.object.structure.IrisStructureAnchorMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; @@ -291,7 +292,7 @@ public final class StructureCaveAnchorResolver { placement.isUnderwater(), cavern, mantleY, - engine.getDimension().getCaveLavaHeight()); + engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT)); } static boolean acceptsAnchorFluid( diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java b/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java new file mode 100644 index 000000000..2d04b7cd0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CarveWorld.java @@ -0,0 +1,29 @@ +/* + * 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 com.volmit.noise.NoiseFactory; + +/** + * What the cave carvers need to know about one world that does not change while it runs: the noise the world's pack builds, + * the carve seed, the dimension's height, its fluid and cave-lava heights (above the dimension's bottom) and the platform's Y of + * its bottom, which converts the absolute world Y of a cave biome band. + */ +public record CarveWorld(NoiseFactory noise, long carveSeed, int height, int fluidHeight, int lavaHeight, int minHeight) { +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 7046d1da8..94745233d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -18,31 +18,19 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.terrain.TerrainPalettes; -import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.modifier.CaveBiomeBands; -import art.arcane.iris.engine.object.terrain.carving.CarvingBands; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.iris.util.project.stream.utility.ChunkFillableDoubleStream2D; -import art.arcane.iris.util.simd.SimdKernels; -import art.arcane.iris.util.simd.SimdSupport; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles; +import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.config.Range; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; import java.util.ArrayList; import java.util.Arrays; @@ -59,6 +47,8 @@ public class CaveCarving { private static final int CHUNK_SIZE = 16; private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; private static final int BLEND_RADIUS = 3; + /** A column's cave biome is the one the world places this far below its surface (at least at height 1). */ + private static final int CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS = 56; private static final int FIELD_SIZE = CHUNK_SIZE + (BLEND_RADIUS * 2); private static final double MIN_WEIGHT = 0.08D; private static final double THRESHOLD_PENALTY = 0.24D; @@ -70,7 +60,11 @@ public class CaveCarving { private static final double[] KERNEL_WEIGHT = new double[KERNEL_SIZE]; private static final ThreadLocal BLEND_SCRATCH = ThreadLocal.withInitial(BlendScratch::new); - private final Engine engine; + private final CarveWorld world; + private final DeclaredCaveProfiles declaredProfiles; + private final CarvingResolver resolver; + private final CaveDressing dressing; + private final boolean upperDimensionCarving; private final Object profileCarverLock = new Object(); private volatile Map profileCarvers = new IdentityHashMap<>(); @@ -87,20 +81,20 @@ public class CaveCarving { } } - public CaveCarving(Engine engine) { - this.engine = engine; + public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.declaredProfiles = DeclaredCaveProfiles.of(packWorld); + this.resolver = CarvingResolver.of(packWorld); + this.dressing = CaveDressing.of(packWorld); + this.upperDimensionCarving = upperDimensionCarving; } - /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ - public void carve(MantleWriter writer, int x, int z, ChunkContext context) { - IrisComplex complex = context.getComplex(); - CarvingResolver.State resolverState = new CarvingResolver.State(); + /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code mantle}, reading the terrain around it from {@code terrain}. */ + public void carve(MatterMantle mantle, TerrainSampler terrain, int x, int z) { BlendScratch blendScratch = BLEND_SCRATCH.get(); - int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, context, blendScratch.chunkSurfaceHeights); - PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); - List weightedProfiles = resolveWeightedProfiles(x, z, complex, resolverState); - engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); - int fluidHeight = engine.getDimension().getFluidHeight(); + int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights); + List weightedProfiles = resolveWeightedProfiles(x, z, terrain); + int fluidHeight = world.fluidHeight(); int[] surfaceFluidBoundaryStartY = blendScratch.surfaceFluidBoundaryStartY; SurfaceFluidBoundaryPlan.fill( chunkSurfaceHeights, @@ -113,27 +107,30 @@ public class CaveCarving { ); CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); for (WeightedProfile weightedProfile : weightedProfiles) { - carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); + carveProfile(weightedProfile, mantle, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); } - UpperDimensionContext upperCtx = engine.getUpperContext(); - if (upperCtx != null && engine.getDimension().isUpperDimensionCarving()) { - carveUpperTerrain(upperCtx, weightedProfiles, writer, x, z, chunkSurfaceHeights, fluidSupportPlan); + if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) { + carveUpperTerrain(terrain, weightedProfiles, mantle, x, z, fluidSupportPlan); } - fluidSupportPlan.resolve(writer.acquireChunk(x, z)); + fluidSupportPlan.resolve(mantle.chunk(x, z)); if (!weightedProfiles.isEmpty()) { CarveOrphanSweep.sweepChunk( - writer.acquireChunk(x, z), + mantle.chunk(x, z), chunkSurfaceHeights, maxSurfaceBreakDepth(weightedProfiles), - writer.getMantle().getWorldHeight() - 1, + world.height() - 1, surfaceFluidBoundaryStartY, fluidHeight ); } } + private static boolean hasUpperDimension(TerrainSampler terrain, int chunkX, int chunkZ) { + return terrain.upperDimensionY(PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ)).isPresent(); + } + private static int maxSurfaceBreakDepth(List weightedProfiles) { int maxDepth = 0; for (WeightedProfile weightedProfile : weightedProfiles) { @@ -142,21 +139,19 @@ public class CaveCarving { return maxDepth; } - @ChunkCoordinates - private void carveProfile(WeightedProfile weightedProfile, MantleWriter writer, int cx, int cz, + private void carveProfile(WeightedProfile weightedProfile, MatterMantle mantle, int cx, int cz, int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY, CaveFluidSupportPlan fluidSupportPlan) { IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan); } - private void carveUpperTerrain(UpperDimensionContext upperCtx, List normalProfiles, - MantleWriter writer, int cx, int cz, int[] lowerSurfaceHeights, + private void carveUpperTerrain(TerrainSampler terrain, List normalProfiles, + MatterMantle mantle, int cx, int cz, CaveFluidSupportPlan fluidSupportPlan) { - int chunkHeight = engine.getHeight(); - int worldMinHeight = engine.getWorld().minHeight(); - int gap = engine.getDimension().getUpperDimensionGap(); + int chunkHeight = world.height(); + int worldMinHeight = world.minHeight(); int baseX = PowerOfTwoCoordinates.chunkToBlock(cx); int baseZ = PowerOfTwoCoordinates.chunkToBlock(cz); @@ -165,9 +160,7 @@ public class CaveCarving { int worldX = baseX + localX; for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldZ = baseZ + localZ; - int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); - int upperY = Math.max(rawUpper, lowerSurfaceHeights[columnIndex] + gap); + int upperY = terrain.upperDimensionY(worldX, worldZ).getAsInt(); if (upperY < minUpperSurfaceY) { minUpperSurfaceY = upperY; } @@ -178,34 +171,34 @@ public class CaveCarving { return; } - IrisRange upperYRange = new IrisRange( + Range upperYRange = Range.of( minUpperSurfaceY + worldMinHeight, chunkHeight - 1 + worldMinHeight ); - IrisRange fullVerticalRange = new IrisRange(0, chunkHeight); + Range fullVerticalRange = Range.of(0, chunkHeight); int[] ceilingSurfaceHeights = new int[CHUNK_AREA]; Arrays.fill(ceilingSurfaceHeights, chunkHeight - 1); for (WeightedProfile weightedProfile : normalProfiles) { - IrisRange constrainedRange; + Range constrainedRange; if (weightedProfile.worldYRange != null) { - double min = Math.max(weightedProfile.worldYRange.getMin(), upperYRange.getMin()); - double max = Math.min(weightedProfile.worldYRange.getMax(), upperYRange.getMax()); + double min = Math.max(weightedProfile.worldYRange.min(), upperYRange.min()); + double max = Math.min(weightedProfile.worldYRange.max(), upperYRange.max()); if (min >= max) { continue; } - constrainedRange = new IrisRange(min, max); + constrainedRange = Range.of(min, max); } else { constrainedRange = upperYRange; } IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(writer, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan); } } - private List resolveWeightedProfiles(int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState) { + private List resolveWeightedProfiles(int chunkX, int chunkZ, TerrainSampler terrain) { BlendScratch blendScratch = BLEND_SCRATCH.get(); CaveProfile[] profileField = blendScratch.profileField; Map columnProfileWeights = blendScratch.columnProfileWeights; @@ -215,7 +208,7 @@ public class CaveCarving { double[] kernelProfileWeights = blendScratch.kernelProfileWeights; activeProfiles.clear(); profileOrder.clear(); - fillProfileField(profileField, chunkX, chunkZ, complex, resolverState, blendScratch); + fillProfileField(profileField, chunkX, chunkZ, terrain, blendScratch); for (int localX = 0; localX < CHUNK_SIZE; localX++) { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { @@ -285,7 +278,7 @@ public class CaveCarving { // averageWeight ranks and orders carve passes, so it must be bit-identical across // installations: kernels.sum reassociates FP addition under the vector kernel, // making profile order depend on a JVM flag. max() is order-independent and safe. - double maxWeight = SimdSupport.kernels().max(weights, weights.length); + double maxWeight = maxOf(weights); if (maxWeight < MIN_WEIGHT) { continue; @@ -296,14 +289,14 @@ public class CaveCarving { } List blendedProfiles = limitAndMergeBlendedProfiles(columnWeightedProfiles, MAX_BLENDED_PROFILE_PASSES, CHUNK_AREA); - List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, resolverState, blendScratch); + List resolvedProfiles = resolveDimensionCarvingProfiles(chunkX, chunkZ, blendScratch); resolvedProfiles.addAll(blendedProfiles); return resolvedProfiles; } - private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, CarvingResolver.State resolverState, BlendScratch blendScratch) { + private List resolveDimensionCarvingProfiles(int chunkX, int chunkZ, BlendScratch blendScratch) { List weightedProfiles = new ArrayList<>(); - List entries = CarvingBands.of(engine).entries(); + List entries = resolver.entries(); if (entries.isEmpty()) { return weightedProfiles; } @@ -316,25 +309,25 @@ public class CaveCarving { continue; } - IrisBiome rootBiome = CarvingResolver.resolveEntryBiome(engine, entry, resolverState); + PackBiome rootBiome = resolver.entryBiome(entry); if (rootBiome == null) { continue; } ResolvedCarvingEntry[] columnPlan = dimensionColumnPlans.computeIfAbsent(entry, key -> new ResolvedCarvingEntry[CHUNK_AREA]); - buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry, resolverState); + buildDimensionColumnPlan(columnPlan, chunkX, chunkZ, entry); Map rootProfileColumnWeights = new IdentityHashMap<>(); List rootProfileOrder = new ArrayList<>(); - IrisRange worldYRange = entry.worldYRange() == null ? null : IrisValues.range(entry.worldYRange()); + Range worldYRange = entry.worldYRange(); for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { ResolvedCarvingEntry resolvedEntry = columnPlan[columnIndex]; - IrisBiome resolvedBiome = CarvingResolver.resolveEntryBiome(engine, resolvedEntry, resolverState); + PackBiome resolvedBiome = resolver.entryBiome(resolvedEntry); if (resolvedBiome == null) { continue; } - CaveProfile profile = CaveProfiles.declaredBy(resolvedBiome); + CaveProfile profile = declaredProfiles.ofBiome(resolvedBiome.id()); if (!isProfileEnabled(profile)) { continue; } @@ -356,7 +349,7 @@ public class CaveCarving { return weightedProfiles; } - private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry, CarvingResolver.State resolverState) { + private void buildDimensionColumnPlan(ResolvedCarvingEntry[] columnPlan, int chunkX, int chunkZ, ResolvedCarvingEntry entry) { int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); for (int localX = 0; localX < CHUNK_SIZE; localX++) { @@ -364,30 +357,22 @@ public class CaveCarving { for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldZ = baseZ + localZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - columnPlan[columnIndex] = CarvingResolver.resolveFromRoot(engine, entry, worldX, worldZ, resolverState); + columnPlan[columnIndex] = resolver.resolveFromRoot(entry, worldX, worldZ); } } } - private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, IrisComplex complex, CarvingResolver.State resolverState, BlendScratch blendScratch) { + private void fillProfileField(CaveProfile[] profileField, int chunkX, int chunkZ, TerrainSampler terrain, BlendScratch blendScratch) { int startX = PowerOfTwoCoordinates.chunkToBlock(chunkX) - BLEND_RADIUS; int startZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ) - BLEND_RADIUS; - prefillProfileFieldSamples(startX, startZ, complex, blendScratch); + prefillFieldHeightsAndFluid(terrain, startX, startZ, blendScratch); for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { int worldX = startX + fieldX; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { int worldZ = startZ + fieldZ; int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; - profileField[fieldIndex] = resolveColumnProfile( - worldX, - worldZ, - blendScratch.fieldSurfaceHeights[fieldIndex], - blendScratch.fieldRegions[fieldIndex], - blendScratch.fieldSurfaceBiomes[fieldIndex], - blendScratch.fieldCaveBiomes[fieldIndex], - resolverState - ); + profileField[fieldIndex] = resolveColumnProfile(terrain, worldX, worldZ, blendScratch.fieldSurfaceHeights[fieldIndex]); } } } @@ -402,65 +387,34 @@ public class CaveCarving { return -1; } - private CaveProfile resolveColumnProfile( - int worldX, - int worldZ, - double surfaceHeight, - IrisRegion region, - IrisBiome surfaceBiome, - IrisBiome caveBiome, - CarvingResolver.State resolverState - ) { + /** + * The profile that carves a column: the dimension's, replaced by the region's, the surface biome's and the cave biome's + * wherever they declare an enabled one. The cave biome is the one the world places at the depth below the surface this + * column's caves start at ({@link #CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS}), after the dimension's carving bands. + */ + private CaveProfile resolveColumnProfile(TerrainSampler terrain, int worldX, int worldZ, double surfaceHeight) { CaveProfile resolved = null; - CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); + CaveProfile dimensionProfile = declaredProfiles.ofDimension(); if (isProfileEnabled(dimensionProfile)) { resolved = dimensionProfile; } - if (region != null) { - CaveProfile regionProfile = CaveProfiles.declaredBy(region); - if (isProfileEnabled(regionProfile)) { - resolved = regionProfile; - } - } - - if (surfaceBiome != null) { - CaveProfile surfaceProfile = CaveProfiles.declaredBy(surfaceBiome); - if (isProfileEnabled(surfaceProfile)) { - resolved = surfaceProfile; - } - } - int roundedSurfaceY = (int) Math.round(surfaceHeight); - int sampleY = Math.max(1, roundedSurfaceY - 56); - int worldY = sampleY + engine.getWorld().minHeight(); - ResolvedCarvingEntry rootCarvingEntry = CarvingResolver.resolveRootEntry(engine, worldY, resolverState); - IrisBiome resolvedCarvingBiome = null; - if (rootCarvingEntry != null) { - ResolvedCarvingEntry resolvedCarvingEntry = CarvingResolver.resolveFromRoot(engine, rootCarvingEntry, worldX, worldZ, resolverState); - resolvedCarvingBiome = CarvingResolver.resolveEntryBiome(engine, resolvedCarvingEntry, resolverState); - if (resolvedCarvingBiome != null) { - caveBiome = resolvedCarvingBiome; - } - } - if (caveBiome != null) { - IrisBiome effectiveCaveBiome = caveBiome; - if (resolvedCarvingBiome == null && surfaceBiome != null) { - if (surfaceBiome != null) { - int truncatedSurfaceY = (int) surfaceHeight; - int depthBelowSurface = truncatedSurfaceY - sampleY; - if (depthBelowSurface <= 0) { - effectiveCaveBiome = surfaceBiome; - } else { - int minDepth = Math.max(0, CaveBiomeBands.minDepthBelowSurface(caveBiome)); - if (depthBelowSurface < minDepth) { - effectiveCaveBiome = surfaceBiome; - } - } - } - } + int sampleY = Math.max(1, roundedSurfaceY - CAVE_SAMPLE_DEPTH_BELOW_SURFACE_BLOCKS); + BiomeSample sample = terrain.biome(worldX, sampleY, worldZ); - CaveProfile caveProfile = CaveProfiles.declaredBy(effectiveCaveBiome); + CaveProfile regionProfile = declaredProfiles.ofRegion(sample.region()); + if (isProfileEnabled(regionProfile)) { + resolved = regionProfile; + } + + CaveProfile surfaceProfile = declaredProfiles.ofBiome(sample.surfaceBiome()); + if (isProfileEnabled(surfaceProfile)) { + resolved = surfaceProfile; + } + + if (sample.caveBiome().isPresent()) { + CaveProfile caveProfile = declaredProfiles.ofBiome(sample.caveBiome().get()); if (isProfileEnabled(caveProfile)) { resolved = caveProfile; } @@ -469,37 +423,14 @@ public class CaveCarving { return resolved; } - private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { - fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights); - fillFieldFluidPresence(TerrainPalettes.of(engine), startX, startZ, blendScratch.fieldHasFluid); - fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions); - fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes); - fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes); - } - - private void fillFieldObjects(ProceduralStream stream, int startX, int startZ, T[] target) { + private void prefillFieldHeightsAndFluid(TerrainSampler terrain, int startX, int startZ, BlendScratch blendScratch) { for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { int worldX = startX + fieldX; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = stream.get(worldX, startZ + fieldZ); - } - } - } - - private void fillFieldHeights(ProceduralStream stream, int startX, int startZ, double[] target) { - for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { - int worldX = startX + fieldX; - for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = stream.getDouble(worldX, startZ + fieldZ); - } - } - } - - private void fillFieldFluidPresence(TerrainPalettes palettes, int startX, int startZ, boolean[] target) { - for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { - int worldX = startX + fieldX; - for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(palettes.fluidAt(worldX, startZ + fieldZ)); + int worldZ = startZ + fieldZ; + int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; + blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ); + blendScratch.fieldHasFluid[fieldIndex] = dressing.fluidPresentAt(worldX, worldZ); } } } @@ -510,7 +441,7 @@ public class CaveCarving { return carver; } - IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(engine, profile); + IrisCaveCarver3D createdCarver = new IrisCaveCarver3D(world, profile); synchronized (profileCarverLock) { IrisCaveCarver3D published = profileCarvers.get(profile); if (published != null) { @@ -528,39 +459,25 @@ public class CaveCarving { return profile != null && profile.enabled(); } - private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, ChunkContext context, int[] scratch) { - int[] surfaceHeights = scratch; + private int[] prepareChunkSurfaceHeights(int chunkX, int chunkZ, TerrainSampler terrain, int[] scratch) { int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - boolean useContextHeight = context != null - && context.getHeight() != null - && context.getX() == baseX - && context.getZ() == baseZ; - double[] cachedChunkHeights = null; - if (!useContextHeight && context != null) { - ProceduralStream heightStream = context.getComplex().getHeightStream(); - if (heightStream instanceof ChunkFillableDoubleStream2D cachedHeightStream) { - cachedChunkHeights = BLEND_SCRATCH.get().chunkSurfaceHeightSamples; - cachedHeightStream.fillChunkDoubles(baseX, baseZ, cachedChunkHeights); - } - } for (int localX = 0; localX < CHUNK_SIZE; localX++) { int worldX = baseX + localX; for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { - int worldZ = baseZ + localZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - if (useContextHeight) { - surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ); - continue; - } - if (cachedChunkHeights != null) { - surfaceHeights[columnIndex] = (int) Math.round(cachedChunkHeights[(localZ << 4) + localX]); - continue; - } - surfaceHeights[columnIndex] = engine.getHeight(worldX, worldZ); + scratch[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, baseZ + localZ)); } } - return surfaceHeights; + return scratch; + } + + private static double maxOf(double[] values) { + double max = Double.NEGATIVE_INFINITY; + for (double value : values) { + max = Math.max(max, value); + } + return max; } private static List limitAndMergeBlendedProfiles(List blendedProfiles, int maxProfiles) { @@ -664,10 +581,10 @@ public class CaveCarving { private final CaveProfile profile; private final double[] columnWeights; private final double averageWeight; - private final IrisRange worldYRange; + private final Range worldYRange; private final int sequence; - private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, IrisRange worldYRange, int sequence) { + private WeightedProfile(CaveProfile profile, double[] columnWeights, double averageWeight, Range worldYRange, int sequence) { this.profile = profile; this.columnWeights = columnWeights; this.averageWeight = averageWeight; @@ -690,11 +607,7 @@ public class CaveCarving { private final List profileOrder = new ArrayList<>(); private final double[] fieldSurfaceHeights = new double[FIELD_SIZE * FIELD_SIZE]; private final boolean[] fieldHasFluid = new boolean[FIELD_SIZE * FIELD_SIZE]; - private final IrisRegion[] fieldRegions = new IrisRegion[FIELD_SIZE * FIELD_SIZE]; - private final IrisBiome[] fieldSurfaceBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE]; - private final IrisBiome[] fieldCaveBiomes = new IrisBiome[FIELD_SIZE * FIELD_SIZE]; private final int[] chunkSurfaceHeights = new int[CHUNK_AREA]; private final int[] surfaceFluidBoundaryStartY = new int[CHUNK_AREA]; - private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA]; } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java index f07e069ce..392ac27ce 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFieldModuleState.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.builtin.carve.CaveFieldModule; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; final class CaveFieldModuleState { - final CNG density; + final NoiseSampler density; final int minY; final int maxY; final double weight; @@ -32,11 +32,11 @@ final class CaveFieldModuleState { final double minContribution; final double maxContribution; - CaveFieldModuleState(ResolvedCaveProfile.Module module, CNG density) { - IrisRange range = module.verticalRange(); + CaveFieldModuleState(CaveFieldModule module, NoiseSampler density) { + Range range = module.verticalRange(); this.density = density; - this.minY = (int) Math.floor(range.getMin()); - this.maxY = (int) Math.ceil(range.getMax()); + this.minY = (int) Math.floor(range.min()); + this.maxY = (int) Math.ceil(range.max()); this.weight = module.weight(); this.threshold = module.threshold(); this.invert = module.invert(); @@ -47,12 +47,12 @@ final class CaveFieldModuleState { } double sample(double x, int y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); + double sampled = density.signed(x, y, z); return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; } double sample(double x, double y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); + double sampled = density.signed(x, y, z); return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java index 3f219f4be..91b0e9cfd 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -18,22 +18,19 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.MatterMantle; +import art.arcane.iris.builtin.carve.CaveFieldModule; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCaveProfile; -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.value.IrisRange; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterSlice; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; +import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; import java.util.ArrayList; import java.util.Arrays; @@ -51,15 +48,13 @@ public class IrisCaveCarver3D { private static final int SURFACE_CEILING_FADE_DEPTH = 12; private static final double SURFACE_CEILING_SOLID_EPSILON = 0.000001D; - private final Engine engine; - private final IrisData data; private final CaveProfile profile; - private final ResolvedCaveProfile resolved; - private final CNG baseDensity; - private final CNG detailDensity; - private final CNG warpDensity; - private final CNG surfaceBreakDensity; - private final RNG thresholdRng; + private final NoiseSampler baseDensity; + private final NoiseSampler detailDensity; + private final NoiseSampler warpDensity; + private final NoiseSampler surfaceBreakDensity; + private final NoiseSampler thresholdNoise; + private final int lavaHeight; private final CaveFieldModuleState[] modules; private final double inverseNormalization; private final MatterCavern carveAir; @@ -80,25 +75,24 @@ public class IrisCaveCarver3D { private final int fluidMinDepthBelowSurface; private final int fluidHeight; private final int aquiferCeilingY; + private final int minHeight; + private final int worldHeight; private final ThreadLocal scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new); - public IrisCaveCarver3D(Engine engine, CaveProfile profile) { - this.engine = engine; - this.data = engine.getData(); + public IrisCaveCarver3D(CarveWorld world, CaveProfile profile) { this.profile = profile; - this.resolved = ResolvedCaveProfile.of(profile); this.carveAir = new MatterCavern(true, "", LIQUID_AIR); this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR); List moduleStates = new ArrayList<>(); - RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); - this.surfaceBreakDensity = resolved.surfaceBreakStyle().create(baseRng.nextParallelRNG(341_219), data); - this.thresholdRng = baseRng.nextParallelRNG(489_112); + long carveSeed = world.carveSeed(); + this.baseDensity = world.noise().sampler(profile.baseDensityStyle(), carveSeed + 934_447); + this.detailDensity = world.noise().sampler(profile.detailDensityStyle(), carveSeed + 612_991); + this.warpDensity = world.noise().sampler(profile.warpStyle(), carveSeed + 770_713); + this.surfaceBreakDensity = world.noise().sampler(profile.surfaceBreakStyle(), carveSeed + 341_219); + this.thresholdNoise = world.noise().sampler(profile.densityThreshold().style(), carveSeed + 489_112); this.baseWeight = profile.baseWeight(); this.detailWeight = profile.detailWeight(); this.warpStrength = profile.warpStrength(); @@ -107,13 +101,16 @@ public class IrisCaveCarver3D { this.allowFluid = profile.allowFluid(); this.fluidRequiresFloor = profile.fluidRequiresFloor(); this.fluidMinDepthBelowSurface = Math.max(0, profile.fluidMinDepthBelowSurface()); - this.fluidHeight = engine.getDimension().getFluidHeight(); - this.aquiferCeilingY = engine.getHeight() - 1; + this.fluidHeight = world.fluidHeight(); + this.worldHeight = world.height(); + this.aquiferCeilingY = world.height() - 1; + this.lavaHeight = world.lavaHeight(); + this.minHeight = world.minHeight(); double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; - for (ResolvedCaveProfile.Module module : resolved.modules()) { - CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + for (CaveFieldModule module : profile.modules()) { + NoiseSampler moduleDensity = world.noise().sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); CaveFieldModuleState state = new CaveFieldModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); @@ -129,249 +126,183 @@ public class IrisCaveCarver3D { detailMaxContribution = detailWeight; } - public int carve(MantleWriter writer, int chunkX, int chunkZ) { - CaveCarveScratch scratch = scratchCache.get(); - if (!scratch.fullWeightsInitialized) { - Arrays.fill(scratch.fullWeights, 1D); - scratch.fullWeightsInitialized = true; - } - return carve(writer, chunkX, chunkZ, scratch.fullWeights, 0D, 0D, null, null); - } - public int carve( - MantleWriter writer, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty - ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, null, null); - } - - public int carve( - MantleWriter writer, + MatterMantle mantle, int chunkX, int chunkZ, double[] columnWeights, double minWeight, double thresholdPenalty, - IrisRange worldYRange + Range worldYRange, + int[] surfaceHeights ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, null); + return carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null); } public int carve( - MantleWriter writer, + MatterMantle mantle, int chunkX, int chunkZ, double[] columnWeights, double minWeight, double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights - ) { - return carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, precomputedSurfaceHeights, null); - } - - public int carve( - MantleWriter writer, - int chunkX, - int chunkZ, - double[] columnWeights, - double minWeight, - double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights, - IrisRange overrideVerticalRange + Range worldYRange, + int[] surfaceHeights, + Range overrideVerticalRange ) { CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - int carved = carve(writer, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, - worldYRange, precomputedSurfaceHeights, null, overrideVerticalRange, fluidSupportPlan); - fluidSupportPlan.resolve(writer.acquireChunk(chunkX, chunkZ)); + int carved = carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, + worldYRange, surfaceHeights, null, overrideVerticalRange, fluidSupportPlan); + fluidSupportPlan.resolve(mantle.chunk(chunkX, chunkZ)); return carved; } + /** {@code surfaceHeights} are the rounded heights of the chunk's columns, packed as {@link PowerOfTwoCoordinates#packLocal16}. */ int carve( - MantleWriter writer, + MatterMantle mantle, int chunkX, int chunkZ, double[] columnWeights, double minWeight, double thresholdPenalty, - IrisRange worldYRange, - int[] precomputedSurfaceHeights, + Range worldYRange, + int[] surfaceHeights, int[] surfaceFluidBoundaryStartY, - IrisRange overrideVerticalRange, + Range overrideVerticalRange, CaveFluidSupportPlan fluidSupportPlan ) { - PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); - try { - CaveCarveScratch scratch = scratchCache.get(); - if (columnWeights == null || columnWeights.length < 256) { - if (!scratch.fullWeightsInitialized) { - Arrays.fill(scratch.fullWeights, 1D); - scratch.fullWeightsInitialized = true; - } - columnWeights = scratch.fullWeights; + CaveCarveScratch scratch = scratchCache.get(); + if (columnWeights == null || columnWeights.length < 256) { + if (!scratch.fullWeightsInitialized) { + Arrays.fill(scratch.fullWeights, 1D); + scratch.fullWeightsInitialized = true; } + columnWeights = scratch.fullWeights; + } - double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); - double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); - int worldHeight = writer.getMantle().getWorldHeight(); - IrisRange effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : resolved.verticalRange(); - int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.getMin())); - int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.getMax())); - if (worldYRange != null) { - int worldMinHeight = engine.getWorld().minHeight(); - int rangeMinY = (int) Math.floor(worldYRange.getMin() - worldMinHeight); - int rangeMaxY = (int) Math.ceil(worldYRange.getMax() - worldMinHeight); - minY = Math.max(minY, rangeMinY); - maxY = Math.min(maxY, rangeMaxY); - } - int sampleStep = Math.max(1, profile.sampleStep()); - boolean exactSampling = sampleStep <= 2; - boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); - int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); - double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); - int surfaceClearance = Math.max(0, profile.surfaceClearance()); - int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); - double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); - double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); - boolean allowSurfaceBreak = profile.allowSurfaceBreak(); - if (maxY < minY) { - return 0; + double resolvedMinWeight = Math.max(0D, Math.min(1D, minWeight)); + double resolvedThresholdPenalty = Math.max(0D, thresholdPenalty); + Range effectiveVerticalRange = overrideVerticalRange != null ? overrideVerticalRange : profile.verticalRange(); + int minY = Math.max(0, (int) Math.floor(effectiveVerticalRange.min())); + int maxY = Math.min(worldHeight - 1, (int) Math.ceil(effectiveVerticalRange.max())); + if (worldYRange != null) { + int rangeMinY = (int) Math.floor(worldYRange.min() - minHeight); + int rangeMaxY = (int) Math.ceil(worldYRange.max() - minHeight); + minY = Math.max(minY, rangeMinY); + maxY = Math.min(maxY, rangeMaxY); + } + int sampleStep = Math.max(1, profile.sampleStep()); + boolean exactSampling = sampleStep <= 2; + boolean adaptiveSampling = exactSampling && profile.adaptiveSampling(); + int adaptiveSampleStep = Math.max(2, profile.adaptiveSampleStep()); + double adaptiveThresholdMargin = Math.max(0D, profile.adaptiveThresholdMargin()); + int surfaceClearance = Math.max(0, profile.surfaceClearance()); + int surfaceBreakDepth = Math.max(0, profile.surfaceBreakDepth()); + double surfaceBreakNoiseThreshold = profile.surfaceBreakNoiseThreshold(); + double surfaceBreakThresholdBoost = Math.max(0, profile.surfaceBreakThresholdBoost()); + boolean allowSurfaceBreak = profile.allowSurfaceBreak(); + if (maxY < minY) { + return 0; + } + + MantleChunk chunk = mantle.chunk(chunkX, chunkZ); + if (chunk == null) { + return 0; + } + + int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int[] columnMaxY = scratch.columnMaxY; + int[] fluidMaxY = scratch.fluidMaxY; + int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; + boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; + boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; + double[] columnThreshold = scratch.columnThreshold; + double[] clampedWeights = scratch.clampedColumnWeights; + double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); + prepareSurfaceClosureThresholdTable(scratch, minY, maxY); + MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); + prepareSectionCaches(scratch, minY, maxY); + + // The threshold noise is constant for the carver, so it is built once (in the constructor) and the + // min==max / flat-style short circuits are decided here, as Iris's styled range has always decided them. + StyledRange densityThreshold = profile.densityThreshold(); + double thresholdMin = densityThreshold.min(); + double thresholdMax = densityThreshold.max(); + double thresholdBias = profile.thresholdBias(); + NoiseSampler thresholdDensity = null; + double constantThreshold = 0D; + if (thresholdMin == thresholdMax) { + constantThreshold = thresholdMin; + } else if (NoiseStyle.FLAT.equals(densityThreshold.style().style())) { + constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); + } else { + thresholdDensity = thresholdNoise; + } + + for (int lx = 0; lx < 16; lx++) { + int x = x0 + lx; + for (int lz = 0; lz < 16; lz++) { + int z = z0 + lz; + int index = PowerOfTwoCoordinates.packLocal16(lx, lz); + int columnSurfaceY; + columnSurfaceY = surfaceHeights[index]; + int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; + int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); + boolean breakColumn = allowSurfaceBreak + && surfaceBreakDensity.signed(x, z) >= surfaceBreakNoiseThreshold; + int columnTopY = breakColumn + ? Math.min(maxY, Math.max(minY, columnSurfaceY)) + : clearanceTopY; + + columnMaxY[index] = columnTopY; + fluidMaxY[index] = allowFluid + ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) + : Integer.MIN_VALUE; + surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); + surfaceBreakColumn[index] = breakColumn; + surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; + columnThreshold[index] = (thresholdDensity == null + ? constantThreshold + : thresholdMin + (thresholdDensity.sample(x, z) * (thresholdMax - thresholdMin))) - thresholdBias; + clampedWeights[index] = clampColumnWeight(columnWeights[index]); } + } - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); - if (chunk == null) { - return 0; - } - - int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int[] columnMaxY = scratch.columnMaxY; - int[] fluidMaxY = scratch.fluidMaxY; - int[] surfaceBreakFloorY = scratch.surfaceBreakFloorY; - boolean[] surfaceBreakColumn = scratch.surfaceBreakColumn; - boolean[] surfaceCeilingColumn = scratch.surfaceCeilingColumn; - double[] columnThreshold = scratch.columnThreshold; - double[] clampedWeights = scratch.clampedColumnWeights; - double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); - prepareSurfaceClosureThresholdTable(scratch, minY, maxY); - MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); - prepareSectionCaches(scratch, minY, maxY); - - // IrisStyledRange.get() resolves its CNG per call, which costs a cache-key allocation, - // a capturing lambda and a shared LRU touch. The CNG is constant for (thresholdRng, data), - // so resolve it once here and replicate the min==max / isFlat short circuits verbatim. - IrisStyledRange densityThreshold = resolved.densityThreshold(); - double thresholdMin = densityThreshold.getMin(); - double thresholdMax = densityThreshold.getMax(); - double thresholdBias = profile.thresholdBias(); - CNG thresholdDensity = null; - double constantThreshold = 0D; - if (thresholdMin == thresholdMax) { - constantThreshold = thresholdMin; - } else if (densityThreshold.getStyle().isFlat()) { - constantThreshold = M.lerp(thresholdMin, thresholdMax, 0.5); + int carved; + if (exactSampling) { + if (adaptiveSampling) { + carved = carvePassAdaptive( + chunk, + x0, + z0, + minY, + maxY, + adaptiveSampleStep, + adaptiveThresholdMargin, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); } else { - thresholdDensity = densityThreshold.getStyle().create(thresholdRng, data); - } - - for (int lx = 0; lx < 16; lx++) { - int x = x0 + lx; - for (int lz = 0; lz < 16; lz++) { - int z = z0 + lz; - int index = PowerOfTwoCoordinates.packLocal16(lx, lz); - int columnSurfaceY; - if (precomputedSurfaceHeights != null && precomputedSurfaceHeights.length > index) { - columnSurfaceY = precomputedSurfaceHeights[index]; - } else { - columnSurfaceY = engine.getHeight(x, z); - } - int unclampedClearanceTopY = columnSurfaceY - surfaceClearance; - int clearanceTopY = Math.min(maxY, Math.max(minY, unclampedClearanceTopY)); - boolean breakColumn = allowSurfaceBreak - && surfaceBreakDensity.noiseFastSigned2D(x, z) >= surfaceBreakNoiseThreshold; - int columnTopY = breakColumn - ? Math.min(maxY, Math.max(minY, columnSurfaceY)) - : clearanceTopY; - - columnMaxY[index] = columnTopY; - fluidMaxY[index] = allowFluid - ? Math.min(fluidHeight, columnSurfaceY - fluidMinDepthBelowSurface) - : Integer.MIN_VALUE; - surfaceBreakFloorY[index] = Math.max(minY, columnSurfaceY - surfaceBreakDepth); - surfaceBreakColumn[index] = breakColumn; - surfaceCeilingColumn[index] = !breakColumn && unclampedClearanceTopY <= maxY; - columnThreshold[index] = (thresholdDensity == null - ? constantThreshold - : thresholdDensity.fitDouble(thresholdMin, thresholdMax, x, z)) - thresholdBias; - clampedWeights[index] = clampColumnWeight(columnWeights[index]); - } - } - - int carved; - if (exactSampling) { - if (adaptiveSampling) { - carved = carvePassAdaptive( - chunk, - x0, - z0, - minY, - maxY, - adaptiveSampleStep, - adaptiveThresholdMargin, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } else { - carved = carvePassExact( - chunk, - x0, - z0, - minY, - maxY, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } - } else { - int latticeStep = sampleStep; - carved = carvePassLattice( + carved = carvePassExact( chunk, x0, z0, minY, maxY, - latticeStep, surfaceBreakThresholdBoost, columnMaxY, fluidMaxY, @@ -388,37 +319,60 @@ public class IrisCaveCarver3D { 0D, false ); - if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { - carved += carvePassFallback( - chunk, - x0, - z0, - minY, - maxY, - sampleStep, - surfaceBreakThresholdBoost, - columnMaxY, - fluidMaxY, - surfaceFluidBoundaryStartY, - surfaceBreakFloorY, - surfaceBreakColumn, - columnThreshold, - clampedWeights, - verticalEdgeFade, - matterByY, - fluidRequiresFloor ? fluidSupportPlan : null, - resolvedMinWeight, - resolvedThresholdPenalty, - 0D, - false - ); - } } - - return carved; - } finally { - engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); + } else { + int latticeStep = sampleStep; + carved = carvePassLattice( + chunk, + x0, + z0, + minY, + maxY, + latticeStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { + carved += carvePassFallback( + chunk, + x0, + z0, + minY, + maxY, + sampleStep, + surfaceBreakThresholdBoost, + columnMaxY, + fluidMaxY, + surfaceFluidBoundaryStartY, + surfaceBreakFloorY, + surfaceBreakColumn, + columnThreshold, + clampedWeights, + verticalEdgeFade, + matterByY, + fluidRequiresFloor ? fluidSupportPlan : null, + resolvedMinWeight, + resolvedThresholdPenalty, + 0D, + false + ); + } } + + return carved; } private int carvePassExact( @@ -1670,7 +1624,7 @@ public class IrisCaveCarver3D { } private boolean classifyDensityPointNoWarpNoModules(int x, int y, int z, double thresholdLimit) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; if ((density + detailMinContribution) > thresholdLimit) { return false; } @@ -1678,7 +1632,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + density += detailDensity.signed(x, y, z) * detailWeight; return density <= thresholdLimit; } @@ -1696,7 +1650,7 @@ public class IrisCaveCarver3D { return classifyDensityPointNoWarpNoModules(x, y, z, thresholdLimit); } - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { return false; } @@ -1704,7 +1658,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + density += detailDensity.signed(x, y, z) * detailWeight; if ((density + remainingMin[0]) > thresholdLimit) { return false; } @@ -1746,7 +1700,7 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; if ((density + detailMinContribution) > thresholdLimit) { return false; } @@ -1754,7 +1708,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; return density <= thresholdLimit; } @@ -1782,7 +1736,7 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; if ((density + detailMinContribution + remainingMin[0]) > thresholdLimit) { return false; } @@ -1790,7 +1744,7 @@ public class IrisCaveCarver3D { return true; } - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; if ((density + remainingMin[0]) > thresholdLimit) { return false; } @@ -2008,8 +1962,8 @@ public class IrisCaveCarver3D { } private double sampleDensityNoWarpNoModules(int x, int y, int z) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; return density * inverseNormalization; } @@ -2020,11 +1974,11 @@ public class IrisCaveCarver3D { } CaveFieldModuleState[] localModules = scratch.activeModules; - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.noiseFastSigned3D(x, y, z) - module.threshold; + double moduleDensity = module.density.signed(x, y, z) - module.threshold; if (module.invert) { moduleDensity = -moduleDensity; } @@ -2045,8 +1999,8 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; return density * inverseNormalization; } @@ -2070,11 +2024,11 @@ public class IrisCaveCarver3D { double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; for (int moduleIndex = 0; moduleIndex < activeModuleCount; moduleIndex++) { CaveFieldModuleState module = localModules[moduleIndex]; - double moduleDensity = module.density.noiseFastSigned3D(warpedX, warpedY, warpedZ) - module.threshold; + double moduleDensity = module.density.signed(warpedX, warpedY, warpedZ) - module.threshold; if (module.invert) { moduleDensity = -moduleDensity; } @@ -2098,8 +2052,8 @@ public class IrisCaveCarver3D { scratch.warpCacheX[slot] = sx; scratch.warpCacheY[slot] = sy; scratch.warpCacheZ[slot] = sz; - scratch.warpCacheA[slot] = warpDensity.noiseFastSigned3D(sx, sy, sz); - scratch.warpCacheB[slot] = warpDensity.noiseFastSigned3D(sx + 31.37D, sy - 17.21D, sz + 23.91D); + scratch.warpCacheA[slot] = warpDensity.signed(sx, sy, sz); + scratch.warpCacheB[slot] = warpDensity.signed(sx + 31.37D, sy - 17.21D, sz + 23.91D); return slot; } @@ -2183,7 +2137,6 @@ public class IrisCaveCarver3D { MatterCavern[] matterByY = scratch.matterByY; boolean allowLava = profile.allowLava(); - int lavaHeight = engine.getDimension().getCaveLavaHeight(); for (int y = minY; y <= maxY; y++) { int offset = y - minY; @@ -2215,7 +2168,7 @@ public class IrisCaveCarver3D { private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { double depthFactor = Math.max(0D, Math.min(1.5D, (fluidHeight - y) / 48D)); double cutoff = 0.35D + (depthFactor * 0.2D); - if (detailDensity.noiseFastSigned3D(x, y * 0.5D, z) <= cutoff) { + if (detailDensity.signed(x, y * 0.5D, z) <= cutoff) { return false; } return !fluidRequiresFloor || hasAquiferCupSupport(scratch, x, y, z, localThreshold); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 87f2a3f23..a1696d4fb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; @@ -585,7 +586,7 @@ public class ObjectPlacing { underwater, writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), candidateY, - engine.getDimension().getCaveLavaHeight())) { + engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT))) { continue; } return new CavePlacementAnchor(candidateX, candidateY, candidateZ); diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java b/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java new file mode 100644 index 000000000..58a3af38a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveColumnMask.java @@ -0,0 +1,95 @@ +/* + * 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.modifier; + +import java.util.Arrays; + +final class CarveColumnMask { + private long[] words = new long[8]; + private int maxWord = -1; + + void add(int y) { + if (y < 0) { + return; + } + + int wordIndex = y >> 6; + if (wordIndex >= words.length) { + words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1)); + } + + words[wordIndex] |= 1L << (y & 63); + if (wordIndex > maxWord) { + maxWord = wordIndex; + } + } + + int nextSetBit(int fromBit) { + if (maxWord < 0) { + return -1; + } + + int startBit = Math.max(0, fromBit); + int wordIndex = startBit >> 6; + if (wordIndex > maxWord) { + return -1; + } + + long word = words[wordIndex] & (-1L << (startBit & 63)); + while (true) { + if (word != 0L) { + return (wordIndex << 6) + Long.numberOfTrailingZeros(word); + } + + wordIndex++; + if (wordIndex > maxWord) { + return -1; + } + word = words[wordIndex]; + } + } + + boolean isEmpty() { + return maxWord < 0; + } + + boolean contains(int y) { + if (y < 0) { + return false; + } + + int wordIndex = y >> 6; + if (wordIndex > maxWord) { + return false; + } + + return (words[wordIndex] & (1L << (y & 63))) != 0L; + } + + void clear() { + if (maxWord < 0) { + return; + } + + for (int index = 0; index <= maxWord; index++) { + words[index] = 0L; + } + maxWord = -1; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 41dd78bc4..0c484456d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -18,36 +18,50 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CarvingBiomeSettings; import art.arcane.iris.builtin.carve.CarvingEnabledSettings; import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.carve.CaveProfile; -import com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.core.modules.IrisMantleChunk; +import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings; +import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.iris.engine.mantle.components.CaveCarving; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import com.volmit.FeatureRegistry; +import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; -import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.FeatureAttachment.Target; +import com.volmit.hunk.Hunk; +import com.volmit.block.BlockState; import com.volmit.service.CaveBiomes; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; +import java.util.function.Function; /** * Module {@code iris:carve}: caves. A mantle stage plans them into the mantle, reaching one block into each * neighboring chunk where blended cave walls cross the border; a chunk stage later cuts them out of the chunk's * terrain. The mantle stage is a port of what was Iris's carving mantle component, its work done by - * {@link CaveCarving}, one per engine runtime. The chunk stage's work is done by {@link CaveApplying}. + * {@link CaveCarving}, one per world. The chunk stage's work is done by {@link CaveApplying}. */ public final class CarveModule implements IrisModule { private static final String VERSION = "built-in"; /** Blended cave walls reach one block past the chunk. */ private static final int CAVE_REACH_BLOCKS = 1; private static final int CHUNK_SHIFT = 4; + /** The centre column of a chunk, where per-chunk settings are read. */ + private static final int CHUNK_CENTRE_BLOCKS = 7; @Override public ModuleInfo info() { @@ -61,6 +75,8 @@ public final class CarveModule implements IrisModule { registry.registerSettings(CarvingEnabledSettings.class); registry.registerSettings(CarvingBiomeSettings.class); registry.registerSettings(CaveDepthSettings.class); + registry.registerSettings(CaveLavaHeightSettings.class); + registry.registerSettings(UpperDimensionCarvingSettings.class); registry.registerService(CaveBiomes.class, new CaveBiomeBands()); } @@ -71,28 +87,58 @@ public final class CarveModule implements IrisModule { } private static void planCaves(MantleStageContext context) { - IrisMantleChunk chunk = IrisMantleChunk.current(); - if (!carves(chunk.engine().getDimension())) { + if (!carves(context.settings(), context.originX(), context.originZ())) { return; } - chunk.state(CaveCarving.class, CaveCarving::new).carve(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + MatterMantle mantle = MatterMantle.of(context.mantle()); + caveCarving(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) + .carve(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT); } private static void applyCaves(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - if (chunk.bypassesMantleStages()) { - return; - } - ModuleLog log = context.log(); - chunk.state(CaveApplying.class, generating -> new CaveApplying(generating, log)).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, - chunk.blocks(), chunk.multicore(), chunk.context()); + MatterMantle mantle = MatterMantle.of(context.mantle()); + Hunk blocks = context.hunk(BlockState.class); + caveApplying(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) + .apply(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT, blocks); + } + + private static CaveCarving caveCarving(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { + return world.state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, terrain), + upperDimensionCarving(settings, originX, originZ))); + } + + private static CaveApplying caveApplying(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { + return world.state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, terrain), + upperDimensionCarving(settings, originX, originZ))); + } + + /** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */ + private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) { + int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); + return new CarveWorld(world.resources().noise(), IrisSeed.CARVE.of(world), terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, + world.minHeight()); + } + + private static boolean upperDimensionCarving(FeatureSettings settings, int originX, int originZ) { + return dimensionEntry(settings, UpperDimensionCarvingSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS) + .map(UpperDimensionCarvingSettings::enabled).orElse(false); } /** * A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents} * also does: Iris then skips this stage's mantle pass like any disabled component. */ - private static boolean carves(IrisDimension dimension) { - return dimension.getModuleSettings().find(CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true); + private static boolean carves(FeatureSettings settings, int originX, int originZ) { + return dimensionEntry(settings, CarvingEnabledSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS) + .map(CarvingEnabledSettings::enabled).orElse(true); + } + + private static Optional dimensionEntry(FeatureSettings settings, Class type, int x, int z) { + return settings.at(type, x, z).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).findFirst(); + } + + private static V dimensionSetting(PackWorld world, Class type, Function read, V fallback) { + return world.settings().declared(type).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).map(read) + .findFirst().orElse(fallback); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java b/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java new file mode 100644 index 000000000..8b036ebc7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java @@ -0,0 +1,166 @@ +/* + * 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.modifier; + +import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import art.arcane.volmlib.util.matter.MatterCavern; + +import java.util.Arrays; + +final class CarveWallBuffer { + private static final int EMPTY_KEY = -1; + private static final double LOAD_FACTOR = 0.75D; + + private int[] keys; + private MatterCavern[] values; + private int mask; + private int resizeAt; + private int size; + + CarveWallBuffer(int expectedSize) { + int capacity = 1; + int minimumCapacity = Math.max(8, expectedSize); + while (capacity < minimumCapacity) { + capacity <<= 1; + } + + keys = new int[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new MatterCavern[capacity]; + mask = capacity - 1; + resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); + } + + void put(int x, int y, int z, MatterCavern value) { + int key = pack(x, y, z); + int index = mix(key) & mask; + + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + keys[index] = key; + values[index] = value; + size++; + if (size >= resizeAt) { + resize(); + } + return; + } + + if (existingKey == key) { + values[index] = value; + return; + } + + index = (index + 1) & mask; + } + } + + MatterCavern get(int x, int y, int z) { + int key = pack(x, y, z); + int index = mix(key) & mask; + while (true) { + int existingKey = keys[index]; + if (existingKey == EMPTY_KEY) { + return null; + } + if (existingKey == key) { + return values[index]; + } + index = (index + 1) & mask; + } + } + + void forEach(Consumer consumer) { + for (int index = 0; index < keys.length; index++) { + int key = keys[index]; + if (key == EMPTY_KEY) { + continue; + } + + MatterCavern cavern = values[index]; + if (cavern != null) { + consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern); + } + } + } + + void clear() { + Arrays.fill(keys, EMPTY_KEY); + Arrays.fill(values, null); + size = 0; + } + + private void resize() { + int[] oldKeys = keys; + MatterCavern[] oldValues = values; + int nextCapacity = oldKeys.length << 1; + keys = new int[nextCapacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new MatterCavern[nextCapacity]; + mask = nextCapacity - 1; + resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); + size = 0; + + for (int index = 0; index < oldKeys.length; index++) { + int key = oldKeys[index]; + MatterCavern value = oldValues[index]; + if (key != EMPTY_KEY && value != null) { + reinsert(key, value); + } + } + } + + private void reinsert(int key, MatterCavern value) { + int index = mix(key) & mask; + while (keys[index] != EMPTY_KEY) { + index = (index + 1) & mask; + } + + keys[index] = key; + values[index] = value; + size++; + } + + private int pack(int x, int y, int z) { + return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15); + } + + private int unpackX(int key) { + return PowerOfTwoCoordinates.unpackLocal16X(key & 255); + } + + private int unpackY(int key) { + return key >> 8; + } + + private int unpackZ(int key) { + return PowerOfTwoCoordinates.unpackLocal16Z(key); + } + + private int mix(int value) { + int mixed = value * 0x9E3779B9; + return mixed ^ (mixed >>> 16); + } + + @FunctionalInterface + interface Consumer { + void accept(int x, int y, int z, MatterCavern cavern); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 306822d7d..a939da5e5 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -18,107 +18,178 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.builtin.CaveDressing; +import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.engine.decorator.BiomeDecorators; -import art.arcane.iris.engine.terrain.BiomeLayers; -import art.arcane.iris.engine.terrain.TerrainPalettes; -import art.arcane.iris.engine.decorator.IrisCeilingDecorator; -import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.mantle.runtime.Mantle; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.mantle.runtime.TectonicPlate; import art.arcane.volmlib.util.math.BlockPosition; -import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.volmlib.util.matter.MatterMarker; import art.arcane.volmlib.util.matter.slices.MarkerMatter; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import art.arcane.iris.engine.mantle.components.CarveWorld; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.hunk.Hunk; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKey; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; import lombok.Data; -import art.arcane.iris.spi.PlatformBlockState; +import java.util.List; import java.util.Map; /** * Applies the caves the mantle planned to a chunk's blocks for {@link CarveModule}: carves each cave zone, paints * its floor and ceiling with the cave biomes' layers, fills fluids and lava and decorates the cave surfaces. - * One per engine runtime, holding the carve stream's random. + * One per world, holding the carve stream's random. */ public class CaveApplying { private static final byte LIQUID_FLUID = 1; + private static final byte LIQUID_FORCED_AIR = 3; private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(IrisCarveScratch::new); private static final int CAVE_BIOME_BLEND_RADIUS = 3; private static final int CAVE_BIOME_BLEND_CENTER_WEIGHT = 4; private static final int CAVE_BIOME_BLEND_TOTAL_WEIGHT = 8; + private static final int CAVE_BIOME_CACHE_SIZE = 2048; + private static final int CHUNK_AREA = 256; + private static final int LAYER_DEPTH = 3; + private static final long CEILING_MARKER_SALT = 0x9E3779B97F4A7C15L; + private static final long FLOOR_MARKER_SALT = 0xC2B2AE3D27D4EB4FL; private static final MatterCavern BASIC_CAVERN = new MatterCavern(true, "", (byte) 0); - private final Engine engine; - private final RNG rng; - private final PlatformBlockState AIR = B.getState("CAVE_AIR"); - private final PlatformBlockState LAVA = B.getState("LAVA"); - private final BiomeDecorators decorators; - private final BiomeLayers layers; - private final TerrainPalettes palettes; - private final IrisSurfaceDecorator surfaceDecorator; - private final IrisCeilingDecorator ceilingDecorator; - public CaveApplying(Engine engine, ModuleLog log) { - this.engine = engine; - rng = new RNG(engine.getSeedManager().getCarve()); - decorators = BiomeDecorators.of(engine); - layers = BiomeLayers.of(engine, log); - palettes = TerrainPalettes.of(engine); - surfaceDecorator = new IrisSurfaceDecorator(engine); - ceilingDecorator = new IrisCeilingDecorator(engine); + private final CarveWorld world; + private final PackResources resources; + private final BlockRegistry blocks; + private final CaveDressing dressing; + private final boolean upperDimensionCarving; + private final RNG rng; + private final BlockState caveAir; + private final BlockState plainAir; + private final BlockState lava; + + public CaveApplying(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.resources = packWorld.resources(); + this.blocks = resources.blocks(); + this.dressing = CaveDressing.of(packWorld); + this.upperDimensionCarving = upperDimensionCarving; + this.rng = new RNG(world.carveSeed()); + this.caveAir = blocks.resolve("minecraft:cave_air"); + this.plainAir = blocks.resolve("minecraft:air"); + this.lava = blocks.resolve("minecraft:lava"); } - /** Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}. */ - @ChunkCoordinates - public void apply(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start(); - Mantle mantle = engine.getMantle().getMantle(); - Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(2048); - IrisCarveScratch scratch = SCRATCH.get(); - scratch.reset(); - CarveWallBuffer walls = scratch.walls; - CarveColumnMask[] columnMasks = scratch.columnMasks; - CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; - int[] surfaceHeights = scratch.surfaceHeights; - Map customBiomeCache = scratch.customBiomeCache; - UpperDimensionContext upperCtx = engine.getUpperContext(); - boolean protectUpper = upperCtx != null && !engine.getDimension().isUpperDimensionCarving(); - int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; - int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(x); - int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(z); - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - surfaceHeights[columnIndex] = context.getRoundedHeight(localX, localZ); - if (protectUpper) { - int worldX = localX + chunkBlockX; - int worldZ = localZ + chunkBlockZ; - int rawUpper = upperCtx.getUpperSurfaceY(worldX, worldZ); - int gap = engine.getDimension().getUpperDimensionGap(); - upperSurfaceHeights[columnIndex] = Math.max(rawUpper, surfaceHeights[columnIndex] + gap); - } + /** + * Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}, whose blocks are {@code output}; the caves are in + * {@code mantle}, and {@code terrain} gives the heights and cave biomes around the chunk. + */ + public void apply(MatterMantle mantle, TerrainSampler terrain, int x, int z, Hunk output) { + MantleChunk mantleChunk = mantle.chunk(x, z); + if (mantleChunk == null) { + return; + } + new Application(mantle, mantleChunk, terrain, x, z, output).run(); + } + + static boolean hasExplicitCarveIntent(MatterCavern cavern) { + return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == LIQUID_FORCED_AIR); + } + + static boolean isFluidIntent(MatterCavern cavern) { + return cavern != null && cavern.getLiquid() == LIQUID_FLUID; + } + + static boolean shouldPreserveExistingFluid(MatterCavern cavern, boolean existingIsFluid) { + return existingIsFluid && !hasExplicitCarveIntent(cavern); + } + + static boolean usesDefaultLava(int caveLavaHeight, int y) { + return y <= caveLavaHeight; + } + + static boolean isUnsupportedSurfaceOre(boolean surfaceIsOre, boolean belowIsSolid) { + return surfaceIsOre && !belowIsSolid; + } + + static BlockState resolveExplicitCarveState(MatterCavern cavern, BlockState fluid, BlockState lava, BlockState air) { + if (cavern == null) { + return null; + } + if (isFluidIntent(cavern)) { + return fluid; + } + if (cavern.isLava()) { + return lava; + } + return cavern.getLiquid() == LIQUID_FORCED_AIR ? air : null; + } + + static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, BlockState layer, CaveBlockClasses classes) { + return !classes.hasGravity(layer) || y > 0 && classes.isSolid(output.get(x, y - 1, z)); + } + + static boolean hasStableCaveFloorSupport(Hunk output, int x, int floorY, int z, CaveBlockClasses classes) { + if (floorY <= 0) { + return false; + } + BlockState support = output.get(x, floorY - 1, z); + if (!classes.isSolid(support)) { + return false; + } + return !classes.hasGravity(support) || floorY > 1 && classes.isSolid(output.get(x, floorY - 2, z)); + } + + /** One chunk's application: the chunk's blocks, mantle and the caches its passes share. */ + final class Application { + private final MatterMantle mantle; + private final MantleChunk mantleChunk; + private final TerrainSampler terrain; + private final int chunkX; + private final int chunkZ; + private final Hunk output; + private final CaveBlockClasses classes = new CaveBlockClasses(blocks); + private final CaveBiomeCache caveBiomeCache = new CaveBiomeCache(CAVE_BIOME_CACHE_SIZE); + private final IrisCarveScratch scratch = SCRATCH.get(); + + Application(MatterMantle mantle, MantleChunk mantleChunk, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output) { + this.mantle = mantle; + this.mantleChunk = mantleChunk; + this.terrain = terrain; + this.chunkX = chunkX; + this.chunkZ = chunkZ; + this.output = output; } - MantleChunk mantleChunk = mantle.getChunk(x, z).use(); - try { - PrecisionStopwatch resolveStopwatch = PrecisionStopwatch.start(); - int worldHeightSpan = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - int caveLavaHeight = engine.getDimension().getCaveLavaHeight(); + void run() { + scratch.reset(); + CarveWallBuffer walls = scratch.walls; + CarveColumnMask[] columnMasks = scratch.columnMasks; + CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; + int[] surfaceHeights = scratch.surfaceHeights; + Map customBiomeCache = scratch.customBiomeCache; + int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + boolean protectUpper = !upperDimensionCarving && terrain.upperDimensionY(chunkBlockX, chunkBlockZ).isPresent(); + int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + int worldX = localX + chunkBlockX; + int worldZ = localZ + chunkBlockZ; + surfaceHeights[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, worldZ)); + if (protectUpper) { + upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt(); + } + } + + int worldHeightSpan = world.height(); + int caveLavaHeight = world.lavaHeight(); mantleChunk.iterate(MatterCavern.class, (xx, yy, zz, cavern) -> { if (cavern == null) { return; @@ -136,10 +207,10 @@ public class CaveApplying { return; } - PlatformBlockState current = output.getRaw(rx, yy, rz); + BlockState current = output.get(rx, yy, rz); boolean explicitCarveIntent = hasExplicitCarveIntent(cavern); - if (shouldPreserveExistingFluid(cavern, current)) { + if (shouldPreserveExistingFluid(cavern, classes.isFluid(current))) { return; } @@ -149,608 +220,466 @@ public class CaveApplying { scratch.customCaveBiomePresent = true; } - if (current.isAir() && !explicitCarveIntent) { + if (classes.isAir(current) && !explicitCarveIntent) { return; } if (explicitCarveIntent) { - // Only a fluid cavern consumes the fluid sample, and on the maintenance path that - // sample is a full procedural stream evaluation, so never take it per voxel. - PlatformBlockState fluid = isFluidIntent(cavern) ? palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; - output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR)); + // Only a fluid cavern consumes the fluid sample, so never take it per voxel. + BlockState fluid = isFluidIntent(cavern) ? dressing.fluidAt(output, chunkBlockX + rx, chunkBlockZ + rz) : null; + BlockState carved = resolveExplicitCarveState(cavern, fluid, lava, caveAir); + output.set(rx, yy, rz, carved == null ? plainAir : carved); } else if (usesDefaultLava(caveLavaHeight, yy)) { - output.setRaw(rx, yy, rz, LAVA); + output.set(rx, yy, rz, lava); } else { - output.setRaw(rx, yy, rz, AIR); + output.set(rx, yy, rz, caveAir); } }); if (scratch.customCaveBiomePresent) { - addInternalWallsFromMantle(mantleChunk, walls, columnMasks); + addInternalWallsFromMantle(walls, columnMasks); } else { addInternalWallsFromMasks(walls, columnMasks); } - addCrossChunkBoundaryWalls(mantle, mantleChunk, walls, boundaryMasks, x, z, surfaceHeights); - engine.getMetrics().getCarveResolve().put(resolveStopwatch.getMilliseconds()); + addCrossChunkBoundaryWalls(walls, boundaryMasks, surfaceHeights); - PrecisionStopwatch applyStopwatch = PrecisionStopwatch.start(); - try { - walls.forEach((rx, yy, rz, cavern) -> { - int worldX = rx + chunkBlockX; - int worldZ = rz + chunkBlockZ; - String customBiome = cavern.getCustomBiome(); - IrisBiome biome = customBiome.isEmpty() - ? resolveCaveBiome(caveBiomeCache, worldX, yy, worldZ) - : resolveCustomBiome(customBiomeCache, customBiome); + walls.forEach((rx, yy, rz, cavern) -> { + int worldX = rx + chunkBlockX; + int worldZ = rz + chunkBlockZ; + String customBiome = cavern.getCustomBiome(); + ResourceId biome = customBiome.isEmpty() + ? resolveCaveBiome(worldX, yy, worldZ) + : resolveCustomBiome(customBiomeCache, customBiome); - if (biome != null) { - PlatformBlockState data = layers.wall(biome).get(rng, worldX, yy, worldZ); - int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); + if (biome != null) { + BlockState data = dressing.wall(output, biome, rng, worldX, yy, worldZ); + int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); - if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { - output.setRaw(rx, yy, rz, data); + if (data != null && classes.isSolid(output.get(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { + output.set(rx, yy, rz, data); + } + } + }); + + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + processColumnFromMask(columnMasks[columnIndex], columnIndex, customBiomeCache); + } + + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { + continue; + } + processBoundaryColumnFromMask(boundaryMasks[columnIndex], walls, columnIndex, customBiomeCache); + } + + // Surface-break carving must not leave an ore cap suspended across the opening. + for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { + int surfaceY = surfaceHeights[columnIndex]; + if (surfaceY <= 0 || surfaceY >= output.getHeight()) { + continue; + } + + int belowY = surfaceY - 1; + if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) { + continue; + } + + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & 15; + BlockState surface = output.get(localX, surfaceY, localZ); + BlockState below = output.get(localX, belowY, localZ); + if (isUnsupportedSurfaceOre(classes.isOre(surface), classes.isSolid(below))) { + output.set(localX, surfaceY, localZ, caveAir); + } + } + } + + private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { + walls.put(rx, yy, rz + 1, BASIC_CAVERN); + } + if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { + walls.put(rx + 1, yy, rz, BASIC_CAVERN); + } + if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { + walls.put(rx, yy, rz - 1, BASIC_CAVERN); + } + if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { + walls.put(rx - 1, yy, rz, BASIC_CAVERN); + } + yy = columnMask.nextSetBit(yy + 1); + } + } + } + + private void addInternalWallsFromMantle(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + CarveColumnMask columnMask = columnMasks[columnIndex]; + if (columnMask.isEmpty()) { + continue; + } + + int rx = columnIndex >> 4; + int rz = columnIndex & 15; + int yy = columnMask.nextSetBit(0); + while (yy >= 0) { + MatterCavern cavern = mantleChunk.get(rx, yy, rz, MatterCavern.class); + if (cavern != null) { + if (rz < 15 && mantleChunk.get(rx, yy, rz + 1, MatterCavern.class) == null) { + walls.put(rx, yy, rz + 1, cavern); + } + if (rx < 15 && mantleChunk.get(rx + 1, yy, rz, MatterCavern.class) == null) { + walls.put(rx + 1, yy, rz, cavern); + } + if (rz > 0 && mantleChunk.get(rx, yy, rz - 1, MatterCavern.class) == null) { + walls.put(rx, yy, rz - 1, cavern); + } + if (rx > 0 && mantleChunk.get(rx - 1, yy, rz, MatterCavern.class) == null) { + walls.put(rx - 1, yy, rz, cavern); } } - }); - - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - processColumnFromMask(output, mantleChunk, mantle, columnMasks[columnIndex], columnIndex, x, z, caveBiomeCache, customBiomeCache); + yy = columnMask.nextSetBit(yy + 1); } - - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - if (boundaryMasks[columnIndex].isEmpty() || !columnMasks[columnIndex].isEmpty()) { - continue; - } - processBoundaryColumnFromMask(output, boundaryMasks[columnIndex], walls, columnIndex, x, z, caveBiomeCache, customBiomeCache); - } - - // Surface-break carving must not leave an ore cap suspended across the opening. - for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { - int surfaceY = surfaceHeights[columnIndex]; - if (surfaceY <= 0 || surfaceY >= output.getHeight()) { - continue; - } - - int belowY = surfaceY - 1; - if (!columnMasks[columnIndex].contains(belowY) && !boundaryMasks[columnIndex].contains(belowY)) { - continue; - } - - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - PlatformBlockState surface = output.getRaw(localX, surfaceY, localZ); - PlatformBlockState below = output.getRaw(localX, belowY, localZ); - if (isUnsupportedSurfaceOre(surface, below)) { - output.setRaw(localX, surfaceY, localZ, AIR); - } - } - } finally { - engine.getMetrics().getCarveApply().put(applyStopwatch.getMilliseconds()); } - } finally { - engine.getMetrics().getCave().put(caveStopwatch.getMilliseconds()); - mantleChunk.release(); } - } - static boolean hasExplicitCarveIntent(MatterCavern cavern) { - return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == 3); - } - - static boolean isFluidIntent(MatterCavern cavern) { - return cavern != null && cavern.getLiquid() == LIQUID_FLUID; - } - - static boolean shouldPreserveExistingFluid(MatterCavern cavern, PlatformBlockState current) { - return B.isFluid(current) && !hasExplicitCarveIntent(cavern); - } - - static boolean usesDefaultLava(int caveLavaHeight, int y) { - return y <= caveLavaHeight; - } - - static boolean isUnsupportedSurfaceOre(PlatformBlockState surface, PlatformBlockState below) { - return B.isOre(surface) && !B.isSolid(below); - } - - static PlatformBlockState resolveExplicitCarveState(MatterCavern cavern, PlatformBlockState fluid, - PlatformBlockState lava, PlatformBlockState air) { - if (cavern == null) { - return null; - } - if (isFluidIntent(cavern)) { - return fluid; - } - if (cavern.isLava()) { - return lava; - } - return cavern.getLiquid() == 3 ? air : null; - } - - private void addInternalWallsFromMasks(CarveWallBuffer walls, CarveColumnMask[] columnMasks) { - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - CarveColumnMask columnMask = columnMasks[columnIndex]; - if (columnMask.isEmpty()) { - continue; + private void addCrossChunkBoundaryWalls(CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, int[] surfaceHeights) { + int maxSurfaceY = 0; + for (int index = 0; index < surfaceHeights.length; index++) { + if (surfaceHeights[index] > maxSurfaceY) { + maxSurfaceY = surfaceHeights[index]; + } + } + int maxY = Math.min(world.height() - 1, maxSurfaceY + 1); + if (maxY < 1) { + return; } - int rx = columnIndex >> 4; + MantleChunk west = mantle.loadedChunk(chunkX - 1, chunkZ); + MantleChunk east = mantle.loadedChunk(chunkX + 1, chunkZ); + MantleChunk north = mantle.loadedChunk(chunkX, chunkZ - 1); + MantleChunk south = mantle.loadedChunk(chunkX, chunkZ + 1); + if (west == null && east == null && north == null && south == null) { + return; + } + + for (int yy = 1; yy <= maxY; yy++) { + for (int offset = 0; offset < 16; offset++) { + if (west != null) { + tryAddBoundaryWall(west, walls, boundaryMasks, 0, yy, offset, 15, offset); + } + if (east != null) { + tryAddBoundaryWall(east, walls, boundaryMasks, 15, yy, offset, 0, offset); + } + if (north != null) { + tryAddBoundaryWall(north, walls, boundaryMasks, offset, yy, 0, offset, 15); + } + if (south != null) { + tryAddBoundaryWall(south, walls, boundaryMasks, offset, yy, 15, offset, 0); + } + } + } + } + + private void tryAddBoundaryWall(MantleChunk neighborChunk, CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, + int localX, int yy, int localZ, int neighborX, int neighborZ) { + if (mantleChunk.get(localX, yy, localZ, MatterCavern.class) != null) { + return; + } + + MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class); + if (neighbor == null) { + return; + } + + walls.put(localX, yy, localZ, neighbor); + int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); + boundaryMasks[columnIndex].add(yy); + } + + private void processColumnFromMask(CarveColumnMask columnMask, int columnIndex, Map customBiomeCache) { + if (columnMask == null || columnMask.isEmpty()) { + return; + } + + int firstHeight = columnMask.nextSetBit(0); + if (firstHeight < 0) { + return; + } + + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int rz = columnIndex & 15; - int yy = columnMask.nextSetBit(0); - while (yy >= 0) { - if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { - walls.put(rx, yy, rz + 1, BASIC_CAVERN); + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + CaveZone zone = new CaveZone(); + zone.setFloor(firstHeight); + int buf = firstHeight - 1; + int y = firstHeight; + + while (y >= 0) { + if (y <= world.height()) { + if (y == buf + 1) { + buf = y; + zone.ceiling = buf; + } else { + if (zone.isValid(world.height())) { + processZone(zone, rx, rz, worldX, worldZ, customBiomeCache); + } + zone = new CaveZone(); + zone.setFloor(y); + buf = y; + } } - if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { - walls.put(rx + 1, yy, rz, BASIC_CAVERN); - } - if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { - walls.put(rx, yy, rz - 1, BASIC_CAVERN); - } - if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { - walls.put(rx - 1, yy, rz, BASIC_CAVERN); - } - yy = columnMask.nextSetBit(yy + 1); + + y = columnMask.nextSetBit(y + 1); + } + + if (zone.isValid(world.height())) { + processZone(zone, rx, rz, worldX, worldZ, customBiomeCache); } } - } - private void addInternalWallsFromMantle(MantleChunk mc, CarveWallBuffer walls, CarveColumnMask[] columnMasks) { - for (int columnIndex = 0; columnIndex < 256; columnIndex++) { - CarveColumnMask columnMask = columnMasks[columnIndex]; - if (columnMask.isEmpty()) { - continue; + private void processBoundaryColumnFromMask(CarveColumnMask boundaryMask, CarveWallBuffer walls, int columnIndex, + Map customBiomeCache) { + int firstHeight = boundaryMask.nextSetBit(0); + if (firstHeight < 0) { + return; } - int rx = columnIndex >> 4; + int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int rz = columnIndex & 15; - int yy = columnMask.nextSetBit(0); - while (yy >= 0) { - MatterCavern cavern = mc.get(rx, yy, rz, MatterCavern.class); - if (cavern != null) { - if (rz < 15 && mc.get(rx, yy, rz + 1, MatterCavern.class) == null) { - walls.put(rx, yy, rz + 1, cavern); - } - if (rx < 15 && mc.get(rx + 1, yy, rz, MatterCavern.class) == null) { - walls.put(rx + 1, yy, rz, cavern); - } - if (rz > 0 && mc.get(rx, yy, rz - 1, MatterCavern.class) == null) { - walls.put(rx, yy, rz - 1, cavern); - } - if (rx > 0 && mc.get(rx - 1, yy, rz, MatterCavern.class) == null) { - walls.put(rx - 1, yy, rz, cavern); - } - } - yy = columnMask.nextSetBit(yy + 1); - } - } - } + int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); + int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); + int zoneFloor = firstHeight; + int zoneCeiling = firstHeight; + int y = boundaryMask.nextSetBit(firstHeight + 1); - private void addCrossChunkBoundaryWalls( - Mantle mantle, - MantleChunk mc, - CarveWallBuffer walls, - CarveColumnMask[] boundaryMasks, - int chunkX, - int chunkZ, - int[] surfaceHeights - ) { - int baseX = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int baseZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int maxSurfaceY = 0; - for (int index = 0; index < surfaceHeights.length; index++) { - if (surfaceHeights[index] > maxSurfaceY) { - maxSurfaceY = surfaceHeights[index]; - } - } - int maxY = Math.min(engine.getWorld().maxHeight() - engine.getWorld().minHeight() - 1, maxSurfaceY + 1); - if (maxY < 1) { - return; - } - - MantleChunk west = existingMantleChunk(mantle, chunkX - 1, chunkZ); - MantleChunk east = existingMantleChunk(mantle, chunkX + 1, chunkZ); - MantleChunk north = existingMantleChunk(mantle, chunkX, chunkZ - 1); - MantleChunk south = existingMantleChunk(mantle, chunkX, chunkZ + 1); - if (west == null && east == null && north == null && south == null) { - return; - } - - for (int yy = 1; yy <= maxY; yy++) { - for (int offset = 0; offset < 16; offset++) { - if (west != null) { - tryAddBoundaryWall(mc, west, walls, boundaryMasks, 0, yy, offset, 15, offset); - } - if (east != null) { - tryAddBoundaryWall(mc, east, walls, boundaryMasks, 15, yy, offset, 0, offset); - } - if (north != null) { - tryAddBoundaryWall(mc, north, walls, boundaryMasks, offset, yy, 0, offset, 15); - } - if (south != null) { - tryAddBoundaryWall(mc, south, walls, boundaryMasks, offset, yy, 15, offset, 0); - } - } - } - } - - private void tryAddBoundaryWall( - MantleChunk mc, - MantleChunk neighborChunk, - CarveWallBuffer walls, - CarveColumnMask[] boundaryMasks, - int localX, - int yy, - int localZ, - int neighborX, - int neighborZ - ) { - if (mc.get(localX, yy, localZ, MatterCavern.class) != null) { - return; - } - - MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class); - if (neighbor == null) { - return; - } - - walls.put(localX, yy, localZ, neighbor); - int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - boundaryMasks[columnIndex].add(yy); - } - - private MantleChunk existingMantleChunk(Mantle mantle, int chunkX, int chunkZ) { - TectonicPlate plate = mantle.getLoadedRegions().get(Mantle.key(chunkX >> 5, chunkZ >> 5)); - if (plate == null || plate.isClosed()) { - return null; - } - return plate.get(chunkX & 31, chunkZ & 31); - } - - private void processColumnFromMask( - Hunk output, - MantleChunk mc, - Mantle mantle, - CarveColumnMask columnMask, - int columnIndex, - int chunkX, - int chunkZ, - Long2ObjectOpenHashMap caveBiomeCache, - Map customBiomeCache - ) { - if (columnMask == null || columnMask.isEmpty()) { - return; - } - - int firstHeight = columnMask.nextSetBit(0); - if (firstHeight < 0) { - return; - } - - int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int rz = columnIndex & 15; - int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); - int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); - CaveZone zone = new CaveZone(); - zone.setFloor(firstHeight); - int buf = firstHeight - 1; - int y = firstHeight; - - while (y >= 0) { - if (y <= engine.getHeight()) { - if (y == buf + 1) { - buf = y; - zone.ceiling = buf; + while (y >= 0) { + if (y == zoneCeiling + 1) { + zoneCeiling = y; } else { - if (zone.isValid(engine)) { - processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, caveBiomeCache, customBiomeCache); - } - zone = new CaveZone(); - zone.setFloor(y); - buf = y; + paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache); + zoneFloor = y; + zoneCeiling = y; } + y = boundaryMask.nextSetBit(y + 1); } - y = columnMask.nextSetBit(y + 1); + paintBoundaryZone(walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, customBiomeCache); } - if (zone.isValid(engine)) { - processZone(output, mc, mantle, zone, rx, rz, worldX, worldZ, caveBiomeCache, customBiomeCache); - } - } + private void paintBoundaryZone(CarveWallBuffer walls, int rx, int rz, int worldX, int worldZ, int zoneFloor, int zoneCeiling, + Map customBiomeCache) { + ResourceId floorBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, customBiomeCache); + ResourceId ceilingBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } - private void processBoundaryColumnFromMask( - Hunk output, - CarveColumnMask boundaryMask, - CarveWallBuffer walls, - int columnIndex, - int chunkX, - int chunkZ, - Long2ObjectOpenHashMap caveBiomeCache, - Map customBiomeCache - ) { - int firstHeight = boundaryMask.nextSetBit(0); - if (firstHeight < 0) { - return; - } + if (floorBiome != null) { + paintFloorLayers(floorBiome, rx, rz, worldX, worldZ, zoneFloor); + } - int rx = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int rz = columnIndex & 15; - int worldX = rx + PowerOfTwoCoordinates.chunkToBlock(chunkX); - int worldZ = rz + PowerOfTwoCoordinates.chunkToBlock(chunkZ); - int zoneFloor = firstHeight; - int zoneCeiling = firstHeight; - int y = boundaryMask.nextSetBit(firstHeight + 1); - - while (y >= 0) { - if (y == zoneCeiling + 1) { - zoneCeiling = y; - } else { - paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, caveBiomeCache, customBiomeCache); - zoneFloor = y; - zoneCeiling = y; + if (ceilingBiome != null) { + paintCeilingLayers(ceilingBiome, rx, rz, worldX, worldZ, zoneCeiling, world.height()); } - y = boundaryMask.nextSetBit(y + 1); } - paintBoundaryZone(output, walls, rx, rz, worldX, worldZ, zoneFloor, zoneCeiling, caveBiomeCache, customBiomeCache); - } - - private void paintBoundaryZone( - Hunk output, - CarveWallBuffer walls, - int rx, - int rz, - int worldX, - int worldZ, - int zoneFloor, - int zoneCeiling, - Long2ObjectOpenHashMap caveBiomeCache, - Map customBiomeCache - ) { - IrisBiome floorBiome = resolveCaveBoundaryBiome( - walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, - caveBiomeCache, customBiomeCache); - IrisBiome ceilingBiome = resolveCaveBoundaryBiome( - walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, - caveBiomeCache, customBiomeCache); - if (floorBiome == null && ceilingBiome == null) { - return; - } - - if (floorBiome != null) { - KList floorLayers = layers.generateLayers(floorBiome, - engine.getDimension(), worldX, worldZ, rng, 3, zoneFloor, engine.getData(), engine.getComplex()); - for (int i = 0; i < zoneFloor - 1; i++) { - if (!floorLayers.hasIndex(i)) { + /** Replaces the solid blocks under {@code floorY} with the layers of {@code floorBiome}. */ + private void paintFloorLayers(ResourceId floorBiome, int rx, int rz, int worldX, int worldZ, int floorY) { + List floorLayers = dressing.floorLayers(output, floorBiome, worldX, worldZ, rng, LAYER_DEPTH, floorY); + for (int i = 0; i < floorY - 1; i++) { + if (i >= floorLayers.size()) { break; } - int floorY = zoneFloor - i - 1; - if (floorY < 0) { - break; - } - PlatformBlockState existing = output.getRaw(rx, floorY, rz); - PlatformBlockState layer = floorLayers.get(i); - if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, floorY, rz, layer)) { + int y = floorY - i - 1; + BlockState layer = floorLayers.get(i); + BlockState existing = output.get(rx, y, rz); + if (layer == null || !classes.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, layer, classes)) { continue; } - if (B.isOre(existing)) { - output.setRaw(rx, floorY, rz, B.toDeepSlateOre(existing, layer)); - continue; - } - output.setRaw(rx, floorY, rz, layer); + output.set(rx, y, rz, classes.isOre(existing) ? dressing.deepSlateOre(output, existing, layer) : layer); } } - if (ceilingBiome != null) { - int worldMaxY = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - KList ceilingLayers = layers.generateCeilingLayers(ceilingBiome, - engine.getDimension(), worldX, worldZ, rng, 3, zoneCeiling, engine.getData(), engine.getComplex()); + /** Replaces the solid blocks over {@code ceilingY} with the cave ceiling layers of {@code ceilingBiome}, below {@code maxY}. */ + private void paintCeilingLayers(ResourceId ceilingBiome, int rx, int rz, int worldX, int worldZ, int ceilingY, int maxY) { + List ceilingLayers = dressing.ceilingLayers(output, ceilingBiome, worldX, worldZ, rng, LAYER_DEPTH, ceilingY); for (int i = 0; i < ceilingLayers.size(); i++) { - int ceilingY = zoneCeiling + i + 1; - if (ceilingY >= worldMaxY) { + int y = ceilingY + i + 1; + if (y >= maxY) { break; } - PlatformBlockState existing = output.getRaw(rx, ceilingY, rz); - if (!B.isSolid(existing)) { + BlockState layer = ceilingLayers.get(i); + BlockState existing = output.get(rx, y, rz); + if (layer == null || !classes.isSolid(existing)) { continue; } - PlatformBlockState layer = ceilingLayers.get(i); - if (B.isOre(existing)) { - output.setRaw(rx, ceilingY, rz, B.toDeepSlateOre(existing, layer)); - continue; - } - output.setRaw(rx, ceilingY, rz, layer); - } - } - } - - /** - * 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt). - * Deterministic per seed and position, thread-order independent, allocation free. - */ - private boolean markerRoll(int x, int y, int z, long salt) { - long h = (engine.getSeedManager().getCarve() + salt) ^ BlockPosition.toLong(x, y, z); - h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; - h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; - h ^= h >>> 31; - return (h & 15L) == 0L; - } - - private void processZone(Hunk output, MantleChunk mc, Mantle mantle, CaveZone zone, int rx, int rz, int xx, int zz, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { - int maxY = output.getHeight(); - - if (zone.ceiling + 1 < maxY && B.isDecorant(output.getRaw(rx, zone.ceiling + 1, rz))) { - output.setRaw(rx, zone.ceiling + 1, rz, AIR); - } - - if (B.isDecorant(output.getRaw(rx, zone.ceiling, rz))) { - output.setRaw(rx, zone.ceiling, rz, AIR); - } - - // Seed-derived and position-keyed, never Math.random(): these markers persist into the - // mantle and drive cave spawning, so the same seed must stamp the same markers on - // every run and every platform. Inline mix, no allocation on this hot path. - if (markerRoll(xx, zone.ceiling, zz, 0x9E3779B97F4A7C15L)) { - mantle.set(xx, zone.ceiling, zz, MarkerMatter.CAVE_CEILING); - } - - if (markerRoll(xx, zone.floor, zz, 0xC2B2AE3D27D4EB4FL)) { - mantle.set(xx, zone.floor, zz, MarkerMatter.CAVE_FLOOR); - } - - IrisBiome floorBiome = resolveCaveBoundaryBiome(mc, rx, zone.floor, rz, xx, zz, caveBiomeCache, customBiomeCache); - IrisBiome ceilingBiome = resolveCaveBoundaryBiome(mc, rx, zone.ceiling, rz, xx, zz, caveBiomeCache, customBiomeCache); - if (floorBiome == null && ceilingBiome == null) { - return; - } - - if (floorBiome != null) { - KList floorBlocks = layers.generateLayers(floorBiome, engine.getDimension(), xx, zz, rng, 3, zone.floor, engine.getData(), engine.getComplex()); - for (int i = 0; i < zone.floor - 1; i++) { - if (!floorBlocks.hasIndex(i)) { - break; - } - int y = zone.floor - i - 1; - PlatformBlockState block = floorBlocks.get(i); - PlatformBlockState existing = output.getRaw(rx, y, rz); - if (!B.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, block)) { - continue; - } - if (B.isOre(existing)) { - output.setRaw(rx, y, rz, B.toDeepSlateOre(existing, block)); - continue; - } - output.setRaw(rx, y, rz, block); + output.set(rx, y, rz, classes.isOre(existing) ? dressing.deepSlateOre(output, existing, layer) : layer); } } - if (ceilingBiome != null) { - KList ceilingBlocks = layers.generateCeilingLayers(ceilingBiome, engine.getDimension(), xx, zz, rng, 3, zone.ceiling, engine.getData(), engine.getComplex()); - for (int i = 0; i < ceilingBlocks.size(); i++) { - int cy = zone.ceiling + i + 1; - if (cy >= maxY) { - break; - } - PlatformBlockState block = ceilingBlocks.get(i); - PlatformBlockState existing = output.getRaw(rx, cy, rz); - if (!B.isSolid(existing)) { - continue; - } - if (B.isOre(existing)) { - output.setRaw(rx, cy, rz, B.toDeepSlateOre(existing, block)); - continue; - } - output.setRaw(rx, cy, rz, block); + /** + * 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt). + * Deterministic per seed and position, thread-order independent, allocation free. + */ + private boolean markerRoll(int x, int y, int z, long salt) { + long h = (world.carveSeed() + salt) ^ BlockPosition.toLong(x, y, z); + h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; + h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; + h ^= h >>> 31; + return (h & 15L) == 0L; + } + + private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map customBiomeCache) { + int maxY = output.getHeight(); + + if (zone.ceiling + 1 < maxY && classes.isDecorant(output.get(rx, zone.ceiling + 1, rz))) { + output.set(rx, zone.ceiling + 1, rz, caveAir); + } + + if (classes.isDecorant(output.get(rx, zone.ceiling, rz))) { + output.set(rx, zone.ceiling, rz, caveAir); + } + + // Seed-derived and position-keyed, never Math.random(): these markers persist into the + // mantle and drive cave spawning, so the same seed must stamp the same markers on + // every run and every platform. Inline mix, no allocation on this hot path. + if (markerRoll(xx, zone.ceiling, zz, CEILING_MARKER_SALT)) { + setMarker(rx, zone.ceiling, rz, MarkerMatter.CAVE_CEILING); + } + + if (markerRoll(xx, zone.floor, zz, FLOOR_MARKER_SALT)) { + setMarker(rx, zone.floor, rz, MarkerMatter.CAVE_FLOOR); + } + + ResourceId floorBiome = resolveCaveBoundaryBiome(rx, zone.floor, rz, xx, zz, customBiomeCache); + ResourceId ceilingBiome = resolveCaveBoundaryBiome(rx, zone.ceiling, rz, xx, zz, customBiomeCache); + if (floorBiome == null && ceilingBiome == null) { + return; + } + + if (floorBiome != null) { + paintFloorLayers(floorBiome, rx, rz, xx, zz, zone.floor); + } + + if (ceilingBiome != null) { + paintCeilingLayers(ceilingBiome, rx, rz, xx, zz, zone.ceiling, maxY); + } + + if (floorBiome != null && dressing.hasDecorators(floorBiome, DecorationPart.NONE) + && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz, classes)) { + dressing.decorateFloor(output, rx, rz, xx, zz, floorBiome, zone.getFloor() - 1, zone.airThickness()); + } + + if (ceilingBiome != null && dressing.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY + && classes.isSolid(output.get(rx, zone.getCeiling() + 1, rz))) { + dressing.decorateCeiling(output, rx, rz, xx, zz, ceilingBiome, zone.getCeiling(), zone.airThickness()); } } - if (floorBiome != null && decorators.hasDecorators(floorBiome, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { - surfaceDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); + private void setMarker(int localX, int y, int localZ, MatterMarker marker) { + Matter section = mantleChunk.getOrCreate(y >> 4); + section.slice(MatterMarker.class).set(localX, y & 15, localZ, marker); } - if (ceilingBiome != null && decorators.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { - ceilingDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); - } - } - - IrisBiome resolveCaveBoundaryBiome(MantleChunk mantleChunk, int x, int y, int z, int worldX, int worldZ, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { - MatterCavern cavern = dataIfPresent(mantleChunk, x, y, z, MatterCavern.class); - return resolveCaveBoundaryBiome( - cavern, worldX, y, worldZ, caveBiomeCache, customBiomeCache); - } - - private static T dataIfPresent(MantleChunk mantleChunk, int x, int y, int z, Class type) { - int section = y >> 4; - if (y < 0 || !mantleChunk.exists(section)) { - return null; - } - Matter matter = mantleChunk.get(section); - if (matter == null || !matter.hasSlice(type)) { - return null; - } - return matter.getSlice(type).get(x & 15, y & 15, z & 15); - } - - IrisBiome resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, Long2ObjectOpenHashMap caveBiomeCache, Map customBiomeCache) { - if (cavern != null && !cavern.getCustomBiome().isEmpty()) { - return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); - } - return resolveCaveBiome(caveBiomeCache, worldX, y, worldZ); - } - - static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, PlatformBlockState layer) { - return !isGravityAffected(layer) || y > 0 && B.isSolid(output.getRaw(x, y - 1, z)); - } - - static boolean hasStableCaveFloorSupport(Hunk output, int x, int floorY, int z) { - if (floorY <= 0) { - return false; - } - PlatformBlockState support = output.getRaw(x, floorY - 1, z); - if (!B.isSolid(support)) { - return false; - } - return !isGravityAffected(support) || floorY > 1 && B.isSolid(output.getRaw(x, floorY - 2, z)); - } - - static boolean isGravityAffected(PlatformBlockState state) { - return state != null && state.hasGravity(); - } - - private IrisBiome resolveCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z) { - IrisBiome center = sampleCaveBiome(caveBiomeCache, x, y, z); - if (center == null) { - return null; + ResourceId resolveCaveBoundaryBiome(int x, int y, int z, int worldX, int worldZ, Map customBiomeCache) { + return resolveCaveBoundaryBiome(cavernIfPresent(x, y, z), worldX, y, worldZ, customBiomeCache); } - IrisBiome xPos = sampleCaveBiome(caveBiomeCache, x + CAVE_BIOME_BLEND_RADIUS, y, z); - IrisBiome xNeg = sampleCaveBiome(caveBiomeCache, x - CAVE_BIOME_BLEND_RADIUS, y, z); - IrisBiome zPos = sampleCaveBiome(caveBiomeCache, x, y, z + CAVE_BIOME_BLEND_RADIUS); - IrisBiome zNeg = sampleCaveBiome(caveBiomeCache, x, y, z - CAVE_BIOME_BLEND_RADIUS); - - if (xPos == center && xNeg == center && zPos == center && zNeg == center) { - return center; + private MatterCavern cavernIfPresent(int x, int y, int z) { + int section = y >> 4; + if (y < 0 || !mantleChunk.exists(section)) { + return null; + } + Matter matter = mantleChunk.get(section); + if (matter == null || !matter.hasSlice(MatterCavern.class)) { + return null; + } + return matter.getSlice(MatterCavern.class).get(x & 15, y & 15, z & 15); } - int roll = Math.floorMod(rng.nextParallelRNG(BlockPosition.toLong(x, y, z)).nextInt(), CAVE_BIOME_BLEND_TOTAL_WEIGHT); - if (roll < CAVE_BIOME_BLEND_CENTER_WEIGHT) { - return center; - } - roll -= CAVE_BIOME_BLEND_CENTER_WEIGHT; - if (roll == 0) { - return xPos != null ? xPos : center; - } - if (roll == 1) { - return xNeg != null ? xNeg : center; - } - if (roll == 2) { - return zPos != null ? zPos : center; - } - return zNeg != null ? zNeg : center; - } - - private IrisBiome sampleCaveBiome(Long2ObjectOpenHashMap caveBiomeCache, int x, int y, int z) { - long key = BlockPosition.toLong(x, y, z); - IrisBiome cachedBiome = caveBiomeCache.get(key); - if (cachedBiome != null) { - return cachedBiome; + ResourceId resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, Map customBiomeCache) { + if (cavern != null && !cavern.getCustomBiome().isEmpty()) { + return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); + } + return resolveCaveBiome(worldX, y, worldZ); } - IrisBiome resolvedBiome = engine.getCaveBiome(x, y, z); - if (resolvedBiome != null) { - caveBiomeCache.put(key, resolvedBiome); - } - return resolvedBiome; - } + private ResourceId resolveCaveBiome(int x, int y, int z) { + ResourceId center = sampleCaveBiome(x, y, z); + if (center == null) { + return null; + } - private IrisBiome resolveCustomBiome(Map customBiomeCache, String customBiome) { - if (customBiomeCache.containsKey(customBiome)) { - return customBiomeCache.get(customBiome); + ResourceId xPos = sampleCaveBiome(x + CAVE_BIOME_BLEND_RADIUS, y, z); + ResourceId xNeg = sampleCaveBiome(x - CAVE_BIOME_BLEND_RADIUS, y, z); + ResourceId zPos = sampleCaveBiome(x, y, z + CAVE_BIOME_BLEND_RADIUS); + ResourceId zNeg = sampleCaveBiome(x, y, z - CAVE_BIOME_BLEND_RADIUS); + + if (xPos == center && xNeg == center && zPos == center && zNeg == center) { + return center; + } + + int roll = Math.floorMod(rng.nextParallelRNG(BlockPosition.toLong(x, y, z)).nextInt(), CAVE_BIOME_BLEND_TOTAL_WEIGHT); + if (roll < CAVE_BIOME_BLEND_CENTER_WEIGHT) { + return center; + } + roll -= CAVE_BIOME_BLEND_CENTER_WEIGHT; + if (roll == 0) { + return xPos != null ? xPos : center; + } + if (roll == 1) { + return xNeg != null ? xNeg : center; + } + if (roll == 2) { + return zPos != null ? zPos : center; + } + return zNeg != null ? zNeg : center; } - IrisBiome loaded = engine.getData().getBiomeLoader().load(customBiome); - customBiomeCache.put(customBiome, loaded); - return loaded; + private ResourceId sampleCaveBiome(int x, int y, int z) { + long key = BlockPosition.toLong(x, y, z); + ResourceId cachedBiome = caveBiomeCache.get(key); + if (cachedBiome != null) { + return cachedBiome; + } + + ResourceId resolvedBiome = terrain.caveBiome(x, y, z).orElse(null); + if (resolvedBiome != null) { + caveBiomeCache.put(key, resolvedBiome); + } + return resolvedBiome; + } + + /** The id of the pack's biome with this key; null when the pack has none or it cannot be loaded. */ + private ResourceId existingBiomeId(String key) { + ResourceId id = resources.idOf(key); + try { + return resources.find(new ResourceKey<>(id, PackBiome.class)).isPresent() ? id : null; + } catch (IllegalStateException unreadable) { + return null; + } + } + + private ResourceId resolveCustomBiome(Map customBiomeCache, String customBiome) { + if (customBiomeCache.containsKey(customBiome)) { + return customBiomeCache.get(customBiome); + } + + ResourceId id = existingBiomeId(customBiome); + customBiomeCache.put(customBiome, id); + return id; + } } @Data @@ -762,8 +691,8 @@ public class CaveApplying { return (ceiling - floor) - 1; } - public boolean isValid(Engine engine) { - return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= engine.getHeight() && airThickness() > 0; + public boolean isValid(int height) { + return floor < ceiling && ceiling - floor >= 1 && floor >= 0 && ceiling <= height && airThickness() > 0; } public String toString() { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java index 4a67e77c3..bae9f392d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java @@ -19,11 +19,10 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.carve.CaveDepthSettings; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; +import art.arcane.iris.engine.object.terrain.carving.DeclaredByLevel; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.resource.ResourceId; import com.volmit.service.CaveBiomes; import com.volmit.world.PackWorld; @@ -36,13 +35,13 @@ import java.util.Optional; public final class CaveBiomeBands implements CaveBiomes { @Override public Optional overriddenBiome(PackWorld world, int x, int y, int z) { - Engine engine = IrisPackWorld.of(world).engine(); - ResolvedCarvingEntry rootEntry = CarvingResolver.resolveRootEntry(engine, y + engine.getWorld().minHeight(), null); + CarvingResolver resolver = CarvingResolver.of(world); + ResolvedCarvingEntry rootEntry = resolver.rootEntryAt(y); if (rootEntry == null) { return Optional.empty(); } - ResolvedCarvingEntry entry = CarvingResolver.resolveFromRoot(engine, rootEntry, x, z, null); - if (CarvingResolver.resolveEntryBiome(engine, entry, null) == null) { + ResolvedCarvingEntry entry = resolver.resolveFromRoot(rootEntry, x, z); + if (resolver.entryBiome(entry) == null) { return Optional.empty(); } return Optional.of(entry.biomeKey().trim()); @@ -50,12 +49,25 @@ public final class CaveBiomeBands implements CaveBiomes { @Override public int minDepthBelowSurface(PackWorld world, String biomeKey) { - IrisBiome biome = IrisPackWorld.of(world).engine().getData().getBiomeLoader().load(biomeKey); - return biome == null ? 0 : minDepthBelowSurface(biome); + return Depths.of(world).minDepthBelowSurface(world.resources().idOf(biomeKey)); } - /** How many blocks below the surface {@code biome}'s caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ - public static int minDepthBelowSurface(IrisBiome biome) { - return biome.getModuleSettings().find(CaveDepthSettings.class).map(CaveDepthSettings::depth).orElse(0); + /** The minimum depths the world's biomes declare ({@code caveMinDepthBelowSurface}), found by biome id. */ + private static final class Depths { + private final DeclaredByLevel declared; + + private Depths(PackWorld world) { + this.declared = DeclaredByLevel.of(world, CaveDepthSettings.class); + } + + static Depths of(PackWorld world) { + return world.state(Depths.class, Depths::new); + } + + /** How many blocks below the surface the biome's caves begin, as its {@code caveMinDepthBelowSurface} says; 0 where it says none. */ + int minDepthBelowSurface(ResourceId biome) { + CaveDepthSettings depth = declared.ofBiome(biome); + return depth == null ? 0 : depth.depth(); + } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java new file mode 100644 index 000000000..5f32cab21 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeCache.java @@ -0,0 +1,99 @@ +/* + * 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.modifier; + +import com.volmit.resource.ResourceId; + +import java.util.Arrays; + +/** + * The cave biomes one chunk's caves have sampled so far, by block position (see {@link art.arcane.volmlib.util.math.BlockPosition#toLong}): + * a cave wall asks for the biome around it five times, and the next wall block asks again for most of them. Open addressing on + * longs, which spares the boxing a map of {@link Long} would do on this hot path; only biomes that exist are kept. + */ +final class CaveBiomeCache { + private static final double LOAD_FACTOR = 0.5D; + private static final long EMPTY_KEY = Long.MIN_VALUE; + + private long[] keys; + private ResourceId[] values; + private int mask; + private int size; + + CaveBiomeCache(int expectedSize) { + int capacity = 8; + while (capacity * LOAD_FACTOR < expectedSize) { + capacity <<= 1; + } + allocate(capacity); + } + + /** The biome kept for {@code key}; null where none is. */ + ResourceId get(long key) { + int index = slot(key); + while (keys[index] != EMPTY_KEY) { + if (keys[index] == key) { + return values[index]; + } + index = (index + 1) & mask; + } + return null; + } + + void put(long key, ResourceId biome) { + if ((size + 1) > keys.length * LOAD_FACTOR) { + grow(); + } + int index = slot(key); + while (keys[index] != EMPTY_KEY) { + if (keys[index] == key) { + values[index] = biome; + return; + } + index = (index + 1) & mask; + } + keys[index] = key; + values[index] = biome; + size++; + } + + private int slot(long key) { + long mixed = key * 0x9E3779B97F4A7C15L; + return (int) (mixed ^ (mixed >>> 32)) & mask; + } + + private void allocate(int capacity) { + keys = new long[capacity]; + Arrays.fill(keys, EMPTY_KEY); + values = new ResourceId[capacity]; + mask = capacity - 1; + size = 0; + } + + private void grow() { + long[] oldKeys = keys; + ResourceId[] oldValues = values; + allocate(oldKeys.length << 1); + for (int index = 0; index < oldKeys.length; index++) { + if (oldKeys[index] != EMPTY_KEY) { + put(oldKeys[index], oldValues[index]); + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java new file mode 100644 index 000000000..78d88e7c8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBlockClasses.java @@ -0,0 +1,89 @@ +/* + * 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.modifier; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * What the cave passes of one chunk ask about blocks, answered from memory. A chunk holds few distinct states and a cave pass asks + * about them per block, so each state instance (the hunk hands out one per distinct state) is classified once. + */ +final class CaveBlockClasses { + private static final int SOLID = 1; + private static final int FLUID = 2; + private static final int AIR = 4; + private static final int ORE = 8; + private static final int DECORATION = 16; + private static final int GRAVITY = 32; + + private final BlockRegistry blocks; + private final Map classes = new IdentityHashMap<>(); + + CaveBlockClasses(BlockRegistry blocks) { + this.blocks = blocks; + } + + boolean isSolid(BlockState state) { + return (classesOf(state) & SOLID) != 0; + } + + boolean isFluid(BlockState state) { + return (classesOf(state) & FLUID) != 0; + } + + boolean isAir(BlockState state) { + return (classesOf(state) & AIR) != 0; + } + + boolean isOre(BlockState state) { + return (classesOf(state) & ORE) != 0; + } + + boolean isDecorant(BlockState state) { + return (classesOf(state) & DECORATION) != 0; + } + + boolean hasGravity(BlockState state) { + return state != null && (classesOf(state) & GRAVITY) != 0; + } + + private int classesOf(BlockState state) { + Integer known = classes.get(state); + if (known != null) { + return known; + } + int computed = classify(state); + classes.put(state, computed); + return computed; + } + + private int classify(BlockState state) { + return flag(state, BlockTrait.SOLID, SOLID) | flag(state, BlockTrait.FLUID, FLUID) | flag(state, BlockTrait.AIR, AIR) + | flag(state, BlockTrait.ORE, ORE) | flag(state, BlockTrait.DECORATION, DECORATION) | flag(state, BlockTrait.GRAVITY, GRAVITY); + } + + private int flag(BlockState state, BlockTrait trait, int bit) { + return blocks.hasTrait(state, trait) ? bit : 0; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java index a2e51e88d..21859bc8a 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java @@ -18,11 +18,8 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.resource.ResourceId; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -31,7 +28,7 @@ final class IrisCarveScratch { final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256]; final int[] surfaceHeights = new int[256]; final CarveWallBuffer walls = new CarveWallBuffer(512); - final Map customBiomeCache = new HashMap<>(); + final Map customBiomeCache = new HashMap<>(); int[] upperSurfaceHeights; boolean customCaveBiomePresent; @@ -59,219 +56,3 @@ final class IrisCarveScratch { customCaveBiomePresent = false; } } - -final class CarveColumnMask { - private long[] words = new long[8]; - private int maxWord = -1; - - void add(int y) { - if (y < 0) { - return; - } - - int wordIndex = y >> 6; - if (wordIndex >= words.length) { - words = Arrays.copyOf(words, Math.max(words.length << 1, wordIndex + 1)); - } - - words[wordIndex] |= 1L << (y & 63); - if (wordIndex > maxWord) { - maxWord = wordIndex; - } - } - - int nextSetBit(int fromBit) { - if (maxWord < 0) { - return -1; - } - - int startBit = Math.max(0, fromBit); - int wordIndex = startBit >> 6; - if (wordIndex > maxWord) { - return -1; - } - - long word = words[wordIndex] & (-1L << (startBit & 63)); - while (true) { - if (word != 0L) { - return (wordIndex << 6) + Long.numberOfTrailingZeros(word); - } - - wordIndex++; - if (wordIndex > maxWord) { - return -1; - } - word = words[wordIndex]; - } - } - - boolean isEmpty() { - return maxWord < 0; - } - - boolean contains(int y) { - if (y < 0) { - return false; - } - - int wordIndex = y >> 6; - if (wordIndex > maxWord) { - return false; - } - - return (words[wordIndex] & (1L << (y & 63))) != 0L; - } - - void clear() { - if (maxWord < 0) { - return; - } - - for (int index = 0; index <= maxWord; index++) { - words[index] = 0L; - } - maxWord = -1; - } -} - -final class CarveWallBuffer { - private static final int EMPTY_KEY = -1; - private static final double LOAD_FACTOR = 0.75D; - - private int[] keys; - private MatterCavern[] values; - private int mask; - private int resizeAt; - private int size; - - CarveWallBuffer(int expectedSize) { - int capacity = 1; - int minimumCapacity = Math.max(8, expectedSize); - while (capacity < minimumCapacity) { - capacity <<= 1; - } - - keys = new int[capacity]; - Arrays.fill(keys, EMPTY_KEY); - values = new MatterCavern[capacity]; - mask = capacity - 1; - resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); - } - - void put(int x, int y, int z, MatterCavern value) { - int key = pack(x, y, z); - int index = mix(key) & mask; - - while (true) { - int existingKey = keys[index]; - if (existingKey == EMPTY_KEY) { - keys[index] = key; - values[index] = value; - size++; - if (size >= resizeAt) { - resize(); - } - return; - } - - if (existingKey == key) { - values[index] = value; - return; - } - - index = (index + 1) & mask; - } - } - - MatterCavern get(int x, int y, int z) { - int key = pack(x, y, z); - int index = mix(key) & mask; - while (true) { - int existingKey = keys[index]; - if (existingKey == EMPTY_KEY) { - return null; - } - if (existingKey == key) { - return values[index]; - } - index = (index + 1) & mask; - } - } - - void forEach(Consumer consumer) { - for (int index = 0; index < keys.length; index++) { - int key = keys[index]; - if (key == EMPTY_KEY) { - continue; - } - - MatterCavern cavern = values[index]; - if (cavern != null) { - consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern); - } - } - } - - void clear() { - Arrays.fill(keys, EMPTY_KEY); - Arrays.fill(values, null); - size = 0; - } - - private void resize() { - int[] oldKeys = keys; - MatterCavern[] oldValues = values; - int nextCapacity = oldKeys.length << 1; - keys = new int[nextCapacity]; - Arrays.fill(keys, EMPTY_KEY); - values = new MatterCavern[nextCapacity]; - mask = nextCapacity - 1; - resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); - size = 0; - - for (int index = 0; index < oldKeys.length; index++) { - int key = oldKeys[index]; - MatterCavern value = oldValues[index]; - if (key != EMPTY_KEY && value != null) { - reinsert(key, value); - } - } - } - - private void reinsert(int key, MatterCavern value) { - int index = mix(key) & mask; - while (keys[index] != EMPTY_KEY) { - index = (index + 1) & mask; - } - - keys[index] = key; - values[index] = value; - size++; - } - - private int pack(int x, int y, int z) { - return (y << 8) | PowerOfTwoCoordinates.packLocal16(x & 15, z & 15); - } - - private int unpackX(int key) { - return PowerOfTwoCoordinates.unpackLocal16X(key & 255); - } - - private int unpackY(int key) { - return key >> 8; - } - - private int unpackZ(int key) { - return PowerOfTwoCoordinates.unpackLocal16Z(key); - } - - private int mix(int value) { - int mixed = value * 0x9E3779B9; - return mixed ^ (mixed >>> 16); - } - - @FunctionalInterface - interface Consumer { - void accept(int x, int y, int z, MatterCavern cavern); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java deleted file mode 100644 index 916e35316..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingBands.java +++ /dev/null @@ -1,71 +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.terrain.carving; - -import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.builtin.carve.CarvingSettings; -import art.arcane.iris.engine.framework.Engine; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * What the carve module keeps for one world: the cave biome bands its dimension declares ({@link CarvingSettings}) made ready - * ({@link ResolvedCarvingEntry}), in the order the dimension lists them, and by id. - */ -public final class CarvingBands { - private final List entries; - private final Map index; - - CarvingBands(List declared) { - this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); - this.index = indexById(entries); - } - - CarvingBands(Engine engine) { - this(engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of())); - } - - /** The bands of the world {@code engine} generates now. */ - public static CarvingBands of(Engine engine) { - return engine.getGeneration().state(CarvingBands.class, CarvingBands::new); - } - - /** Every declared entry, enabled or not. */ - public List entries() { - return entries; - } - - /** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */ - public Map index() { - return index; - } - - private static Map indexById(List entries) { - Map index = new HashMap<>(); - for (ResolvedCarvingEntry entry : entries) { - if (!entry.id().isBlank()) { - index.put(entry.id().trim(), entry); - } - } - return Map.copyOf(index); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index a4eb736ed..ad137c0fa 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -1,78 +1,122 @@ +/* + * 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.terrain.carving; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.util.project.interpolation.IrisInterpolation; -import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Range; +import com.volmit.FeatureAttachment.Target; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; -import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; -import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; /** - * Picks the dimension's carving entry for a position: the last enabled root entry whose world Y band holds the height, - * then, through the entries' children, the one a noise pattern selects at the column. The state a caller passes (or, when - * it passes none, the thread's) keeps the picks and the entries' biomes, so a caller resolving many positions reuses them. + * What the carve module keeps for one world about the cave biome bands its dimension declares ({@link CarvingSettings}): the + * entries made ready ({@link ResolvedCarvingEntry}), in the order the dimension lists them and by id, and the picks among them. + * A pick is the dimension's last enabled root entry whose world Y band holds a height, then, through the entries' children, the + * one a noise pattern selects at a column. */ public final class CarvingResolver { private static final int MAX_CHILD_DEPTH = 32; private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L; - private static final ThreadLocal> THREAD_STATE = - ThreadLocal.withInitial(() -> new WeakReference<>(null)); - private CarvingResolver() { + private final PackResources resources; + private final ModuleLog log; + private final int minHeight; + private final long childSeed; + private final List entries; + private final Map index; + private final Map> rootEntriesByWorldY = new ConcurrentHashMap<>(); + private final Map selectionPlans = new ConcurrentHashMap<>(); + CarvingResolver(PackWorld world, List declared) { + this.resources = world.resources(); + this.log = world.log(); + this.minHeight = world.minHeight(); + this.childSeed = IrisSeed.CARVE.of(world) ^ CHILD_SEED_SALT; + this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); + this.index = indexById(entries); } - public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY) { - return resolveRootEntry(engine, worldY, threadState()); + /** The bands of the world {@code world} generates now. */ + public static CarvingResolver of(PackWorld world) { + return world.state(CarvingResolver.class, generating -> new CarvingResolver(generating, dimensionEntries(generating))); } - public static ResolvedCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) { - State resolvedState = state == null ? threadState() : state; - resolvedState.bind(engine); - if (resolvedState.rootEntriesByWorldY.containsKey(worldY)) { - return resolvedState.rootEntriesByWorldY.get(worldY); + private static List dimensionEntries(PackWorld world) { + List dimensionEntries = new ArrayList<>(); + for (Entry entry : world.settings().declared(CarvingSettings.class)) { + if (entry.level() == Target.DIMENSION) { + dimensionEntries.addAll(entry.value().entries()); + } } + return dimensionEntries; + } - List entries = resolvedState.bands.entries(); - if (entries.isEmpty()) { - resolvedState.rootEntriesByWorldY.put(worldY, null); - return null; - } + /** Every declared entry, enabled or not. */ + public List entries() { + return entries; + } + /** The entries by their trimmed ids; entries without an id are not in it, and the last of several with one id is. */ + public Map index() { + return index; + } + + /** The root entry for a height above the dimension's bottom; null where no enabled entry with a biome holds it. */ + public ResolvedCarvingEntry rootEntryAt(int y) { + return rootEntryAtWorldY(y + minHeight); + } + + /** The root entry for a world Y as packs write them; null where no enabled entry with a biome holds it. */ + public ResolvedCarvingEntry rootEntryAtWorldY(int worldY) { + return rootEntriesByWorldY.computeIfAbsent(worldY, this::pickRootEntry).orElse(null); + } + + private Optional pickRootEntry(int worldY) { ResolvedCarvingEntry resolved = null; for (ResolvedCarvingEntry entry : entries) { - if (!isRootCandidate(engine, entry, worldY, resolvedState)) { - continue; + if (isRootCandidate(entry, worldY)) { + resolved = entry; } - - resolved = entry; } - - resolvedState.rootEntriesByWorldY.put(worldY, resolved); - return resolved; + return Optional.ofNullable(resolved); } - public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { - return resolveFromRoot(engine, rootEntry, worldX, worldZ, threadState()); - } - - public static ResolvedCarvingEntry resolveFromRoot(Engine engine, ResolvedCarvingEntry rootEntry, int worldX, int worldZ, State state) { - State resolvedState = state == null ? threadState() : state; - resolvedState.bind(engine); + public ResolvedCarvingEntry resolveFromRoot(ResolvedCarvingEntry rootEntry, int worldX, int worldZ) { if (rootEntry == null) { return null; } - IrisBiome rootBiome = resolveEntryBiome(engine, rootEntry, resolvedState); + PackBiome rootBiome = entryBiome(rootEntry); if (rootBiome == null) { return null; } @@ -82,11 +126,10 @@ public final class CarvingResolver { return rootEntry; } - Map entryIndex = resolvedState.bands.index(); ResolvedCarvingEntry current = rootEntry; int depth = remainingDepth; while (depth > 0) { - ResolvedCarvingEntry selected = selectChild(engine, current, worldX, worldZ, entryIndex, resolvedState); + ResolvedCarvingEntry selected = selectChild(current, worldX, worldZ); if (selected == null || selected == current) { break; } @@ -102,30 +145,12 @@ public final class CarvingResolver { return current; } - public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry) { - return resolveEntryBiome(engine, entry, null); + /** The pack biome the entry names; null when it names none or the pack has no such biome. */ + public PackBiome entryBiome(ResolvedCarvingEntry entry) { + return entry == null ? null : entry.realBiome(resources, log); } - public static IrisBiome resolveEntryBiome(Engine engine, ResolvedCarvingEntry entry, State state) { - if (entry == null) { - return null; - } - - if (state == null) { - return entry.realBiome(engine.getData()); - } - - state.bind(engine); - if (state.biomeCache.containsKey(entry)) { - return state.biomeCache.get(entry); - } - - IrisBiome biome = entry.realBiome(engine.getData()); - state.biomeCache.put(entry, biome); - return biome; - } - - private static boolean isRootCandidate(Engine engine, ResolvedCarvingEntry entry, int worldY, State state) { + private boolean isRootCandidate(ResolvedCarvingEntry entry, int worldY) { if (entry == null || !entry.enabled()) { return false; } @@ -135,41 +160,28 @@ public final class CarvingResolver { return false; } - return resolveEntryBiome(engine, entry, state) != null; + return entryBiome(entry) != null; } - private static ResolvedCarvingEntry selectChild( - Engine engine, - ResolvedCarvingEntry parent, - int worldX, - int worldZ, - Map entryIndex, - State state - ) { + private ResolvedCarvingEntry selectChild(ResolvedCarvingEntry parent, int worldX, int worldZ) { List children = parent.children(); if (children.isEmpty()) { return parent; } - IrisBiome parentBiome = resolveEntryBiome(engine, parent, state); + PackBiome parentBiome = entryBiome(parent); if (parentBiome == null) { return parent; } - ParentSelectionPlan selectionPlan = state.selectionPlans.get(parent); - if (selectionPlan == null) { - selectionPlan = buildSelectionPlan(engine, parent, parentBiome, entryIndex, state); - state.selectionPlans.put(parent, selectionPlan); - } - + ParentSelectionPlan selectionPlan = selectionPlans.computeIfAbsent(parent, key -> buildSelectionPlan(key, parentBiome)); if (selectionPlan.parentOnly) { return parent; } - long seed = resolveChildSeed(engine, state); - CNG childGenerator = parent.childrenGenerator(seed, engine.getData()); - double sample = childGenerator.noiseFast2D(worldX, worldZ); - int selectedIndex = (int) Math.round(IrisInterpolation.lerp(0, selectionPlan.maxIndex, sample)); + NoiseSampler childGenerator = parent.childrenGenerator(childSeed, resources); + double sample = childGenerator.sample(worldX, worldZ); + int selectedIndex = (int) Math.round(sample * selectionPlan.maxIndex); CarvingChoice selected = selectionPlan.get(selectedIndex); if (selected == null || selected.entry == null) { return parent; @@ -178,25 +190,19 @@ public final class CarvingResolver { return selected.entry; } - private static ParentSelectionPlan buildSelectionPlan( - Engine engine, - ResolvedCarvingEntry parent, - IrisBiome parentBiome, - Map entryIndex, - State state - ) { + private ParentSelectionPlan buildSelectionPlan(ResolvedCarvingEntry parent, PackBiome parentBiome) { List options = new ArrayList<>(); for (String childId : parent.children()) { if (childId == null || childId.isBlank()) { continue; } - ResolvedCarvingEntry child = entryIndex.get(childId.trim()); + ResolvedCarvingEntry child = index.get(childId.trim()); if (child == null || !child.enabled()) { continue; } - IrisBiome childBiome = resolveEntryBiome(engine, child, state); + PackBiome childBiome = entryBiome(child); if (childBiome == null) { continue; } @@ -243,13 +249,12 @@ public final class CarvingResolver { return mapped.toArray(new CarvingChoice[0]); } - private static int rarity(IrisBiome biome) { + private static int rarity(PackBiome biome) { if (biome == null) { return 1; } - int rarity = biome.getRarity(); - return Math.max(rarity, 1); + return Math.max(biome.rarity(), 1); } private static int clampDepth(int depth) { @@ -260,56 +265,14 @@ public final class CarvingResolver { return Math.min(depth, MAX_CHILD_DEPTH); } - private static long resolveChildSeed(Engine engine, State state) { - if (state.childSeed == null) { - state.childSeed = engine.getSeedManager().getCarve() ^ CHILD_SEED_SALT; - } - - return state.childSeed; - } - - private static State threadState() { - WeakReference reference = THREAD_STATE.get(); - State state = reference.get(); - if (state != null) { - return state; - } - State replacement = new State(); - THREAD_STATE.set(new WeakReference<>(replacement)); - return replacement; - } - - public static final class State { - private final Map rootEntriesByWorldY = new HashMap<>(); - private final Map selectionPlans = new IdentityHashMap<>(); - private final Map biomeCache = new IdentityHashMap<>(); - private WeakReference engineIdentity; - private WeakReference dimensionIdentity; - private WeakReference dataIdentity; - private CarvingBands bands; - private Long childSeed; - - private void bind(Engine engine) { - IrisDimension dimension = engine.getDimension(); - IrisData data = engine.getData(); - if (references(engineIdentity, engine) - && references(dimensionIdentity, dimension) - && references(dataIdentity, data)) { - return; + private static Map indexById(List entries) { + Map index = new HashMap<>(); + for (ResolvedCarvingEntry entry : entries) { + if (!entry.id().isBlank()) { + index.put(entry.id().trim(), entry); } - engineIdentity = new WeakReference<>(engine); - dimensionIdentity = new WeakReference<>(dimension); - dataIdentity = new WeakReference<>(data); - bands = CarvingBands.of(engine); - rootEntriesByWorldY.clear(); - selectionPlans.clear(); - biomeCache.clear(); - childSeed = null; - } - - private static boolean references(WeakReference identity, Object value) { - return identity != null && identity.get() == value; } + return Map.copyOf(index); } private static final class ParentSelectionPlan { @@ -350,18 +313,6 @@ public final class CarvingResolver { } } - private static final class CarvingChoice implements IRare { - private final ResolvedCarvingEntry entry; - private final int rarity; - - private CarvingChoice(ResolvedCarvingEntry entry, int rarity) { - this.entry = entry; - this.rarity = rarity; - } - - @Override - public int getRarity() { - return rarity; - } + private record CarvingChoice(ResolvedCarvingEntry entry, int rarity) { } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java similarity index 63% rename from src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java rename to src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java index 4eaef2997..6432cc232 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/IrisCaveProfileSampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java @@ -18,26 +18,26 @@ package art.arcane.iris.engine.object.terrain.carving; +import art.arcane.iris.builtin.carve.CaveFieldModule; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.engine.object.value.IrisRange; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.math.M; +import com.volmit.config.Range; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; import java.util.ArrayList; import java.util.List; -public final class IrisCaveProfileSampler { +public final class CaveProfileSampler { private static final double FLOATING_THRESHOLD_BIAS_SCALE = 0.2D; - private final IrisData data; private final CaveProfile profile; - private final ResolvedCaveProfile resolved; - private final CNG baseDensity; - private final CNG detailDensity; - private final CNG warpDensity; - private final RNG thresholdRng; + private final NoiseSampler baseDensity; + private final NoiseSampler detailDensity; + private final NoiseSampler warpDensity; + private final NoiseSampler thresholdNoise; private final ModuleState[] modules; private final double inverseNormalization; private final double baseWeight; @@ -47,16 +47,13 @@ public final class IrisCaveProfileSampler { private final boolean hasWarp; private final boolean hasModules; - public IrisCaveProfileSampler(Engine engine, CaveProfile profile) { - this.data = engine.getData(); + public CaveProfileSampler(NoiseFactory noise, long carveSeed, CaveProfile profile) { this.profile = profile; - this.resolved = ResolvedCaveProfile.of(profile); List moduleStates = new ArrayList<>(); - RNG baseRng = new RNG(engine.getSeedManager().getCarve()); - this.baseDensity = resolved.baseDensityStyle().create(baseRng.nextParallelRNG(934_447), data); - this.detailDensity = resolved.detailDensityStyle().create(baseRng.nextParallelRNG(612_991), data); - this.warpDensity = resolved.warpStyle().create(baseRng.nextParallelRNG(770_713), data); - this.thresholdRng = baseRng.nextParallelRNG(489_112); + this.baseDensity = noise.sampler(profile.baseDensityStyle(), carveSeed + 934_447); + this.detailDensity = noise.sampler(profile.detailDensityStyle(), carveSeed + 612_991); + this.warpDensity = noise.sampler(profile.warpStyle(), carveSeed + 770_713); + this.thresholdNoise = noise.sampler(profile.densityThreshold().style(), carveSeed + 489_112); this.baseWeight = profile.baseWeight(); this.detailWeight = profile.detailWeight(); this.warpStrength = profile.warpStrength(); @@ -64,8 +61,8 @@ public final class IrisCaveProfileSampler { double weight = Math.abs(baseWeight) + Math.abs(detailWeight); int index = 0; - for (ResolvedCaveProfile.Module module : resolved.modules()) { - CNG moduleDensity = module.style().create(baseRng.nextParallelRNG(1_000_003L + (index * 65_537L)), data); + for (CaveFieldModule module : profile.modules()) { + NoiseSampler moduleDensity = noise.sampler(module.style(), carveSeed + 1_000_003L + (index * 65_537L)); ModuleState state = new ModuleState(module, moduleDensity); moduleStates.add(state); weight += Math.abs(state.weight); @@ -76,7 +73,7 @@ public final class IrisCaveProfileSampler { double normalization = weight <= 0 ? 1D : weight; this.inverseNormalization = 1D / normalization; this.hasModules = modules.length > 0; - this.enabled = profile.enabled() && baseDensity != null && detailDensity != null && (!hasWarp || warpDensity != null); + this.enabled = profile.enabled(); } public boolean shouldCarve(int x, int y, int z, double floatingCarveThreshold) { @@ -84,11 +81,23 @@ public final class IrisCaveProfileSampler { return false; } - double threshold = resolved.densityThreshold().get(thresholdRng, x, z, data) - profile.thresholdBias(); + double threshold = thresholdAt(x, z) - profile.thresholdBias(); threshold += floatingThresholdBias(floatingCarveThreshold); return sampleDensity(x, y, z) <= threshold; } + /** The profile's density threshold at the column, as a styled range picks its value. */ + private double thresholdAt(int x, int z) { + StyledRange range = profile.densityThreshold(); + if (range.min() == range.max()) { + return range.min(); + } + if (NoiseStyle.FLAT.equals(range.style().style())) { + return M.lerp(range.min(), range.max(), 0.5); + } + return range.min() + (thresholdNoise.sample(x, z) * (range.max() - range.min())); + } + double sampleDensity(int x, int y, int z) { if (hasWarp) { return sampleDensityWarped(x, y, z); @@ -98,8 +107,8 @@ public final class IrisCaveProfileSampler { } private double sampleDensityUnwarped(int x, int y, int z) { - double density = baseDensity.noiseFastSigned3D(x, y, z) * baseWeight; - density += detailDensity.noiseFastSigned3D(x, y, z) * detailWeight; + double density = baseDensity.signed(x, y, z) * baseWeight; + density += detailDensity.signed(x, y, z) * detailWeight; if (hasModules) { for (ModuleState module : modules) { if (!module.isActive(y)) { @@ -114,13 +123,13 @@ public final class IrisCaveProfileSampler { } private double sampleDensityWarped(int x, int y, int z) { - double warpA = warpDensity.noiseFastSigned3D(x, y, z); - double warpB = warpDensity.noiseFastSigned3D(x + 31.37D, y - 17.21D, z + 23.91D); + double warpA = warpDensity.signed(x, y, z); + double warpB = warpDensity.signed(x + 31.37D, y - 17.21D, z + 23.91D); double warpedX = x + (warpA * warpStrength); double warpedY = y + (warpB * warpStrength); double warpedZ = z + ((warpA - warpB) * 0.5D * warpStrength); - double density = baseDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * baseWeight; - density += detailDensity.noiseFastSigned3D(warpedX, warpedY, warpedZ) * detailWeight; + double density = baseDensity.signed(warpedX, warpedY, warpedZ) * baseWeight; + density += detailDensity.signed(warpedX, warpedY, warpedZ) * detailWeight; if (hasModules) { for (ModuleState module : modules) { if (!module.isActive(y)) { @@ -140,18 +149,18 @@ public final class IrisCaveProfileSampler { } private static final class ModuleState { - private final CNG density; + private final NoiseSampler density; private final int minY; private final int maxY; private final double weight; private final double threshold; private final boolean invert; - private ModuleState(ResolvedCaveProfile.Module module, CNG density) { - IrisRange range = module.verticalRange(); + private ModuleState(CaveFieldModule module, NoiseSampler density) { + Range range = module.verticalRange(); this.density = density; - this.minY = (int) Math.floor(range.getMin()); - this.maxY = (int) Math.ceil(range.getMax()); + this.minY = (int) Math.floor(range.min()); + this.maxY = (int) Math.ceil(range.max()); this.weight = module.weight(); this.threshold = module.threshold(); this.invert = module.invert(); @@ -162,7 +171,7 @@ public final class IrisCaveProfileSampler { } private double sample(double x, double y, double z) { - double sampled = density.noiseFastSigned3D(x, y, z); + double sampled = density.signed(x, y, z); return invert ? (threshold - sampled) * weight : (sampled - threshold) * weight; } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java new file mode 100644 index 000000000..bc0aac7af --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java @@ -0,0 +1,83 @@ +/* + * 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.terrain.carving; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.HashMap; +import java.util.Map; + +/** + * The settings of one type that a world's dimension, regions and biomes declare, found again by the id region and biome + * samples carry ({@code overworld:desert/dunes}), which is how the layout names the region or biome of a column. A settings + * entry names its source by kind ({@code overworld:biome/desert/dunes}), so the kind is taken off the id. + * + *

Only the regions and biomes the dimension reaches declare anything here ({@link com.volmit.config.PackSettings#declared}). + */ +public final class DeclaredByLevel { + private final F dimension; + private final Map regions; + private final Map biomes; + + private DeclaredByLevel(F dimension, Map regions, Map biomes) { + this.dimension = dimension; + this.regions = Map.copyOf(regions); + this.biomes = Map.copyOf(biomes); + } + + public static DeclaredByLevel of(PackWorld world, Class type) { + F dimension = null; + Map regions = new HashMap<>(); + Map biomes = new HashMap<>(); + for (Entry entry : world.settings().declared(type)) { + if (entry.level() == Target.DIMENSION) { + dimension = entry.value(); + } else if (entry.level() == Target.REGION) { + regions.putIfAbsent(sampleId(entry.source()), entry.value()); + } else if (entry.level() == Target.BIOME) { + biomes.putIfAbsent(sampleId(entry.source()), entry.value()); + } + } + return new DeclaredByLevel<>(dimension, regions, biomes); + } + + /** The dimension's declaration; null when it declares none. */ + public F ofDimension() { + return dimension; + } + + /** The declaration of the region with this id; null when it declares none. */ + public F ofRegion(ResourceId region) { + return regions.get(region); + } + + /** The declaration of the biome with this id; null when it declares none. */ + public F ofBiome(ResourceId biome) { + return biomes.get(biome); + } + + private static ResourceId sampleId(ResourceId source) { + String path = source.path(); + return new ResourceId(source.namespace(), path.substring(path.indexOf('/') + 1)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java new file mode 100644 index 000000000..36431ece9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java @@ -0,0 +1,52 @@ +/* + * 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.terrain.carving; + +import art.arcane.iris.builtin.carve.CaveProfile; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +/** + * What the carve module keeps for one world: the cave profiles its dimension, regions and biomes declare ({@code caveProfile}). + * A profile that is not declared is as good as one that is not enabled, so the lookups answer null for it. + */ +public final class DeclaredCaveProfiles { + private final DeclaredByLevel declared; + + private DeclaredCaveProfiles(PackWorld world) { + this.declared = DeclaredByLevel.of(world, CaveProfile.class); + } + + /** The profiles of the world {@code world}. */ + public static DeclaredCaveProfiles of(PackWorld world) { + return world.state(DeclaredCaveProfiles.class, DeclaredCaveProfiles::new); + } + + public CaveProfile ofDimension() { + return declared.ofDimension(); + } + + public CaveProfile ofRegion(ResourceId region) { + return declared.ofRegion(region); + } + + public CaveProfile ofBiome(ResourceId biome) { + return declared.ofBiome(biome); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index 53b3752aa..9248d49bb 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -19,21 +19,20 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisValues; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import com.volmit.config.Range; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceKey; +import com.volmit.world.PackBiome; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** - * One {@link CarvingEntry} made ready for one world: the biome it names, loaded from the pack when first asked for, and the + * One {@link CarvingEntry} made ready for one world: the biome it names, found in the pack when first asked for, and the * noise that splits it into child entries, built once per seed. What the entry describes stays in the settings. */ public final class ResolvedCarvingEntry { @@ -42,13 +41,11 @@ public final class ResolvedCarvingEntry { private static final double MIN_CHILD_SCALE = 0.0001D; private final CarvingEntry settings; - private final IrisGeneratorStyle childStyle; - private final AtomicCache realBiome = new AtomicCache<>(true); - private final Map childGenerators = new ConcurrentHashMap<>(); + private final AtomicCache realBiome = new AtomicCache<>(true); + private final Map childGenerators = new ConcurrentHashMap<>(); ResolvedCarvingEntry(CarvingEntry settings) { this.settings = settings; - this.childStyle = IrisValues.generatorStyle(settings.childStyle()); } public String id() { @@ -77,25 +74,29 @@ public final class ResolvedCarvingEntry { } /** The pack biome the entry names; null when it names none or the pack has no such biome. */ - public IrisBiome realBiome(IrisData data) { + public PackBiome realBiome(PackResources resources, ModuleLog log) { return realBiome.aquire(() -> { String biomeKey = settings.biome(); if (biomeKey.isBlank()) { return null; } - return data.getBiomeLoader().load(biomeKey.trim()); + try { + return resources.find(new ResourceKey<>(resources.idOf(biomeKey.trim()), PackBiome.class)).orElse(null); + } catch (IllegalStateException unreadable) { + log.warnOnce("carving-biome:" + biomeKey, "The biome " + biomeKey + " of a carving entry cannot be loaded: " + unreadable.getMessage()); + return null; + } }); } /** The noise that picks between the entry and its children, seeded by {@code seed} and the entry's id. */ - public CNG childrenGenerator(long seed, IrisData data) { + public NoiseSampler childrenGenerator(long seed, PackResources resources) { long idHash = settings.id().trim().hashCode(); long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; return childGenerators.computeIfAbsent(generatorSeed, key -> { double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor()); - RNG random = new RNG(key); - return childStyle.create(random.nextParallelRNG(CHILD_GENERATOR_SIGNATURE), data).bake().scale(scale).bake(); + return resources.noise().sampler(settings.childStyle(), key + CHILD_GENERATOR_SIGNATURE).scaled(scale); }); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java deleted file mode 100644 index c4cdb4918..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCaveProfile.java +++ /dev/null @@ -1,123 +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.terrain.carving; - -import art.arcane.iris.builtin.carve.CaveFieldModule; -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.noise.IrisStyledRange; -import art.arcane.iris.engine.object.value.IrisRange; - -import java.util.List; - -/** - * The parts of a {@link CaveProfile} that the carvers read as Iris's own noise and range types, made once per carver: - * the generator styles that build the cave fields, the ranges and the extra field modules. The carvers read these - * through Iris's generators because those keep Iris's coordinate caches and fast signed reads, which the cave - * hot paths rely on. - */ -public final class ResolvedCaveProfile { - private final IrisRange verticalRange; - private final IrisGeneratorStyle baseDensityStyle; - private final IrisGeneratorStyle detailDensityStyle; - private final IrisGeneratorStyle warpStyle; - private final IrisGeneratorStyle surfaceBreakStyle; - private final IrisStyledRange densityThreshold; - private final List modules; - - private ResolvedCaveProfile(CaveProfile settings) { - this.verticalRange = IrisValues.range(settings.verticalRange()); - this.baseDensityStyle = IrisValues.generatorStyle(settings.baseDensityStyle()); - this.detailDensityStyle = IrisValues.generatorStyle(settings.detailDensityStyle()); - this.warpStyle = IrisValues.generatorStyle(settings.warpStyle()); - this.surfaceBreakStyle = IrisValues.generatorStyle(settings.surfaceBreakStyle()); - this.densityThreshold = IrisValues.styledRange(settings.densityThreshold()); - this.modules = settings.modules().stream().map(Module::new).toList(); - } - - public static ResolvedCaveProfile of(CaveProfile settings) { - return new ResolvedCaveProfile(settings); - } - - public IrisRange verticalRange() { - return verticalRange; - } - - public IrisGeneratorStyle baseDensityStyle() { - return baseDensityStyle; - } - - public IrisGeneratorStyle detailDensityStyle() { - return detailDensityStyle; - } - - public IrisGeneratorStyle warpStyle() { - return warpStyle; - } - - public IrisGeneratorStyle surfaceBreakStyle() { - return surfaceBreakStyle; - } - - public IrisStyledRange densityThreshold() { - return densityThreshold; - } - - public List modules() { - return modules; - } - - /** One {@link CaveFieldModule} with its style and range as Iris's types. */ - public static final class Module { - private final IrisGeneratorStyle style; - private final double weight; - private final double threshold; - private final IrisRange verticalRange; - private final boolean invert; - - private Module(CaveFieldModule settings) { - this.style = IrisValues.generatorStyle(settings.style()); - this.weight = settings.weight(); - this.threshold = settings.threshold(); - this.verticalRange = IrisValues.range(settings.verticalRange()); - this.invert = settings.invert(); - } - - public IrisGeneratorStyle style() { - return style; - } - - public double weight() { - return weight; - } - - public double threshold() { - return threshold; - } - - public IrisRange verticalRange() { - return verticalRange; - } - - public boolean invert() { - return invert; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 668cebc73..82e2d9d63 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; @@ -415,7 +415,7 @@ public final class FloatingIslandSample { CNG wallWarp = entry.getWallWarpCng(baseSeed, data); double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude()); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); - IrisCaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); + CaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; double carveThreshold = entry.settings().carveThreshold(); boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; @@ -484,7 +484,7 @@ public final class FloatingIslandSample { return amplitude * fade; } - static boolean directCarveEnabled(ResolvedFloatingChild entry, IrisCaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { + static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; } @@ -500,7 +500,7 @@ public final class FloatingIslandSample { }); } - static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, IrisCaveProfileSampler carve, double carveThreshold) { + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CaveProfileSampler carve, double carveThreshold) { return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> carve.shouldCarve(x, y, z, carveThreshold)); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index f92556cd0..6949b9003 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -29,9 +29,8 @@ import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObjectScale; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.CarvingBands; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; -import art.arcane.iris.engine.object.terrain.carving.IrisCaveProfileSampler; +import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.util.project.noise.CNG; @@ -62,7 +61,7 @@ public final class ResolvedFloatingChild implements IRare { private final AtomicCache bottomCache = new AtomicCache<>(); private final AtomicCache wallWarpCache = new AtomicCache<>(); private final AtomicCache carveCache = new AtomicCache<>(); - private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); + private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); private final AtomicCache shrinkScaleCache = new AtomicCache<>(); public ResolvedFloatingChild(FloatingChildBiome settings) { @@ -132,7 +131,7 @@ public final class ResolvedFloatingChild implements IRare { return carveCache.aquire(() -> carveStyle.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); } - public IrisCaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { + public CaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { if (!hasCarvingReference()) { return null; } @@ -144,7 +143,7 @@ public final class ResolvedFloatingChild implements IRare { return null; } - return new IrisCaveProfileSampler(engine, profile); + return new CaveProfileSampler(data.getPackResources().noise(), engine.getSeedManager().getCarve(), profile); }); } @@ -158,9 +157,10 @@ public final class ResolvedFloatingChild implements IRare { return null; } - ResolvedCarvingEntry entry = CarvingBands.of(engine).index().get(carving); + CarvingResolver resolver = CarvingResolver.of(engine.getGeneration().world()); + ResolvedCarvingEntry entry = resolver.index().get(carving); if (entry != null) { - return CarvingResolver.resolveEntryBiome(engine, entry); + return resolver.entryBiome(entry) == null || data.getBiomeLoader() == null ? null : data.getBiomeLoader().load(entry.biomeKey().trim()); } if (data.getBiomeLoader() == null) { 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 index 327edb132..ace7709c7 100644 --- 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 @@ -186,8 +186,6 @@ public class IrisDimension extends IrisRegistrant { @MaxNumber(256) @Desc("Minimum air gap in blocks between the lower terrain surface and the upper terrain surface.") private int upperDimensionGap = 32; - @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") - private boolean upperDimensionCarving = false; @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") private boolean upperDimensionObjects = false; @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") @@ -245,10 +243,6 @@ public class IrisDimension extends IrisRegistrant { @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<>(); - @MinNumber(0) - @MaxNumber(318) - @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") - private int caveLavaHeight = 8; @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.") From 412987daf96a4ddb58033cf57f662ece2b346213 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:07:38 +0200 Subject: [PATCH 075/139] iris:objects owns objects, proceduralObjects, treeSettings and the dimension's object surface-support and upper-object switches as module settings; the host reads them through ObjectPlacements --- .../arcane/iris/builtin/loot/ObjectLoot.java | 76 ++++ .../iris/builtin/loot/ObjectLootEntry.java | 41 ++ .../iris/builtin/loot/ObjectVanillaLoot.java | 71 ++++ .../iris/builtin/objects/HeightmapNoise.java | 136 ++++++ .../iris/builtin/objects/ObjectPlacement.java | 315 ++++++++++++++ .../iris/builtin/objects/ObjectScale.java | 85 ++++ .../iris/builtin/objects/ObjectSettings.java | 47 +++ .../objects/ProceduralObjectSettings.java | 99 +++++ .../RequireSurfaceSupportSettings.java | 41 ++ .../builtin/objects/ScaleInterpolation.java | 33 ++ .../objects/SurfaceSupportBufferSettings.java | 45 ++ .../builtin/objects/TreeGrowthSettings.java | 50 +++ .../objects/TreeMode.java} | 12 +- .../iris/builtin/objects/TreeOverride.java | 76 ++++ .../arcane/iris/builtin/objects/TreeSize.java | 57 +++ .../objects/UpperObjectsForceSettings.java | 39 ++ .../builtin/objects/UpperObjectsSettings.java | 39 ++ .../objects/tree/Tree.java} | 397 ++++++++++++------ .../iris/builtin/spawn/PlacementMarker.java | 72 ++++ .../mantle/components/ObjectLocating.java | 5 +- .../mantle/components/ObjectModule.java | 30 +- .../mantle/components/ObjectPlacing.java | 63 +-- .../mantle/components/ObjectWarmUp.java | 13 +- .../engine/mantle/components/TreeGrowing.java | 41 +- .../object/placement/IrisObjectPlacement.java | 18 +- .../engine/object/placement/IrisTree.java | 83 ---- .../engine/object/placement/IrisTreeSize.java | 54 --- .../object/placement/ObjectPlacements.java | 139 ++++++ .../procedural/IrisProceduralObjects.java | 112 ----- .../procedural/ResolvedProceduralObjects.java | 69 +++ .../procedural/tree/IrisTreeSettings.java | 45 -- .../tree/ProceduralTreeGenerator.java | 10 +- .../object/procedural/tree/ResolvedTree.java | 120 ++++++ .../procedural/tree/TreeBlockResolver.java | 54 +-- .../procedural/tree/TreeCanopyBuilder.java | 43 +- .../procedural/tree/TreeDecoratorApplier.java | 6 +- .../object/procedural/tree/TreeFunctions.java | 40 +- .../procedural/tree/TreePlausibility.java | 6 +- .../procedural/tree/TreeRootBuilder.java | 10 +- .../procedural/tree/TreeTrunkBuilder.java | 48 +-- .../floating/ResolvedFloatingChild.java | 3 +- .../engine/object/world/biome/IrisBiome.java | 39 -- .../world/biome/IrisBiomeColorRenderer.java | 3 +- .../object/world/dimension/IrisDimension.java | 13 - .../object/world/region/IrisRegion.java | 39 -- 45 files changed, 2122 insertions(+), 715 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java create mode 100644 src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java create mode 100644 src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisTreeModes.java => builtin/objects/TreeMode.java} (78%) create mode 100644 src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/TreeSize.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java rename src/main/java/art/arcane/iris/{engine/object/procedural/tree/IrisProceduralTree.java => builtin/objects/tree/Tree.java} (59%) create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java create mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java new file mode 100644 index 000000000..95ca8dae0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -0,0 +1,76 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("object-loot") +@Desc("Represents loot within this object") +public final class ObjectLoot implements ObjectLootEntry { + @MinItems(1) + @Desc("The list of blocks this loot table should apply to") + private List filter = List.of(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The loot table name") + @Required + @ResourceRef(LootTable.class) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public ObjectLoot() { + } + + /** A table for every container of the placement. */ + public ObjectLoot(String name, int weight) { + this.name = name; + this.weight = weight; + } + + @Override + public String name() { + return name; + } + + @Override + public int weight() { + return weight; + } + + @Override + public boolean exact() { + return exact; + } + + @Override + public List filter() { + return filter == null ? List.of() : Collections.unmodifiableList(filter); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java new file mode 100644 index 000000000..92a2a5d77 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLootEntry.java @@ -0,0 +1,41 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; + +import java.util.List; + +/** + * One loot table an object placement gives its containers: which table, how often it is picked among the placement's + * tables, and which of the object's containers it is for. + */ +public interface ObjectLootEntry { + /** The table: a key of the pack's loot tables, or a key of the platform's. */ + String name(); + + /** How often the table is picked among equals; a table with no weight is never picked. */ + int weight(); + + /** Whether the table applies to the exact state of the blocks in {@link #filter}, not to every state of their kind of block. */ + boolean exact(); + + /** The blocks the table is for; none means every container the placement holds. */ + List filter(); +} diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java new file mode 100644 index 000000000..45351c4d1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java @@ -0,0 +1,71 @@ +/* + * 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.builtin.loot; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("object-vanilla-loot") +@Desc("Represents vanilla loot within this object") +public final class ObjectVanillaLoot implements ObjectLootEntry { + @MinItems(1) + @Desc("The list of blocks this loot table should apply to") + private List filter = List.of(); + @Desc("Exactly match the block data or not") + private boolean exact = false; + @Desc("The vanilla loot table key") + @Required + @Ref(Reference.LOOT_TABLE) + private String name; + @Desc("The weight of this loot table being chosen") + @MinNumber(1) + private int weight = 1; + + public ObjectVanillaLoot() { + } + + @Override + public String name() { + return name; + } + + @Override + public int weight() { + return weight; + } + + @Override + public boolean exact() { + return exact; + } + + @Override + public List filter() { + return filter == null ? List.of() : Collections.unmodifiableList(filter); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java b/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java new file mode 100644 index 000000000..2c1c85628 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java @@ -0,0 +1,136 @@ +/* + * 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.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; + +import java.util.Collections; +import java.util.List; + +/** The virtual heightmap an object placement may sit on instead of the terrain, written as the placement's {@code heightmap}. */ +@Snippet("generator") +@Desc("A noise generator") +public final class HeightmapNoise { + @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 NoiseStyle style = NoiseStyle.of("IRIS"); + @MinNumber(1) + @Desc("Multiple octaves for multple generators of changing zooms added together") + private int octaves = 1; + @MinItems(1) + @Desc("Apply a child noise generator to fracture the input coordinates of this generator") + private List fracture = List.of(); + + public HeightmapNoise() { + } + + public double zoom() { + return zoom; + } + + public boolean negative() { + return negative; + } + + public double opacity() { + return opacity; + } + + public double offsetX() { + return offsetX; + } + + public double offsetY() { + return offsetY; + } + + public double offsetZ() { + return offsetZ; + } + + public long seed() { + return seed; + } + + public boolean parametric() { + return parametric; + } + + public boolean bezier() { + return bezier; + } + + public boolean sinCentered() { + return sinCentered; + } + + public double exponent() { + return exponent; + } + + public boolean enabled() { + return enabled; + } + + public NoiseStyle style() { + return style; + } + + public int octaves() { + return octaves; + } + + public List fracture() { + return fracture == null ? List.of() : Collections.unmodifiableList(fracture); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java new file mode 100644 index 000000000..d0fc5c6e4 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -0,0 +1,315 @@ +/* + * 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.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.spawn.PlacementMarker; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * One object placement of a biome or region, an entry of its {@code objects}: which objects, how often, and how they sit + * in the world. {@code iris:objects} decides from the options it owns (what to place, chance, density, carving and + * surface support); Iris's placement stages read the rest from the placement itself, so this keeps the JSON the placement + * was written as ({@link #json()}) for Iris to read it again the way it reads placements everywhere else. + */ +@Snippet("object-placer") +@Desc("Represents an iris object placer. It places objects.") +@JsonAdapter(ObjectPlacement.KeepingItsJson.class) +public final class ObjectPlacement { + private static final int DEFAULT_SURFACE_SUPPORT_BUFFER = 2; + private static final int DEFAULT_SURFACE_SUPPORT_DEPTH = 2; + + @Required + @MinItems(1) + @Ref(Reference.PACK_OBJECT) + @Desc("List of objects to place") + private List place = List.of(); + @Desc("Rotate this objects placement") + private ObjectRotation rotation = new ObjectRotation(); + @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 StyledRange 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; + @MinItems(1) + @Desc("Add markers to blocks in this object") + private List markers = List.of(); + @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 = DEFAULT_SURFACE_SUPPORT_BUFFER; + @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 = DEFAULT_SURFACE_SUPPORT_DEPTH; + @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 HeightmapNoise 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 NoiseStyle warp = NoiseStyle.of(NoiseStyle.FLAT); + @Desc("The placement mode") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + @MinItems(1) + @Desc("Find and replace blocks") + private List edit = List.of(); + @Desc("Translate this object's placement") + private ObjectTranslate translate = new ObjectTranslate(); + @Desc("Scale Objects") + private ObjectScale scale = new ObjectScale(); + @MinItems(1) + @Desc("The loot tables to apply to these objects") + private List loot = List.of(); + @MinItems(1) + @Desc("The vanilla loot tables to apply to these objects") + private List vanillaLoot = List.of(); + @Desc("Whether the given loot tables override any and all other loot tables available in the dimension, region or biome.") + private boolean overrideGlobalLoot = false; + @MinItems(1) + @Desc("This object / these objects override the following trees when they grow...") + private List trees = List.of(); + @MinItems(1) + @Ref(Reference.PACK_OBJECT) + @Desc("List of objects to this object is allowed to collied with") + private List allowedCollisions = List.of(); + @MinItems(1) + @Ref(Reference.PACK_OBJECT) + @Desc("List of objects to this object is forbidden to collied with") + private List forbiddenCollisions = List.of(); + @Desc("Ignore any placement restrictions for this object") + @SerializedName(value = "forcePlace", alternate = {"force"}) + private boolean forcePlace = false; + + private transient volatile String json; + private transient volatile Object hostForm; + + public ObjectPlacement() { + } + + /** The objects to pick from, by the keys of the pack's objects. */ + public List place() { + return place == null ? List.of() : Collections.unmodifiableList(place); + } + + public double chance() { + return chance; + } + + /** The count of placements when the chance check passes, unless {@link #densityStyle()} picks it. */ + public int density() { + return density; + } + + public Optional densityStyle() { + return Optional.ofNullable(densityStyle); + } + + /** The fixed density, or, when a style picks the count, the middle of its range. */ + public int middleDensity() { + if (densityStyle == null) { + return density; + } + return (int) ((densityStyle.max() + densityStyle.min()) / 2); + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectTranslate translate() { + return translate; + } + + public ObjectScale scale() { + return scale; + } + + public NoiseStyle warp() { + return warp; + } + + public ObjectPlaceMode mode() { + return mode; + } + + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public CarvingMode carvingSupport() { + return carvingSupport; + } + + public CaveAnchorMode caveAnchorMode() { + return caveAnchorMode; + } + + public boolean underwater() { + return underwater; + } + + public boolean isDolphinTarget() { + return isDolphinTarget; + } + + public boolean forcePlace() { + return forcePlace; + } + + public boolean requireSurfaceSupport() { + return requireSurfaceSupport; + } + + public int surfaceSupportBuffer() { + return surfaceSupportBuffer; + } + + public List trees() { + return trees == null ? List.of() : Collections.unmodifiableList(trees); + } + + /** The JSON this placement was read from, which Iris reads again as its own placement; null for one made in code. */ + public String json() { + return json; + } + + /** + * What Iris made of {@link #json()} the last time it asked, kept here so it asks once. Only Iris sets or reads it, + * and it is its own type. + */ + public Object hostForm() { + return hostForm; + } + + public void hostForm(Object form) { + this.hostForm = form; + } + + /** Reads a placement like any settings and keeps the JSON it was read from. */ + public static final class KeepingItsJson implements TypeAdapterFactory { + @Override + @SuppressWarnings("unchecked") // The type is checked to be ObjectPlacement. + public TypeAdapter create(Gson gson, TypeToken type) { + if (type.getRawType() != ObjectPlacement.class) { + return null; + } + TypeAdapter placements = gson.getDelegateAdapter(this, TypeToken.get(ObjectPlacement.class)); + TypeAdapter elements = gson.getAdapter(JsonElement.class); + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ObjectPlacement placement) throws IOException { + placements.write(out, placement); + } + + @Override + public ObjectPlacement read(JsonReader in) throws IOException { + JsonElement written = elements.read(in); + ObjectPlacement placement = placements.fromJsonTree(written); + if (placement != null) { + placement.json = written.toString(); + } + return placement; + } + }.nullSafe(); + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java new file mode 100644 index 000000000..2390f0654 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java @@ -0,0 +1,85 @@ +/* + * 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.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +/** How an object placement scales its objects, written as the placement's {@code scale}. */ +@Snippet("object-scale") +@Desc("Scale Objects") +public final class ObjectScale { + private static final double NO_SCALE = 1; + + @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 = NO_SCALE; + + @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 = NO_SCALE; + + @MinNumber(0.01) + @MaxNumber(50) + @Desc("The maximum scale. Used when size is 1 to pick a random scale per placement.") + private double maximumScale = NO_SCALE; + + @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 ScaleInterpolation interpolation = ScaleInterpolation.NONE; + + public ObjectScale() { + } + + public double size() { + return size; + } + + public int variations() { + return variations; + } + + public double minimumScale() { + return minimumScale; + } + + public double maximumScale() { + return maximumScale; + } + + public ScaleInterpolation interpolation() { + return interpolation == null ? ScaleInterpolation.NONE : interpolation; + } + + /** The largest factor this scale makes an object, which a placement's reach has to cover. */ + public double maxScale() { + if (size != NO_SCALE) { + return size; + } + return Math.max(minimumScale, maximumScale); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java new file mode 100644 index 000000000..c1b7484c1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java @@ -0,0 +1,47 @@ +/* + * 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.builtin.objects; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The object placements a region or biome declares, written as {@code "objects": [...]}, the list of placements. A chunk + * places those of its centre column's region and of that column's biome, and of the cave biome where it places in caves. + */ +@Desc("Objects define what schematics (iob files) iris will place here") +@Feature(id = "iris:objects", name = "Objects", key = "objects", root = "objects", targets = {Target.REGION, Target.BIOME}) +public final class ObjectSettings implements IrisFeature { + @MinItems(1) + @Desc("Objects define what schematics (iob files) iris will place here") + private List objects = List.of(); + + public ObjectSettings() { + } + + public List objects() { + return objects == null ? List.of() : Collections.unmodifiableList(objects); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java b/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java new file mode 100644 index 000000000..a23f89b5c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java @@ -0,0 +1,99 @@ +/* + * 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.builtin.objects; + +import art.arcane.iris.builtin.objects.coral.Coral; +import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.builtin.objects.ruin.Ruin; +import art.arcane.iris.builtin.objects.tree.Tree; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** + * The procedural objects a region or biome declares, written as {@code "proceduralObjects": {"trees": [...], ...}}: things + * Iris generates from scratch at world-gen time and places like object placements. + */ +@Snippet("procedural-objects") +@Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") +@Feature(id = "iris:objects/procedural", name = "Procedural objects", key = "proceduralObjects", targets = {Target.REGION, Target.BIOME}) +public final class ProceduralObjectSettings implements IrisFeature { + @MinItems(1) + @Desc("Procedurally generated trees.") + private List trees = List.of(); + + @MinItems(1) + @Desc("Procedurally generated ruins (crumbling pillars, walls, arches, rubble).") + private List ruins = List.of(); + + @MinItems(1) + @Desc("Procedurally generated natural rock formations (spires, hoodoos, arches, sea stacks, boulders, basalt columns).") + private List formations = List.of(); + + @MinItems(1) + @Desc("Procedurally generated underwater coral structures.") + private List coral = List.of(); + + @MinItems(1) + @Desc("Procedurally generated mushrooms and shelf fungi.") + private List fungi = List.of(); + + @MinItems(1) + @Desc("Procedurally generated crystal clusters (usually placed in caves).") + private List crystals = List.of(); + + public ProceduralObjectSettings() { + } + + public List trees() { + return view(trees); + } + + public List ruins() { + return view(ruins); + } + + public List formations() { + return view(formations); + } + + public List coral() { + return view(coral); + } + + public List fungi() { + return view(fungi); + } + + public List crystals() { + return view(crystals); + } + + private static List view(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java b/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java new file mode 100644 index 000000000..684951af1 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java @@ -0,0 +1,41 @@ +/* + * 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.builtin.objects; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension refuses surface objects over carved openings, written as {@code "requireObjectSurfaceSupport": true}. */ +@Desc("Refuse to place surface objects and trees over carved surface openings.") +@Feature(id = "iris:objects/surface-support", name = "Require surface support", key = "requireObjectSurfaceSupport", root = "require", targets = Target.DIMENSION) +public final class RequireSurfaceSupportSettings implements IrisFeature { + private static final boolean DEFAULT_REQUIRED = true; + + @Desc("Refuse to place surface objects and trees over carved surface openings.") + private boolean require = DEFAULT_REQUIRED; + + public RequireSurfaceSupportSettings() { + } + + public boolean require() { + return require; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java b/src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java new file mode 100644 index 000000000..077e3e80e --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ScaleInterpolation.java @@ -0,0 +1,33 @@ +/* + * 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.builtin.objects; + +import com.volmit.config.Desc; + +@Desc("Use 3D Interpolation on scaled objects if they are larger than the origin.") +public enum ScaleInterpolation { + @Desc("Don't interpolate, big cubes") + NONE, + @Desc("Uses linear interpolation in 3 dimensions, generally pretty good, but slow") + TRILINEAR, + @Desc("Uses cubic spline interpolation in 3 dimensions, even better, but extreme slowdowns") + TRICUBIC, + @Desc("Uses hermite spline interpolation in 3 dimensions, even better, but extreme slowdowns") + TRIHERMITE +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java b/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java new file mode 100644 index 000000000..91b44f3ec --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java @@ -0,0 +1,45 @@ +/* + * 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.builtin.objects; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** The least surface-support buffer a dimension gives its surface objects, written as {@code "objectSurfaceSupportBuffer": 2}. */ +@Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") +@Feature(id = "iris:objects/surface-support-buffer", name = "Surface support buffer", key = "objectSurfaceSupportBuffer", root = "buffer", targets = Target.DIMENSION) +public final class SurfaceSupportBufferSettings implements IrisFeature { + private static final int DEFAULT_BUFFER_BLOCKS = 2; + + @MinNumber(0) + @MaxNumber(16) + @Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") + private int buffer = DEFAULT_BUFFER_BLOCKS; + + public SurfaceSupportBufferSettings() { + } + + public int buffer() { + return buffer; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java b/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java new file mode 100644 index 000000000..584fe7ea3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java @@ -0,0 +1,50 @@ +/* + * 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.builtin.objects; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** Whether a dimension's saplings grow the trees of its object placements, written as {@code "treeSettings": {...}}. */ +@Snippet("tree-settings") +@Desc("Tree growth override settings") +@Feature(id = "iris:objects/trees", name = "Tree growth", key = "treeSettings", targets = Target.DIMENSION) +public final class TreeGrowthSettings implements IrisFeature { + @Required + @Desc("Turn replacing on and off") + private boolean enabled = false; + + @Desc("Object picking modes") + private TreeMode mode = TreeMode.FIRST; + + public TreeGrowthSettings() { + } + + public boolean enabled() { + return enabled; + } + + public TreeMode mode() { + return mode == null ? TreeMode.FIRST : mode; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java b/src/main/java/art/arcane/iris/builtin/objects/TreeMode.java similarity index 78% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java rename to src/main/java/art/arcane/iris/builtin/objects/TreeMode.java index 060e506ed..a0c643406 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeModes.java +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeMode.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,15 +16,15 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Sapling override object picking options") -public enum IrisTreeModes { +public enum TreeMode { @Desc("Check biome, then region, pick the first one that has options. Dimension placements are not consulted.") FIRST, @Desc("Check biome, regions, and dimensions, and pick any option from the total list") ALL -} \ No newline at end of file +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java b/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java new file mode 100644 index 000000000..398959a35 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java @@ -0,0 +1,76 @@ +/* + * 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.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** The trees an object placement overrides when their saplings grow, an entry of the placement's {@code trees}. */ +@Snippet("tree") +@Desc("Tree replace options for this object placer") +public final class TreeOverride { + @Required + @MinItems(1) + @Desc("The types of trees overwritten by this object") + private List treeTypes = List.of(); + + @Required + @MinItems(1) + @Desc("The size of the square of saplings this applies to (2 means a 2 * 2 sapling area)") + private List sizes = List.of(); + + public TreeOverride() { + } + + public List treeTypes() { + return treeTypes == null ? List.of() : Collections.unmodifiableList(treeTypes); + } + + public List sizes() { + return sizes == null ? List.of() : Collections.unmodifiableList(sizes); + } + + /** Whether this override is for a sapling area of {@code width} by {@code depth} growing the species {@code species}. */ + public boolean matches(int width, int depth, String species) { + return matchesSize(width, depth) && matchesSpecies(species); + } + + private boolean matchesSize(int width, int depth) { + for (TreeSize size : sizes()) { + if (size.matches(width, depth)) { + return true; + } + } + return false; + } + + private boolean matchesSpecies(String species) { + for (String type : treeTypes()) { + if (type != null && type.equalsIgnoreCase(species)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java b/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java new file mode 100644 index 000000000..3c6edd7b9 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java @@ -0,0 +1,57 @@ +/* + * 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.builtin.objects; + +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +/** The size of a sapling area, in saplings, that a tree override applies to. */ +@Snippet("tree-size") +@Desc("Sapling override object picking options") +public final class TreeSize { + @Required + @Desc("The width of the sapling area") + private int width = 1; + + @Required + @Desc("The depth of the sapling area") + private int depth = 1; + + public TreeSize() { + } + + public TreeSize(int width, int depth) { + this.width = width; + this.depth = depth; + } + + public int width() { + return width; + } + + public int depth() { + return depth; + } + + /** Whether an area of {@code otherWidth} by {@code otherDepth} saplings is this size, turned either way. */ + public boolean matches(int otherWidth, int otherDepth) { + return (width == otherWidth && depth == otherDepth) || (depth == otherWidth && width == otherDepth); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java new file mode 100644 index 000000000..5264ce562 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java @@ -0,0 +1,39 @@ +/* + * 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.builtin.objects; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether the objects placed in the terrain stacked above ignore placement restrictions, written as {@code "upperObjectsForcePlace": true}. */ +@Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") +@Feature(id = "iris:objects/upper-force", name = "Force upper dimension objects", key = "upperObjectsForcePlace", root = "force", targets = Target.DIMENSION) +public final class UpperObjectsForceSettings implements IrisFeature { + @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") + private boolean force = false; + + public UpperObjectsForceSettings() { + } + + public boolean force() { + return force; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java new file mode 100644 index 000000000..9d9c832fe --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java @@ -0,0 +1,39 @@ +/* + * 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.builtin.objects; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether the objects of a dimension are also placed in the terrain stacked above it, written as {@code "upperDimensionObjects": true}. */ +@Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") +@Feature(id = "iris:objects/upper", name = "Upper dimension objects", key = "upperDimensionObjects", root = "enabled", targets = Target.DIMENSION) +public final class UpperObjectsSettings implements IrisFeature { + @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") + private boolean enabled = false; + + public UpperObjectsSettings() { + } + + public boolean enabled() { + return enabled; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java b/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java similarity index 59% rename from src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java rename to src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java index 80d69facd..bc3fdbdab 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisProceduralTree.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,53 +16,32 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural.tree; +package art.arcane.iris.builtin.objects.tree; -import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; -import art.arcane.iris.builtin.objects.tree.TreeDecorator; -import art.arcane.iris.builtin.objects.tree.TreeCanopy; -import art.arcane.iris.builtin.objects.tree.TreeRootStyle; -import art.arcane.iris.builtin.objects.tree.TreeProfile; -import art.arcane.iris.builtin.objects.tree.TreeFunction; -import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.core.loader.IrisData; -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.RegistryListBlockType; -import art.arcane.iris.engine.object.annotations.Required; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.iris.engine.object.procedural.tree.ProceduralTreeGenerator; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; @Snippet("procedural-tree") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor @Desc("A single procedurally generated tree. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") -@Data -public class IrisProceduralTree implements IrisProceduralPlacement { - private final transient AtomicCache> variantCache = new AtomicCache<>(); - +public final class Tree { @Desc("A human readable name used in logs and as the variant load key.") private String name = "procedural-tree"; @@ -90,7 +69,7 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; @Desc("Rotate this tree's placement.") - private IrisObjectRotation rotation = new IrisObjectRotation(); + private ObjectRotation rotation = new ObjectRotation(); @Desc("Limit the max or min height of placement.") private ObjectLimit clamp = new ObjectLimit(); @@ -102,7 +81,7 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private boolean underwater = false; @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + private ObjectTranslate translate = new ObjectTranslate(); @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") private StiltSettings stiltSettings; @@ -112,19 +91,19 @@ public class IrisProceduralTree implements IrisProceduralPlacement { @Required @Desc("The trunk (log) block, e.g. minecraft:oak_log. Ignored when trunkPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String trunk = "minecraft:oak_log"; @Desc("A noise-driven palette for the trunk. When set this overrides the single trunk block, letting the trunk mix blocks by noise.") - private IrisMaterialPalette trunkPalette = null; + private PaletteSpec trunkPalette; @Required @Desc("The leaf block, e.g. minecraft:oak_leaves. Ignored when leavesPalette is set.") - @RegistryListBlockType + @Ref(Reference.BLOCK) private String leaves = "minecraft:oak_leaves"; @Desc("A noise-driven palette for the leaves. When set this overrides the single leaf block, letting the canopy mix leaf (or other) blocks by noise. Only blocks that are actually leaves get vanilla decay distances.") - private IrisMaterialPalette leavesPalette = null; + private PaletteSpec leavesPalette; @Desc("The named canopy profile that drives default crown radii and shape.") private TreeProfile profile = TreeProfile.OAK; @@ -209,27 +188,27 @@ public class IrisProceduralTree implements IrisProceduralPlacement { private int azimuthWhorlCount = 5; @Desc("Optional accent leaf block scattered through the canopy (blossoms, shroomlight).") - @RegistryListBlockType - private String secondaryLeaves = null; + @Ref(Reference.BLOCK) + private String secondaryLeaves; @MinNumber(0) @MaxNumber(1) @Desc("The fraction of leaves replaced by the secondary leaf block(s).") private double secondaryLeafFraction = 0.35; - @ArrayType(min = 1, type = TreeSecondaryLeaf.class) + @MinItems(1) @Desc("Optional weighted set of accent leaf blocks. When set this overrides the single secondaryLeaves block.") - private KList weightedSecondaryLeaves = new KList<>(); + private List weightedSecondaryLeaves = List.of(); @Desc("A noise-driven palette for the secondary (accent) leaves. When set this overrides both secondaryLeaves and weightedSecondaryLeaves.") - private IrisMaterialPalette secondaryLeavesPalette = null; + private PaletteSpec secondaryLeavesPalette; @Desc("Optional secondary trunk block used over a height band (for color-banded trunks). Ignored when secondaryTrunkPalette is set.") - @RegistryListBlockType - private String secondaryTrunk = null; + @Ref(Reference.BLOCK) + private String secondaryTrunk; @Desc("A noise-driven palette for the secondary trunk band. When set this overrides the single secondaryTrunk block.") - private IrisMaterialPalette secondaryTrunkPalette = null; + private PaletteSpec secondaryTrunkPalette; @MinNumber(0) @MaxNumber(1) @@ -271,80 +250,254 @@ public class IrisProceduralTree implements IrisProceduralPlacement { @Desc("The leaf crown configuration.") private TreeCanopy canopy = new TreeCanopy(); - @ArrayType(min = 1, type = TreeDecorator.class) + @MinItems(1) @Desc("Accent decorators applied after the tree is built (fruit, vines, snow, glow).") - private KList decorators = new KList<>(); + private List decorators = List.of(); - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> { - KList baked = new KList<>(); - int count = Math.max(1, variants); - int lo = Math.min(heightMin, heightMax); - int hi = Math.max(heightMin, heightMax); - RNG heightRng = new RNG(seed); - - for (int i = 0; i < count; i++) { - int height; - if (count == 1 || lo == hi) { - height = heightRng.i(lo, hi + 1); - } else { - double step = (hi - lo) / (double) (count - 1); - double base = lo + step * i; - double jitter = heightRng.d(-step * 0.3, step * 0.3); - height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); - } - - IrisObject object = ProceduralTreeGenerator.generate(this, Math.max(2, height), new RNG(seed + (i * 7919L)), data); - if (object == null || object.getBlocks().isEmpty()) { - continue; - } - object.setLoadKey(getVariantLoadKey(i)); - object.setLoader(data); - baked.add(object); - } - - if (new java.io.File("plugins/Iris/goldendebug.txt").isFile()) { - for (IrisObject object : baked) { - long[] digest = new long[]{0L}; - object.getBlocks().forEach((vector, state) -> { - long position = ((long) vector.getBlockX() << 40) ^ ((long) vector.getBlockY() << 20) ^ vector.getBlockZ(); - digest[0] ^= Long.rotateLeft(position * 0x9E3779B97F4A7C15L ^ state.key().hashCode(), (int) (position & 63)); - }); - IrisLogging.debug("Goldendebug bake: " + object.getLoadKey() + " blocks=" + object.getBlocks().size() + " digest=" + Long.toHexString(digest[0])); - } - } - - return baked; - }); + public Tree() { } - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); + public String name() { + return name; } - public String getVariantLoadKey(int index) { - if (index < 0) { - throw new IllegalArgumentException("index must not be negative"); - } - return "procedural/tree/" + name + "#" + index; + public double chance() { + return chance; } - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(mode); - placement.setRotation(rotation); - placement.setClamp(clamp); - placement.setCarvingSupport(carvingSupport); - placement.setUnderwater(underwater); - placement.setTranslate(translate); - placement.setStiltSettings(stiltSettings); - placement.setVacuumSettings(vacuumSettings); - placement.setChance(chance); - placement.setDensity(density); - return placement; + public int density() { + return density; + } + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public boolean plausible() { + return plausible; + } + + public ObjectPlaceMode mode() { + return mode; + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public CarvingMode carvingSupport() { + return carvingSupport; + } + + public boolean underwater() { + return underwater; + } + + public ObjectTranslate translate() { + return translate; + } + + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); + } + + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); + } + + public String trunk() { + return trunk; + } + + public Optional trunkPalette() { + return Optional.ofNullable(trunkPalette); + } + + public String leaves() { + return leaves; + } + + public Optional leavesPalette() { + return Optional.ofNullable(leavesPalette); + } + + public TreeProfile profile() { + return profile; + } + + public int heightMin() { + return heightMin; + } + + public int heightMax() { + return heightMax; + } + + public int trunkWidth() { + return trunkWidth; + } + + public TreeFunction trunkShape() { + return trunkShape; + } + + public double shapeStart() { + return shapeStart; + } + + public double shapeEnd() { + return shapeEnd; + } + + public double shapeSteepness() { + return shapeSteepness; + } + + public double shapeBase() { + return shapeBase; + } + + public double shapePeriod() { + return shapePeriod; + } + + public double shapeAmplitude() { + return shapeAmplitude; + } + + public double shapePeakOffset() { + return shapePeakOffset; + } + + public double shapeFloor() { + return shapeFloor; + } + + public double leanAzimuth() { + return leanAzimuth; + } + + public double leanAngle() { + return leanAngle; + } + + public TreeFunction trunkCurve() { + return trunkCurve; + } + + public double curveSteepness() { + return curveSteepness; + } + + public TreeAzimuthMode leanAzimuthMode() { + return leanAzimuthMode; + } + + public double azimuthStart() { + return azimuthStart; + } + + public double azimuthEnd() { + return azimuthEnd; + } + + public double azimuthTurns() { + return azimuthTurns; + } + + public double azimuthAmplitude() { + return azimuthAmplitude; + } + + public double azimuthPeriod() { + return azimuthPeriod; + } + + public double azimuthOffset() { + return azimuthOffset; + } + + public double azimuthScale() { + return azimuthScale; + } + + public int azimuthWhorlCount() { + return azimuthWhorlCount; + } + + public Optional secondaryLeaves() { + return Optional.ofNullable(secondaryLeaves); + } + + public double secondaryLeafFraction() { + return secondaryLeafFraction; + } + + public List weightedSecondaryLeaves() { + return weightedSecondaryLeaves == null ? List.of() : Collections.unmodifiableList(weightedSecondaryLeaves); + } + + public Optional secondaryLeavesPalette() { + return Optional.ofNullable(secondaryLeavesPalette); + } + + public Optional secondaryTrunk() { + return Optional.ofNullable(secondaryTrunk); + } + + public Optional secondaryTrunkPalette() { + return Optional.ofNullable(secondaryTrunkPalette); + } + + public double secondaryTrunkStart() { + return secondaryTrunkStart; + } + + public double secondaryTrunkEnd() { + return secondaryTrunkEnd; + } + + public boolean roots() { + return roots; + } + + public TreeRootStyle rootStyle() { + return rootStyle; + } + + public int rootDepth() { + return rootDepth; + } + + public double rootFlare() { + return rootFlare; + } + + public int trunkForks() { + return trunkForks; + } + + public double forkHeight() { + return forkHeight; + } + + public double forkAngle() { + return forkAngle; + } + + public TreeCanopy canopy() { + return canopy; + } + + public List decorators() { + return decorators == null ? List.of() : Collections.unmodifiableList(decorators); } } diff --git a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java new file mode 100644 index 000000000..435cc4af5 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -0,0 +1,72 @@ +/* + * 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.builtin.spawn; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +/** Blocks of an object placement that get a {@link SpawnMarker}, an entry of the placement's {@code markers}. */ +@Snippet("object-marker") +@Desc("Find blocks to mark") +public final class PlacementMarker { + @MinItems(1) + @Required + @Desc("Find block types to mark") + private List mark = List.of(); + @MinNumber(1) + @MaxNumber(16) + @Desc("The maximum amount of markers to place. Use these sparingly!") + private int maximumMarkers = 8; + @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") + private boolean exact = false; + @Required + @ResourceRef(SpawnMarker.class) + @Desc("The marker to add") + private String marker; + + public PlacementMarker() { + } + + /** The blocks that get a marker. */ + public List mark() { + return mark == null ? List.of() : Collections.unmodifiableList(mark); + } + + public int maximumMarkers() { + return maximumMarkers; + } + + public boolean exact() { + return exact; + } + + /** The key of the {@link SpawnMarker} to place. */ + public String marker() { + return marker; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index e4e27f575..98b448b57 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.engine.object.placement.ObjectPlacements; import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; @@ -44,14 +45,14 @@ public final class ObjectLocating implements ObjectsAt { Engine engine = engine(world); Set biomes = new LinkedHashSet<>(); for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - if (biome != null && placesObject(biome.getSurfaceObjects(), objectKey)) { + if (biome != null && placesObject(ObjectPlacements.surface(biome), objectKey)) { biomes.add(biome.getLoadKey()); } } Set regions = new LinkedHashSet<>(); for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region != null && placesObject(region.getSurfaceObjects(), objectKey)) { + if (region != null && placesObject(ObjectPlacements.surface(region), objectKey)) { regions.add(region.getLoadKey()); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index b4b572e9b..de1aa17d6 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -19,14 +19,13 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.builtin.objects.crystal.Crystal; -import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.builtin.objects.tree.TreeCanopy; -import art.arcane.iris.builtin.objects.tree.TreeDecorator; -import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +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.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.core.modules.IrisPackWorld; @@ -71,14 +70,13 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { log = registry.log(); registry.registerService(ObjectsAt.class, new ObjectLocating()); registry.registerService(SaplingGrowth.class, new TreeGrowing()); - registry.registerHeldType(TreeCanopy.class); - registry.registerHeldType(TreeDecorator.class); - registry.registerHeldType(TreeSecondaryLeaf.class); - registry.registerHeldType(Coral.class); - registry.registerHeldType(Crystal.class); - registry.registerHeldType(Formation.class); - registry.registerHeldType(Fungus.class); - registry.registerHeldType(Ruin.class); + registry.registerSettings(ObjectSettings.class); + registry.registerSettings(ProceduralObjectSettings.class); + registry.registerSettings(TreeGrowthSettings.class); + registry.registerSettings(RequireSurfaceSupportSettings.class); + registry.registerSettings(SurfaceSupportBufferSettings.class); + registry.registerSettings(UpperObjectsSettings.class); + registry.registerSettings(UpperObjectsForceSettings.class); registry.registerLifecycle(this); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 87f2a3f23..92ae78dc8 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -27,6 +27,7 @@ import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.placement.ObjectPlacements; import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.util.common.data.B; @@ -43,9 +44,9 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; @@ -145,8 +146,8 @@ public class ObjectPlacing { + " surfaceY=" + surfaceY + " maxAnchorY=" + maxY + " carvedAtCenter=" + carvedBlocks - + " biomeCarvingObjects=" + caveBiome.getCarvingObjects().size() - + " regionCarvingObjects=" + region.getCarvingObjects().size() + + " biomeCarvingObjects=" + ObjectPlacements.carving(caveBiome).size() + + " regionCarvingObjects=" + ObjectPlacements.carving(region).size() + " sameBiome=" + (caveBiome == surfaceBiome || java.util.Objects.equals(caveBiome.getLoadKey(), surfaceBiome.getLoadKey()))); } if (traceRegen) { @@ -154,16 +155,16 @@ public class ObjectPlacing { + " surfaceBiome=" + surfaceBiome.getLoadKey() + " caveBiome=" + caveBiome.getLoadKey() + " region=" + region.getLoadKey() - + " biomeSurfacePlacers=" + surfaceBiome.getSurfaceObjects().size() - + " biomeCavePlacers=" + caveBiome.getCarvingObjects().size() - + " regionSurfacePlacers=" + region.getSurfaceObjects().size() - + " regionCavePlacers=" + region.getCarvingObjects().size()); + + " biomeSurfacePlacers=" + ObjectPlacements.surface(surfaceBiome).size() + + " biomeCavePlacers=" + ObjectPlacements.carving(caveBiome).size() + + " regionSurfacePlacers=" + ObjectPlacements.surface(region).size() + + " regionCavePlacers=" + ObjectPlacements.carving(region).size()); } ObjectPlacementSummary summary = placeObjects(writer, rng, x, z, surfaceBiome, caveBiome, region, complex, traceRegen); placeProceduralObjects(writer, rng, x, z, surfaceBiome, caveBiome, region); UpperDimensionContext upperCtx = engine.getUpperContext(); IrisDimension dimension = engine.getDimension(); - if (upperCtx != null && dimension.isUpperDimensionObjects()) { + if (upperCtx != null && ObjectPlacements.upperObjects(dimension)) { placeUpperObjects(writer, rng, x, z, xxx, zzz, surfaceY, upperCtx, dimension, complex, traceRegen); } if (traceRegen) { @@ -212,7 +213,7 @@ public class ObjectPlacing { continue; } - if (!sampled.getCarvingObjects().isEmpty()) { + if (!ObjectPlacements.carving(sampled).isEmpty()) { ladderChoice = sampled; } } @@ -243,7 +244,7 @@ public class ObjectPlacing { CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), CaveProfiles.declaredBy(caveBiome)); CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); - for (IrisObjectPlacement i : surfaceBiome.getSurfaceObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.surface(surfaceBiome)) { biomeSurfaceChecked++; boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); if (traceRegen) { @@ -272,7 +273,7 @@ public class ObjectPlacing { } } - for (IrisObjectPlacement i : caveBiome.getCarvingObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.carving(caveBiome)) { if (!i.getCarvingSupport().supportsCarving()) { continue; } @@ -304,7 +305,7 @@ public class ObjectPlacing { } } - for (IrisObjectPlacement i : region.getSurfaceObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.surface(region)) { regionSurfaceChecked++; boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); if (traceRegen) { @@ -333,7 +334,7 @@ public class ObjectPlacing { } } - for (IrisObjectPlacement i : region.getCarvingObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.carving(region)) { if (!i.getCarvingSupport().supportsCarving()) { continue; } @@ -386,11 +387,11 @@ public class ObjectPlacing { private void placeProceduralObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region) { CaveProfile surfaceCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(surfaceBiome), CaveProfiles.declaredBy(region)); CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), caveBiome == null ? null : CaveProfiles.declaredBy(caveBiome)); - placeProceduralFrom(writer, rng, x, z, surfaceBiome.getProceduralObjects(), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); - placeProceduralFrom(writer, rng, x, z, region.getProceduralObjects(), region.getName(), regionCaveProfile, null); + placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(surfaceBiome), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); + placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(region), region.getName(), regionCaveProfile, null); if (caveBiome != null && caveBiome != surfaceBiome) { CaveProfile caveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); - placeProceduralFrom(writer, rng, x, z, caveBiome.getProceduralObjects(), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); + placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(caveBiome), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); } } @@ -400,7 +401,7 @@ public class ObjectPlacing { RNG rng, int x, int z, - IrisProceduralObjects proceduralObjects, + ResolvedProceduralObjects proceduralObjects, String scope, CaveProfile caveProfile, String expectedCaveBiomeKey @@ -414,7 +415,7 @@ public class ObjectPlacing { boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(x, z); CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); for (IrisProceduralPlacement p : proceduralObjects.getAllPlacements()) { - boolean treePlacement = p instanceof IrisProceduralTree; + boolean treePlacement = p instanceof ResolvedTree; boolean chancePassed = passesProceduralChance(rng, p.getChance()); if (golden) { log.debug("Goldendebug procedural chance: chunk=" + x + "," + z @@ -979,9 +980,9 @@ public class ObjectPlacing { return; } - boolean forcePlace = dimension.isUpperObjectsForcePlace(); + boolean forcePlace = ObjectPlacements.upperObjectsForced(dimension); if (upperBiome != null) { - for (IrisObjectPlacement i : upperBiome.getSurfaceObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.surface(upperBiome)) { if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { continue; } @@ -995,7 +996,7 @@ public class ObjectPlacing { } if (upperRegion != null) { - for (IrisObjectPlacement i : upperRegion.getSurfaceObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.surface(upperRegion)) { if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { continue; } @@ -1163,8 +1164,8 @@ public class ObjectPlacing { /** Dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ private IrisObjectPlacement applyDimensionSurfaceSupport(IrisObjectPlacement placement) { IrisDimension dimension = engine.getDimension(); - boolean require = placement.isRequireSurfaceSupport() && dimension.isRequireObjectSurfaceSupport(); - int buffer = Math.max(placement.getSurfaceSupportBuffer(), dimension.getObjectSurfaceSupportBuffer()); + boolean require = placement.isRequireSurfaceSupport() && ObjectPlacements.requiresSurfaceSupport(dimension); + int buffer = Math.max(placement.getSurfaceSupportBuffer(), ObjectPlacements.surfaceSupportBuffer(dimension)); if (require == placement.isRequireSurfaceSupport() && buffer == placement.getSurfaceSupportBuffer()) { return placement; } @@ -1432,13 +1433,13 @@ public class ObjectPlacing { IrisBiome biome = engine.getSurfaceBiome((x << 4) + 8, (z << 4) + 8); IrisRegion region = engine.getRegion((x << 4) + 8, (z << 4) + 8); Set v = new KSet<>(); - for (IrisObjectPlacement i : biome.getSurfaceObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.surface(biome)) { if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { v.addAll(guessPlacedKeys(rng, x, z, i)); } } - for (IrisObjectPlacement i : region.getSurfaceObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.surface(region)) { if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { v.addAll(guessPlacedKeys(rng, x, z, i)); } @@ -1457,15 +1458,15 @@ public class ObjectPlacing { if (region == null) { continue; } - radius = Math.max(radius, computePlacementRadius(region.getObjects(), sizeCache, warnedLargeObjects)); - radius = Math.max(radius, computeProceduralRadius(region.getProceduralObjects())); + radius = Math.max(radius, computePlacementRadius(ObjectPlacements.all(region), sizeCache, warnedLargeObjects)); + radius = Math.max(radius, computeProceduralRadius(ObjectPlacements.procedural(region))); } for (IrisBiome biome : dimension.getReachableBiomes(engine)) { if (biome == null) { continue; } - radius = Math.max(radius, computePlacementRadius(biome.getObjects(), sizeCache, warnedLargeObjects)); - radius = Math.max(radius, computeProceduralRadius(biome.getProceduralObjects())); + radius = Math.max(radius, computePlacementRadius(ObjectPlacements.all(biome), sizeCache, warnedLargeObjects)); + radius = Math.max(radius, computeProceduralRadius(ObjectPlacements.procedural(biome))); } return radius; @@ -1500,7 +1501,7 @@ public class ObjectPlacing { return radius; } - private int computeProceduralRadius(IrisProceduralObjects procedural) { + private int computeProceduralRadius(ResolvedProceduralObjects procedural) { if (procedural == null || procedural.isEmpty()) { return 0; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 71880284c..5f8855641 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -20,7 +20,8 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; +import art.arcane.iris.engine.object.placement.ObjectPlacements; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; @@ -52,15 +53,15 @@ final class ObjectWarmUp { KList biomes = engine.getAllBiomes(); biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); for (IrisBiome biome : biomes) { - warmPlacements(biome.getObjects()); - warmProcedural(biome.getProceduralObjects()); + warmPlacements(ObjectPlacements.all(biome)); + warmProcedural(ObjectPlacements.procedural(biome)); } KList regions = engine.getDimension().getAllRegions(engine); regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); for (IrisRegion region : regions) { - warmPlacements(region.getObjects()); - warmProcedural(region.getProceduralObjects()); + warmPlacements(ObjectPlacements.all(region)); + warmProcedural(ObjectPlacements.procedural(region)); } } @@ -78,7 +79,7 @@ final class ObjectWarmUp { } } - private void warmProcedural(IrisProceduralObjects procedural) { + private void warmProcedural(ResolvedProceduralObjects procedural) { if (procedural == null) { return; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 40dee1a6d..bd8a3c3d1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -24,12 +24,13 @@ import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.IrisTreeSize; +import art.arcane.iris.engine.object.placement.ObjectPlacements; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.procedural.tree.IrisTreeModes; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; +import art.arcane.iris.builtin.objects.TreeMode; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.spi.IrisPlatforms; @@ -54,12 +55,13 @@ import java.util.Set; * of blocks the host then places. The same placements tell which objects are trees. */ public final class TreeGrowing implements SaplingGrowth { - private static final IrisTreeSize SAPLING_SIZE = new IrisTreeSize(1, 1); + private static final int SAPLING_WIDTH = 1; + private static final int SAPLING_DEPTH = 1; @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { Engine engine = IrisPackWorld.of(world).engine(); - if (!engine.getDimension().getTreeSettings().isEnabled()) { + if (!ObjectPlacements.treeGrowth(engine.getDimension()).enabled()) { return Optional.empty(); } @@ -84,14 +86,14 @@ public final class TreeGrowing implements SaplingGrowth { for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { if (region != null) { - collectPlacements(region.getObjects(), objects); - collectProceduralTrees(region.getProceduralObjects(), procedural); + collectPlacements(ObjectPlacements.all(region), objects); + collectProceduralTrees(ObjectPlacements.procedural(region), procedural); } } for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { if (biome != null) { - collectPlacements(biome.getObjects(), objects); - collectProceduralTrees(biome.getProceduralObjects(), procedural); + collectPlacements(ObjectPlacements.all(biome), objects); + collectProceduralTrees(ObjectPlacements.procedural(biome), procedural); } } return new TreeObjects(objects, procedural); @@ -100,12 +102,12 @@ public final class TreeGrowing implements SaplingGrowth { /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { KList placements = new KList<>(); - boolean useAll = engine.getDimension().getTreeSettings().getMode().equals(IrisTreeModes.ALL); + boolean useAll = ObjectPlacements.treeGrowth(engine.getDimension()).mode() == TreeMode.ALL; BlockPosition at = sapling.at(); - placements.addAll(matching(engine.getBiome(at.x(), at.y(), at.z()).getObjects(), sapling.species())); + placements.addAll(matching(ObjectPlacements.all(engine.getBiome(at.x(), at.y(), at.z())), sapling.species())); if (useAll || placements.isEmpty()) { - placements.addAll(matching(engine.getRegion(at.x(), at.z()).getObjects(), sapling.species())); + placements.addAll(matching(ObjectPlacements.all(engine.getRegion(at.x(), at.z())), sapling.species())); } return placements.isNotEmpty() ? placements.getRandom() : null; } @@ -113,7 +115,7 @@ public final class TreeGrowing implements SaplingGrowth { private static KList matching(KList objects, String species) { KList matches = new KList<>(); for (IrisObjectPlacement placement : objects) { - if (placement.matches(SAPLING_SIZE, species)) { + if (placement.matches(SAPLING_WIDTH, SAPLING_DEPTH, species)) { matches.add(placement); } } @@ -139,17 +141,18 @@ public final class TreeGrowing implements SaplingGrowth { } } - private static void collectProceduralTrees(IrisProceduralObjects proceduralObjects, Set objectKeys) { + private static void collectProceduralTrees(ResolvedProceduralObjects proceduralObjects, Set objectKeys) { if (proceduralObjects == null || proceduralObjects.getTrees() == null) { return; } - for (IrisProceduralTree tree : proceduralObjects.getTrees()) { - if (tree == null || tree.getName() == null || tree.getName().isBlank()) { + for (ResolvedTree resolved : proceduralObjects.getTrees()) { + Tree tree = resolved.settings(); + if (tree.name() == null || tree.name().isBlank()) { continue; } - int variants = Math.max(1, tree.getVariants()); + int variants = Math.max(1, tree.variants()); for (int index = 0; index < variants; index++) { - objectKeys.add(tree.getVariantLoadKey(index)); + objectKeys.add(resolved.getVariantLoadKey(index)); } } } 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 index 2a7c4583c..557aa63cf 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java @@ -19,6 +19,7 @@ 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; @@ -63,7 +64,6 @@ import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import org.bukkit.Bukkit; -import org.bukkit.TreeType; import org.jetbrains.annotations.Nullable; @@ -176,8 +176,8 @@ public class IrisObjectPlacement { @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 = IrisTree.class) - private KList trees = new KList<>(); + @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") @@ -267,14 +267,10 @@ public class IrisObjectPlacement { 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 size}. */ - public boolean matches(IrisTreeSize size, String species) { - return matches(size, TreeType.valueOf(species)); - } - - public boolean matches(IrisTreeSize size, TreeType type) { - for (IrisTree i : getTrees()) { - if (i.matches(size, type)) { + /** 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; } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java deleted file mode 100644 index 5f99d7bb5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisTree.java +++ /dev/null @@ -1,83 +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.annotations.ArrayType; -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.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import org.bukkit.TreeType; - -@Snippet("tree") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Tree replace options for this object placer") -@Data -public class IrisTree { - @Required - @Desc("The types of trees overwritten by this object") - @ArrayType(min = 1, type = String.class) - private KList treeTypes = new KList<>(); - - - @Required - @Desc("The size of the square of saplings this applies to (2 means a 2 * 2 sapling area)") - @ArrayType(min = 1, type = IrisTreeSize.class) - private KList sizes = new KList<>(); - - - public boolean matches(IrisTreeSize size, TreeType type) { - if (!matchesSize(size)) { - return false; - } - - return matchesType(type); - } - - private boolean matchesSize(IrisTreeSize size) { - for (IrisTreeSize i : getSizes()) { - if ((i.getDepth() == size.getDepth() && i.getWidth() == size.getWidth()) || (i.getDepth() == size.getWidth() && i.getWidth() == size.getDepth())) { - return true; - } - } - - return false; - } - - private boolean matchesType(TreeType type) { - if (type == null) { - return false; - } - - String name = type.name(); - for (String i : getTreeTypes()) { - if (i != null && i.equalsIgnoreCase(name)) { - return true; - } - } - - return false; - } -} \ No newline at end of file diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.java deleted file mode 100644 index 31d9c026c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisTreeSize.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.object.placement; - -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("tree-size") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Sapling override object picking options") -@Data -public class IrisTreeSize { - - @Required - @Desc("The width of the sapling area") - int width = 1; - - @Required - @Desc("The depth of the sapling area") - int depth = 1; - - /** - * Does the size match - * - * @param size the size to check match - * @return true if it matches (fits within width and depth) - */ - public boolean doesMatch(IrisTreeSize size) { - return (width == size.getWidth() && depth == size.getDepth()) || (depth == size.getWidth() && width == size.getDepth()); - } -} 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 new file mode 100644 index 000000000..4296c7c08 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java @@ -0,0 +1,139 @@ +/* + * 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.ProceduralObjectSettings; +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.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.volmlib.util.collection.KList; + +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.WeakHashMap; + +/** + * The object placements and procedural objects 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 static final Map PROCEDURAL = 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; + } + + /** The procedural objects {@code owner} declares; none when it declares none. */ + public static ResolvedProceduralObjects procedural(IrisRegistrant owner) { + Optional settings = owner.getModuleSettings().find(ProceduralObjectSettings.class); + return PROCEDURAL.computeIfAbsent(settings.orElse(NO_PROCEDURAL_OBJECTS), ResolvedProceduralObjects::new); + } + + /** 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 ProceduralObjectSettings NO_PROCEDURAL_OBJECTS = new ProceduralObjectSettings(); + 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/procedural/IrisProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java deleted file mode 100644 index eb594c1d0..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralObjects.java +++ /dev/null @@ -1,112 +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.procedural; - -import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; -import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; -import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; -import art.arcane.iris.builtin.objects.crystal.Crystal; -import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; -import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.Snippet; -import art.arcane.volmlib.util.collection.KList; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; -import lombok.AllArgsConstructor; -import lombok.AccessLevel; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("procedural-objects") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") -@Data -public class IrisProceduralObjects { - @Getter(AccessLevel.NONE) - @Setter(AccessLevel.NONE) - @EqualsAndHashCode.Exclude - private final transient Map placeables = new ConcurrentHashMap<>(); - - @ArrayType(min = 1, type = IrisProceduralTree.class) - @Desc("Procedurally generated trees.") - private KList trees = new KList<>(); - - @ArrayType(min = 1, type = Ruin.class) - @Desc("Procedurally generated ruins (crumbling pillars, walls, arches, rubble).") - private KList ruins = new KList<>(); - - @ArrayType(min = 1, type = Formation.class) - @Desc("Procedurally generated natural rock formations (spires, hoodoos, arches, sea stacks, boulders, basalt columns).") - private KList formations = new KList<>(); - - @ArrayType(min = 1, type = Coral.class) - @Desc("Procedurally generated underwater coral structures.") - private KList coral = new KList<>(); - - @ArrayType(min = 1, type = Fungus.class) - @Desc("Procedurally generated mushrooms and shelf fungi.") - private KList fungi = new KList<>(); - - @ArrayType(min = 1, type = Crystal.class) - @Desc("Procedurally generated crystal clusters (usually placed in caves).") - private KList crystals = new KList<>(); - - public KList getAllPlacements() { - KList all = new KList<>(); - if (trees != null) { - all.addAll(trees); - } - addPlaceable(all, ruins, ResolvedRuin::new); - addPlaceable(all, formations, ResolvedFormation::new); - addPlaceable(all, coral, ResolvedCoral::new); - addPlaceable(all, fungi, ResolvedFungus::new); - addPlaceable(all, crystals, ResolvedCrystal::new); - return all; - } - - /** The settings in {@code settings}, each made placeable once, in order. */ - @SuppressWarnings("unchecked") - private void addPlaceable(KList all, KList settings, Function resolve) { - if (settings == null) { - return; - } - for (S entry : settings) { - all.add(placeables.computeIfAbsent(entry, key -> resolve.apply((S) key))); - } - } - - public boolean isEmpty() { - return getAllPlacements().isEmpty(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java new file mode 100644 index 000000000..e2109ace6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java @@ -0,0 +1,69 @@ +/* + * 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.procedural; + +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; +import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; +import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; +import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; +import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; +import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; +import art.arcane.volmlib.util.collection.KList; + +import java.util.List; +import java.util.function.Function; + +/** The procedural objects a region or biome declares, each made placeable once, in the order the settings list them. */ +public final class ResolvedProceduralObjects { + private final KList all = new KList<>(); + private final KList trees = new KList<>(); + + public ResolvedProceduralObjects(ProceduralObjectSettings settings) { + for (Tree tree : settings.trees()) { + ResolvedTree resolved = new ResolvedTree(tree); + trees.add(resolved); + all.add(resolved); + } + addAll(settings.ruins(), ResolvedRuin::new); + addAll(settings.formations(), ResolvedFormation::new); + addAll(settings.coral(), ResolvedCoral::new); + addAll(settings.fungi(), ResolvedFungus::new); + addAll(settings.crystals(), ResolvedCrystal::new); + } + + private void addAll(List settings, Function resolve) { + for (S entry : settings) { + all.add(resolve.apply(entry)); + } + } + + public KList getAllPlacements() { + return all; + } + + public KList getTrees() { + return trees; + } + + public boolean isEmpty() { + return all.isEmpty(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java deleted file mode 100644 index 4a88bbf4c..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/IrisTreeSettings.java +++ /dev/null @@ -1,45 +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.procedural.tree; - -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.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Snippet("tree-settings") -@Accessors(chain = true) -@AllArgsConstructor -@NoArgsConstructor -@Desc("Tree growth override settings") -@Data -@EqualsAndHashCode(callSuper = false) -public class IrisTreeSettings { - - @Required - @Desc("Turn replacing on and off") - boolean enabled = false; - - @Desc("Object picking modes") - IrisTreeModes mode = IrisTreeModes.FIRST; -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java index 87ac0bcdd..860f30d52 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; @@ -36,13 +36,13 @@ public final class ProceduralTreeGenerator { private ProceduralTreeGenerator() { } - public static IrisObject generate(IrisProceduralTree tree, int height, RNG rng, IrisData data) { + public static IrisObject generate(Tree tree, int height, RNG rng, IrisData data) { TreeBlockCanvas canvas = new TreeBlockCanvas(); long baseSeed = rng.getSeed(); List limbs = TreeTrunkBuilder.build(canvas, tree, height); - boolean wantEndpoints = tree.getDecorators() != null && !tree.getDecorators().isEmpty(); + boolean wantEndpoints = tree.decorators() != null && !tree.decorators().isEmpty(); List branchEndpoints = wantEndpoints ? new ArrayList<>() : null; int limbIndex = 0; @@ -55,11 +55,11 @@ public final class ProceduralTreeGenerator { TreeDecoratorApplier.apply(canvas, tree, baseSeed, branchEndpoints); } - if (tree.isRoots()) { + if (tree.roots()) { TreeRootBuilder.build(canvas, tree, height, baseSeed); } - if (tree.isPlausible()) { + if (tree.plausible()) { TreeSupport.ensureLeavesSupported(canvas, 24); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java new file mode 100644 index 000000000..5bf0f7742 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -0,0 +1,120 @@ +/* + * 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.procedural.tree; + +import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; + +import java.io.File; + +/** A procedural tree made placeable: its variants are baked by {@link ProceduralTreeGenerator}, at heights spread between its limits. */ +public final class ResolvedTree extends ResolvedProceduralPlacement { + private static final long VARIANT_SEED_STRIDE = 7919L; + private static final double HEIGHT_JITTER_FRACTION = 0.3; + private static final int MINIMUM_HEIGHT = 2; + + private final Tree settings; + + public ResolvedTree(Tree settings) { + super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), + settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + this.settings = settings; + } + + /** The key a variant is loaded under, which placement markers and the sapling tree list name. */ + public static String variantLoadKey(String name, int index) { + if (index < 0) { + throw new IllegalArgumentException("index must not be negative"); + } + return "procedural/tree/" + name + "#" + index; + } + + public String getVariantLoadKey(int index) { + return variantLoadKey(settings.name(), index); + } + + public Tree settings() { + return settings; + } + + @Override + public boolean isPlausible() { + return settings.plausible(); + } + + @Override + protected IrisObject generate(int index, RNG rng, IrisData data) { + throw new UnsupportedOperationException("Tree variants are baked with heights spread over the limits"); + } + + @Override + protected KList bake(IrisData data) { + KList baked = new KList<>(); + int count = Math.max(1, settings.variants()); + int lo = Math.min(settings.heightMin(), settings.heightMax()); + int hi = Math.max(settings.heightMin(), settings.heightMax()); + RNG heightRng = new RNG(settings.seed()); + + for (int i = 0; i < count; i++) { + int height = variantHeight(heightRng, lo, hi, count, i); + IrisObject object = ProceduralTreeGenerator.generate(settings, Math.max(MINIMUM_HEIGHT, height), + new RNG(settings.seed() + (i * VARIANT_SEED_STRIDE)), data); + if (object == null || object.getBlocks().isEmpty()) { + continue; + } + object.setLoadKey(getVariantLoadKey(i)); + object.setLoader(data); + baked.add(object); + } + + digestForGoldenDebug(baked); + return baked; + } + + private static int variantHeight(RNG heightRng, int lo, int hi, int count, int index) { + if (count == 1 || lo == hi) { + return heightRng.i(lo, hi + 1); + } + double step = (hi - lo) / (double) (count - 1); + double base = lo + step * index; + double jitter = heightRng.d(-step * HEIGHT_JITTER_FRACTION, step * HEIGHT_JITTER_FRACTION); + return (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); + } + + private static void digestForGoldenDebug(KList baked) { + if (!new File("plugins/Iris/goldendebug.txt").isFile()) { + return; + } + for (IrisObject object : baked) { + long[] digest = new long[]{0L}; + object.getBlocks().forEach((vector, state) -> { + long position = ((long) vector.getBlockX() << 40) ^ ((long) vector.getBlockY() << 20) ^ vector.getBlockZ(); + digest[0] ^= Long.rotateLeft(position * 0x9E3779B97F4A7C15L ^ state.key().hashCode(), (int) (position & 63)); + }); + IrisLogging.debug("Goldendebug bake: " + object.getLoadKey() + " blocks=" + object.getBlocks().size() + " digest=" + Long.toHexString(digest[0])); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java index 037695c7a..9fdcfa109 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java @@ -21,10 +21,9 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; import art.arcane.iris.builtin.objects.tree.TreeDecorator; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; import com.volmit.block.PaletteSpec; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.math.RNG; @@ -33,38 +32,38 @@ public final class TreeBlockResolver { private TreeBlockResolver() { } - public static PlatformBlockState resolve(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Cell cell, TreeBlockCanvas.Vec pos) { - RNG paletteRng = new RNG(tree.getSeed()); - RNG posRng = new RNG(tree.getSeed() ^ positionHash(pos)); + public static PlatformBlockState resolve(Tree tree, IrisData data, TreeBlockCanvas.Cell cell, TreeBlockCanvas.Vec pos) { + RNG paletteRng = new RNG(tree.seed()); + RNG posRng = new RNG(tree.seed() ^ positionHash(pos)); switch (cell.role()) { case TRUNK -> { - PlatformBlockState state = resolveBlock(tree.getTrunk(), tree.getTrunkPalette(), data, pos, paletteRng); + PlatformBlockState state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), data, pos, paletteRng); return finishTrunk(state, cell); } case SECONDARY_TRUNK -> { - PlatformBlockState state = resolveBlock(tree.getSecondaryTrunk(), tree.getSecondaryTrunkPalette(), data, pos, paletteRng); + PlatformBlockState state = resolveBlock(tree.secondaryTrunk().orElse(null), tree.secondaryTrunkPalette().orElse(null), data, pos, paletteRng); if (state == null) { - state = resolveBlock(tree.getTrunk(), tree.getTrunkPalette(), data, pos, paletteRng); + state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), data, pos, paletteRng); } return finishTrunk(state, cell); } case LEAF -> { - return resolveBlock(tree.getLeaves(), tree.getLeavesPalette(), data, pos, paletteRng); + return resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), data, pos, paletteRng); } case SECONDARY_LEAF -> { PlatformBlockState state = resolveSecondaryLeaf(tree, data, pos, paletteRng, posRng); if (state == null) { - state = resolveBlock(tree.getLeaves(), tree.getLeavesPalette(), data, pos, paletteRng); + state = resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), data, pos, paletteRng); } return state; } case DECORATOR -> { int index = cell.decoratorIndex(); - if (index < 0 || tree.getDecorators() == null || index >= tree.getDecorators().size()) { + if (index < 0 || tree.decorators() == null || index >= tree.decorators().size()) { return null; } - TreeDecorator dec = tree.getDecorators().get(index); + TreeDecorator dec = tree.decorators().get(index); PlatformBlockState state = resolveBlock(dec.block(), dec.palette().orElse(null), data, pos, paletteRng); if (state != null && cell.facing() != null && IrisProceduralBlocks.hasProperty(state, "facing")) { try { @@ -96,23 +95,24 @@ public final class TreeBlockResolver { return state; } - private static PlatformBlockState resolveSecondaryLeaf(IrisProceduralTree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng, RNG posRng) { - if (TreeTrunkBuilder.paletteSet(tree.getSecondaryLeavesPalette())) { - return tree.getSecondaryLeavesPalette().get(paletteRng, pos.x(), pos.y(), pos.z(), data); + private static PlatformBlockState resolveSecondaryLeaf(Tree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng, RNG posRng) { + PaletteSpec secondaryPalette = tree.secondaryLeavesPalette().orElse(null); + if (IrisProceduralBlocks.paletteSet(secondaryPalette)) { + return IrisProceduralBlocks.pick(secondaryPalette, data, paletteRng.getSeed(), pos.x(), pos.y(), pos.z()); } - if (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) { + if (tree.weightedSecondaryLeaves() != null && !tree.weightedSecondaryLeaves().isEmpty()) { String picked = pickWeighted(tree, posRng); return picked == null ? null : B.getStateOrNull(picked, false); } - if (tree.getSecondaryLeaves() != null && !tree.getSecondaryLeaves().isEmpty()) { - return B.getStateOrNull(tree.getSecondaryLeaves(), false); + if (tree.secondaryLeaves().isPresent() && !tree.secondaryLeaves().get().isEmpty()) { + return B.getStateOrNull(tree.secondaryLeaves().get(), false); } return null; } - private static String pickWeighted(IrisProceduralTree tree, RNG rng) { + private static String pickWeighted(Tree tree, RNG rng) { int total = 0; - for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { + for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { total += Math.max(0, s.weight()); } if (total <= 0) { @@ -120,29 +120,19 @@ public final class TreeBlockResolver { } double r = rng.nextDouble() * total; double cumulative = 0; - for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.getWeightedSecondaryLeaves()) { + for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { cumulative += Math.max(0, s.weight()); if (r < cumulative) { return s.block(); } } - return tree.getWeightedSecondaryLeaves().get(tree.getWeightedSecondaryLeaves().size() - 1).block(); + return tree.weightedSecondaryLeaves().get(tree.weightedSecondaryLeaves().size() - 1).block(); } private static PlatformBlockState resolveBlock(String block, PaletteSpec palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { return IrisProceduralBlocks.resolve(block, palette, data, pos.x(), pos.y(), pos.z(), paletteRng); } - private static PlatformBlockState resolveBlock(String block, IrisMaterialPalette palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { - if (TreeTrunkBuilder.paletteSet(palette)) { - return palette.get(paletteRng, pos.x(), pos.y(), pos.z(), data); - } - if (block != null && !block.isEmpty()) { - return B.getStateOrNull(block, false); - } - return null; - } - private static PlatformBlockState woodCap(PlatformBlockState state) { String key = state.key(); int bracket = key.indexOf('['); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java index 6c3bd3e7b..37a9cc223 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java @@ -24,7 +24,8 @@ import art.arcane.iris.builtin.objects.tree.TreeCanopy; import art.arcane.iris.builtin.objects.tree.TreeBranches; import art.arcane.iris.builtin.objects.tree.TreeProfile; import art.arcane.iris.builtin.objects.tree.TreeLeafMode; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; @@ -34,15 +35,15 @@ public final class TreeCanopyBuilder { private TreeCanopyBuilder() { } - public static void build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, double[][] offsets, + public static void build(TreeBlockCanvas canvas, Tree tree, int height, double[][] offsets, int branchStartY, long baseSeed, List branchEndpoints) { - TreeCanopy canopy = tree.getCanopy(); + TreeCanopy canopy = tree.canopy(); if (canopy == null) { canopy = new TreeCanopy(); } TreeBranches branches = canopy.branches().orElse(null); - double[][] layers = resolveLayers(canopy, tree.getProfile(), height, branches != null); + double[][] layers = resolveLayers(canopy, tree.profile(), height, branches != null); if (branches != null) { if (layers.length > 0) { @@ -56,7 +57,7 @@ public final class TreeCanopyBuilder { } } - private static void placeApexCap(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, double[][] layers, + private static void placeApexCap(TreeBlockCanvas canvas, Tree tree, int height, double[][] layers, double[][] offsets, long baseSeed) { int ocx = 0; int ocz = 0; @@ -69,7 +70,7 @@ public final class TreeCanopyBuilder { maxR = Math.max(maxR, layer[1]); } int capRadius = Math.max(2, Math.min(3, (int) Math.round(maxR * 0.35))); - TreeCanopy canopy = tree.getCanopy(); + TreeCanopy canopy = tree.canopy(); TreeLeafMode mode = canopy != null ? canopy.mode() : TreeLeafMode.TRIMMED; double density = canopy != null ? canopy.leafDensity() : 1.0; placeLeafCluster(canvas, tree, ocx, height - 1, ocz, capRadius, mode, density, baseSeed + 5555L); @@ -88,7 +89,7 @@ public final class TreeCanopyBuilder { return TreeProfiles.presetLayers(profile, height, branchDriven); } - private static void volumeCanopy(TreeBlockCanvas canvas, IrisProceduralTree tree, double[][] layers, + private static void volumeCanopy(TreeBlockCanvas canvas, Tree tree, double[][] layers, TreeCanopy canopy, long baseSeed, double[][] offsets) { int ocx = 0; int ocz = 0; @@ -136,7 +137,7 @@ public final class TreeCanopyBuilder { return (int) Math.ceil(radius * squish); } - private static void placeLeafDisc(TreeBlockCanvas canvas, IrisProceduralTree tree, int cx, int cy, int cz, + private static void placeLeafDisc(TreeBlockCanvas canvas, Tree tree, int cx, int cy, int cz, double radius, TreeLeafMode mode, double density, long seed) { double sx = stretchX(tree); double sz = stretchZ(tree); @@ -157,7 +158,7 @@ public final class TreeCanopyBuilder { } } - private static void placeLeafCluster(TreeBlockCanvas canvas, IrisProceduralTree tree, int cx, int cy, int cz, + private static void placeLeafCluster(TreeBlockCanvas canvas, Tree tree, int cx, int cy, int cz, int radius, TreeLeafMode mode, double density, long seed) { double sx = stretchX(tree); double sz = stretchZ(tree); @@ -180,13 +181,13 @@ public final class TreeCanopyBuilder { } } - private static double stretchX(IrisProceduralTree tree) { - TreeCanopy c = tree.getCanopy(); + private static double stretchX(Tree tree) { + TreeCanopy c = tree.canopy(); return c == null ? 1.0 : Math.max(0.1, c.crownStretchX()); } - private static double stretchZ(IrisProceduralTree tree) { - TreeCanopy c = tree.getCanopy(); + private static double stretchZ(Tree tree) { + TreeCanopy c = tree.canopy(); return c == null ? 1.0 : Math.max(0.1, c.crownStretchZ()); } @@ -244,20 +245,20 @@ public final class TreeCanopyBuilder { } } - private static TreeBlockCanvas.Role resolveLeaf(IrisProceduralTree tree, RNG rng) { - boolean hasSecondary = TreeTrunkBuilder.paletteSet(tree.getSecondaryLeavesPalette()) - || (tree.getWeightedSecondaryLeaves() != null && !tree.getWeightedSecondaryLeaves().isEmpty()) - || (tree.getSecondaryLeaves() != null && !tree.getSecondaryLeaves().isEmpty()); - if (!hasSecondary || tree.getSecondaryLeafFraction() <= 0.0) { + private static TreeBlockCanvas.Role resolveLeaf(Tree tree, RNG rng) { + boolean hasSecondary = IrisProceduralBlocks.paletteSet(tree.secondaryLeavesPalette()) + || (tree.weightedSecondaryLeaves() != null && !tree.weightedSecondaryLeaves().isEmpty()) + || tree.secondaryLeaves().filter(leaves -> !leaves.isEmpty()).isPresent(); + if (!hasSecondary || tree.secondaryLeafFraction() <= 0.0) { return TreeBlockCanvas.Role.LEAF; } - if (rng.nextDouble() >= tree.getSecondaryLeafFraction()) { + if (rng.nextDouble() >= tree.secondaryLeafFraction()) { return TreeBlockCanvas.Role.LEAF; } return TreeBlockCanvas.Role.SECONDARY_LEAF; } - private static void branchCanopy(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, + private static void branchCanopy(TreeBlockCanvas canvas, Tree tree, int height, TreeBranches branches, int branchStartY, long baseSeed, double[][] offsets, List branchEndpoints) { long branchSeed = baseSeed + 9999; @@ -297,7 +298,7 @@ public final class TreeCanopyBuilder { } } - private static void growSubBranches(TreeBlockCanvas canvas, IrisProceduralTree tree, int ox, int oy, int oz, + private static void growSubBranches(TreeBlockCanvas canvas, Tree tree, int ox, int oy, int oz, double az, double el, double len, TreeSubBranches sub, int depth, long seed) { if (sub == null || depth <= 0) { return; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java index 4784e81ac..c014ec309 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeDecorator; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.math.RNG; @@ -31,8 +31,8 @@ public final class TreeDecoratorApplier { private TreeDecoratorApplier() { } - public static void apply(TreeBlockCanvas canvas, IrisProceduralTree tree, long baseSeed, List branchEndpoints) { - KList decorators = tree.getDecorators(); + public static void apply(TreeBlockCanvas canvas, Tree tree, long baseSeed, List branchEndpoints) { + List decorators = tree.decorators(); if (decorators == null || decorators.isEmpty()) { return; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java index 8583584fd..0ab4640a9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeBranches; import art.arcane.iris.builtin.objects.tree.TreeFunction; import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; public final class TreeFunctions { @@ -30,27 +30,27 @@ public final class TreeFunctions { private TreeFunctions() { } - public static double trunkWidthMultiplier(IrisProceduralTree tree, double t) { - double start = tree.getShapeStart(); - double end = tree.getShapeEnd(); - return switch (tree.getTrunkShape()) { + public static double trunkWidthMultiplier(Tree tree, double t) { + double start = tree.shapeStart(); + double end = tree.shapeEnd(); + return switch (tree.trunkShape()) { case CONSTANT -> 1.0; case LINEAR -> start + (end - start) * t; - case SIGMOID -> 1.0 / (1.0 + Math.exp(tree.getShapeSteepness() * (t - 0.5))); + case SIGMOID -> 1.0 / (1.0 + Math.exp(tree.shapeSteepness() * (t - 0.5))); case LOG -> { - double base = Math.max(1.0001, tree.getShapeBase()); + double base = Math.max(1.0001, tree.shapeBase()); if (t <= 0.0) { yield 1.0; } yield Math.max(0.0, 1.0 - Math.log(1.0 + t * (base - 1.0)) / Math.log(base)); } case SINE -> { - double period = tree.getShapePeriod() == 0 ? 1.0 : tree.getShapePeriod(); - yield 1.0 + tree.getShapeAmplitude() * Math.sin(2.0 * Math.PI * t / period); + double period = tree.shapePeriod() == 0 ? 1.0 : tree.shapePeriod(); + yield 1.0 + tree.shapeAmplitude() * Math.sin(2.0 * Math.PI * t / period); } case PARABOLIC -> { - double peak = tree.getShapePeakOffset(); - double floor = tree.getShapeFloor(); + double peak = tree.shapePeakOffset(); + double floor = tree.shapeFloor(); double denom = Math.pow(Math.max(peak, 1.0 - peak), 2); if (denom == 0) { denom = 1; @@ -59,7 +59,7 @@ public final class TreeFunctions { } case EXPONENTIAL -> geometric(start, end, t); case SQRT -> start + (end - start) * Math.sqrt(t); - case STEP -> t < tree.getShapePeakOffset() ? start : end; + case STEP -> t < tree.shapePeakOffset() ? start : end; case BELL -> start + (end - start) * bell(t); case EASE_IN_OUT -> start + (end - start) * smoothstep(t); }; @@ -114,24 +114,24 @@ public final class TreeFunctions { }; } - public static double azimuthDegrees(TreeAzimuthMode mode, double t, int index, IrisProceduralTree tree, double constantBase, RNG rng) { + public static double azimuthDegrees(TreeAzimuthMode mode, double t, int index, Tree tree, double constantBase, RNG rng) { return switch (mode) { case CONSTANT -> constantBase; - case LINEAR -> tree.getAzimuthStart() + (tree.getAzimuthEnd() - tree.getAzimuthStart()) * t; - case SPIRAL -> tree.getAzimuthStart() + tree.getAzimuthTurns() * 360.0 * t; + case LINEAR -> tree.azimuthStart() + (tree.azimuthEnd() - tree.azimuthStart()) * t; + case SPIRAL -> tree.azimuthStart() + tree.azimuthTurns() * 360.0 * t; case SINE -> { - double period = tree.getAzimuthPeriod() == 0 ? 1.0 : tree.getAzimuthPeriod(); - yield tree.getAzimuthOffset() + tree.getAzimuthAmplitude() * Math.sin(2.0 * Math.PI * t / period); + double period = tree.azimuthPeriod() == 0 ? 1.0 : tree.azimuthPeriod(); + yield tree.azimuthOffset() + tree.azimuthAmplitude() * Math.sin(2.0 * Math.PI * t / period); } - case NOISE -> noiseAzimuth(t, tree.getAzimuthScale(), tree.getSeed()); + case NOISE -> noiseAzimuth(t, tree.azimuthScale(), tree.seed()); case RANDOM -> rng != null ? rng.d(0.0, 360.0) : constantBase; case GOLDEN_ANGLE -> index >= 0 ? constantBase + index * GOLDEN_ANGLE : constantBase; case ALTERNATING -> index >= 0 ? constantBase + (index % 2) * 180.0 : constantBase; case WHORL -> { - int count = Math.max(1, tree.getAzimuthWhorlCount()); + int count = Math.max(1, tree.azimuthWhorlCount()); yield index >= 0 ? constantBase + (index % count) * (360.0 / count) : constantBase; } - case ZIGZAG -> index >= 0 ? constantBase + ((index % 2 == 0) ? -tree.getAzimuthAmplitude() : tree.getAzimuthAmplitude()) : constantBase; + case ZIGZAG -> index >= 0 ? constantBase + ((index % 2 == 0) ? -tree.azimuthAmplitude() : tree.azimuthAmplitude()) : constantBase; }; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java index ab62bab58..e62b28499 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.spi.PlatformBlockState; import java.util.ArrayDeque; @@ -38,7 +38,7 @@ public final class TreePlausibility { } public static void apply(Map resolved, Set trunkPositions, - Set leafPositions, IrisProceduralTree tree) { + Set leafPositions, Tree tree) { Set realLeaves = new HashSet<>(); for (TreeBlockCanvas.Vec v : leafPositions) { PlatformBlockState state = resolved.get(v); @@ -55,7 +55,7 @@ public final class TreePlausibility { for (TreeBlockCanvas.Vec v : realLeaves) { PlatformBlockState leaf = resolved.get(v); Integer d = distance.get(v); - if (!tree.isPlausible()) { + if (!tree.plausible()) { leaf = leaf.withProperty("persistent", "true").withProperty("distance", "1"); } else if (d != null && d < MAX_DISTANCE) { leaf = leaf.withProperty("persistent", "false").withProperty("distance", String.valueOf(Math.max(1, d))); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java index 2a296b30a..a20e80dfb 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeRootStyle; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; @@ -29,7 +29,7 @@ public final class TreeRootBuilder { private TreeRootBuilder() { } - public static void build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height, long baseSeed) { + public static void build(TreeBlockCanvas canvas, Tree tree, int height, long baseSeed) { List cells = new ArrayList<>(); for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { if (v.y() == 0) { @@ -40,7 +40,7 @@ public final class TreeRootBuilder { return; } - int depth = tree.getRootDepth() > 0 ? tree.getRootDepth() : autoDepth(height); + int depth = tree.rootDepth() > 0 ? tree.rootDepth() : autoDepth(height); RNG rng = new RNG(baseSeed ^ 0x5009L); double cx = 0; @@ -56,9 +56,9 @@ public final class TreeRootBuilder { for (int[] c : cells) { baseRadius = Math.max(baseRadius, Math.hypot(c[0] - cx, c[1] - cz) + 0.5); } - double flare = tree.getRootFlare() > 0 ? tree.getRootFlare() : baseRadius + Math.max(2.0, depth * 0.6); + double flare = tree.rootFlare() > 0 ? tree.rootFlare() : baseRadius + Math.max(2.0, depth * 0.6); - TreeRootStyle style = tree.getRootStyle(); + TreeRootStyle style = tree.rootStyle(); switch (style) { case TAPROOT -> taproot(canvas, cells, cx, cz, baseRadius, depth); case BUTTRESS -> { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java index 25e26b971..29b2462b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java @@ -19,8 +19,8 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; -import art.arcane.iris.engine.object.procedural.tree.IrisProceduralTree; +import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.builtin.objects.tree.Tree; import java.util.ArrayList; import java.util.List; @@ -32,10 +32,10 @@ public final class TreeTrunkBuilder { private TreeTrunkBuilder() { } - public static List build(TreeBlockCanvas canvas, IrisProceduralTree tree, int height) { + public static List build(TreeBlockCanvas canvas, Tree tree, int height) { boolean hasSecondary = hasSecondaryTrunk(tree); double[][] mainOffsets = leanPath(tree, height); - int forks = Math.max(1, tree.getTrunkForks()); + int forks = Math.max(1, tree.trunkForks()); List limbs = new ArrayList<>(); if (forks == 1) { @@ -45,12 +45,12 @@ public final class TreeTrunkBuilder { return limbs; } - int forkY = Math.max(1, Math.min(height - 2, (int) Math.round(tree.getForkHeight() * (height - 1)))); + int forkY = Math.max(1, Math.min(height - 2, (int) Math.round(tree.forkHeight() * (height - 1)))); placeColumn(canvas, tree, mainOffsets, height, 0, forkY, hasSecondary); double baseCx = mainOffsets[forkY][0]; double baseCz = mainOffsets[forkY][1]; - double reachMax = (height - forkY) * Math.tan(Math.toRadians(tree.getForkAngle())); + double reachMax = (height - forkY) * Math.tan(Math.toRadians(tree.forkAngle())); for (int f = 0; f < forks; f++) { double az = Math.toRadians((360.0 / forks) * f); @@ -73,7 +73,7 @@ public final class TreeTrunkBuilder { return limbs; } - private static double[][] leanPath(IrisProceduralTree tree, int height) { + private static double[][] leanPath(Tree tree, int height) { double[][] offsets = new double[height][2]; for (int y = 0; y < height; y++) { double[] lean = leanOffset(tree, y, height); @@ -83,7 +83,7 @@ public final class TreeTrunkBuilder { return offsets; } - private static void placeColumn(TreeBlockCanvas canvas, IrisProceduralTree tree, double[][] offsets, int height, + private static void placeColumn(TreeBlockCanvas canvas, Tree tree, double[][] offsets, int height, int yStart, int yEnd, boolean hasSecondary) { double prevCx = yStart > 0 ? offsets[yStart - 1][0] : 0.0; double prevCz = yStart > 0 ? offsets[yStart - 1][1] : 0.0; @@ -128,45 +128,41 @@ public final class TreeTrunkBuilder { } } - private static int widthAt(IrisProceduralTree tree, int y, int height) { + private static int widthAt(Tree tree, int y, int height) { double t = y / (double) Math.max(height - 1, 1); double multiplier = TreeFunctions.trunkWidthMultiplier(tree, t); - return Math.max(1, (int) Math.round(tree.getTrunkWidth() * multiplier)); + return Math.max(1, (int) Math.round(tree.trunkWidth() * multiplier)); } - private static TreeBlockCanvas.Role trunkRole(IrisProceduralTree tree, boolean hasSecondary, int y, int height) { + private static TreeBlockCanvas.Role trunkRole(Tree tree, boolean hasSecondary, int y, int height) { if (!hasSecondary) { return TreeBlockCanvas.Role.TRUNK; } double t = y / (double) Math.max(height - 1, 1); - if (tree.getSecondaryTrunkStart() <= t && t <= tree.getSecondaryTrunkEnd()) { + if (tree.secondaryTrunkStart() <= t && t <= tree.secondaryTrunkEnd()) { return TreeBlockCanvas.Role.SECONDARY_TRUNK; } return TreeBlockCanvas.Role.TRUNK; } - private static boolean hasSecondaryTrunk(IrisProceduralTree tree) { - if (paletteSet(tree.getSecondaryTrunkPalette())) { + private static boolean hasSecondaryTrunk(Tree tree) { + if (IrisProceduralBlocks.paletteSet(tree.secondaryTrunkPalette())) { return true; } - return tree.getSecondaryTrunk() != null && !tree.getSecondaryTrunk().isEmpty(); + return tree.secondaryTrunk().filter(trunk -> !trunk.isEmpty()).isPresent(); } - static boolean paletteSet(IrisMaterialPalette palette) { - return palette != null && palette.getPalette() != null && !palette.getPalette().isEmpty(); - } - - private static double[] leanOffset(IrisProceduralTree tree, int y, int height) { - if (tree.getLeanAngle() == 0.0 || height <= 1) { + private static double[] leanOffset(Tree tree, int y, int height) { + if (tree.leanAngle() == 0.0 || height <= 1) { return new double[]{0.0, 0.0}; } double t = y / (double) Math.max(height - 1, 1); - double progress = TreeFunctions.curveProgress(tree.getTrunkCurve(), t, tree.getCurveSteepness()); - double maxReach = height * Math.tan(Math.toRadians(tree.getLeanAngle())); + double progress = TreeFunctions.curveProgress(tree.trunkCurve(), t, tree.curveSteepness()); + double maxReach = height * Math.tan(Math.toRadians(tree.leanAngle())); double reach = maxReach * progress; - double azDeg = tree.getLeanAzimuthMode() == TreeAzimuthMode.CONSTANT - ? tree.getLeanAzimuth() - : TreeFunctions.azimuthDegrees(tree.getLeanAzimuthMode(), t, -1, tree, tree.getLeanAzimuth(), null); + double azDeg = tree.leanAzimuthMode() == TreeAzimuthMode.CONSTANT + ? tree.leanAzimuth() + : TreeFunctions.azimuthDegrees(tree.leanAzimuthMode(), t, -1, tree, tree.leanAzimuth(), null); double azRad = Math.toRadians(azDeg); double dx = reach * Math.sin(azRad); double dz = reach * Math.cos(azRad); diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index f92556cd0..8f4551ccb 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.terrain.floating; +import art.arcane.iris.engine.object.placement.ObjectPlacements; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.core.loader.IrisData; @@ -171,7 +172,7 @@ public final class ResolvedFloatingChild implements IRare { } public KList resolveTopObjects(IrisBiome target) { - KList surfaceObjects = (settings.inheritObjects() && target != null) ? target.getSurfaceObjects() : new KList<>(); + KList surfaceObjects = (settings.inheritObjects() && target != null) ? ObjectPlacements.surface(target) : new KList<>(); return resolveTopObjectsFromSurface(surfaceObjects); } 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 index 659bec501..deca571f8 100644 --- 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 @@ -20,8 +20,6 @@ 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.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; @@ -80,8 +78,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { 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> surfaceObjectsCache = new AtomicCache<>(); - private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(); private final transient AtomicCache cacheColor = new AtomicCache<>(); private final transient AtomicCache cacheColorObjectDensity = new AtomicCache<>(); private final transient AtomicCache cacheColorDecoratorLoad = new AtomicCache<>(); @@ -141,11 +137,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { @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 = IrisObjectPlacement.class) - @Desc("Objects define what schematics (iob files) iris will place in this biome") - private KList objects = new KList<>(); - @Desc("Procedural objects (such as trees) iris generates from scratch and places in this biome, instead of loading them from iob files") - private IrisProceduralObjects proceduralObjects = new IrisProceduralObjects(); @ArrayType(min = 1, type = IrisStructurePlacement.class) @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this biome") private KList structures = new KList<>(); @@ -264,36 +255,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { return IrisBiomeGenLinks.getGenLink(this, loadKey); } - public KList getSurfaceObjects() { - return getSurfaceObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for (IrisObjectPlacement i : o.copy()) { - if (!i.getCarvingSupport().supportsSurface()) { - o.remove(i); - } - } - - return o; - }); - } - - public KList getCarvingObjects() { - return getCarveObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for (IrisObjectPlacement i : o.copy()) { - if (!i.getCarvingSupport().supportsCarving()) { - o.remove(i); - } - } - - return o; - }); - } - public double getHeight(Engine xg, double x, double z, long seed) { double height = 0; 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 index a8882ca8d..4c7264e3d 100644 --- 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 @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.world.biome; +import art.arcane.iris.engine.object.placement.ObjectPlacements; import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.terrain.BiomeLayers; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; @@ -68,7 +69,7 @@ final class IrisBiomeColorRenderer { return biome.getCacheColorObjectDensity().aquire(() -> { double density = 0; - for (IrisObjectPlacement i : biome.getObjects()) { + for (IrisObjectPlacement i : ObjectPlacements.all(biome)) { density += i.getDensity() * i.getChance(); } 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 index 327edb132..97696102a 100644 --- 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 @@ -25,7 +25,6 @@ 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.procedural.tree.IrisTreeSettings; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.value.IrisRange; @@ -123,8 +122,6 @@ public class IrisDimension extends IrisRegistrant { @MaxNumber(16) @Desc("Every X/Z % debugCrossSectionsMod == 0 cuts the chunk") private int debugCrossSectionsMod = 3; - @Desc("Tree growth override settings") - private IrisTreeSettings treeSettings = new IrisTreeSettings(); @MinNumber(0) @Desc("The version of this dimension. Changing this will stop users from accidentally upgrading (and breaking their worlds).") private int version = 1; @@ -150,12 +147,6 @@ public class IrisDimension extends IrisRegistrant { private boolean debugSmartBore = false; @Desc("Generate decorations or not") private boolean decorate = true; - @Desc("Refuse to place surface objects and trees over carved surface openings.") - private boolean requireObjectSurfaceSupport = true; - @MinNumber(0) - @MaxNumber(16) - @Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") - private int objectSurfaceSupportBuffer = 2; @Desc("The world environment") private IrisEnvironment environment = IrisEnvironment.NORMAL; @RegistryListResource(IrisRegion.class) @@ -188,10 +179,6 @@ public class IrisDimension extends IrisRegistrant { private int upperDimensionGap = 32; @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") private boolean upperDimensionCarving = false; - @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") - private boolean upperDimensionObjects = false; - @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") - private boolean upperObjectsForcePlace = false; @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 = ""; 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 index e57c3b9f9..a298509e7 100644 --- 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 @@ -18,8 +18,6 @@ package art.arcane.iris.engine.object.world.region; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.InferredType; @@ -58,8 +56,6 @@ import java.util.Random; @Data @EqualsAndHashCode(callSuper = false) public class IrisRegion extends IrisRegistrant implements IRare { - private final transient AtomicCache> surfaceObjectsCache = new AtomicCache<>(); - private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(); private final transient AtomicCache> cacheRidge = new AtomicCache<>(); private final transient AtomicCache> cacheSpot = new AtomicCache<>(); private final transient AtomicCache shoreHeightGenerator = new AtomicCache<>(); @@ -76,11 +72,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { @MaxNumber(128) @Desc("The rarity of the region") private int rarity = 1; - @ArrayType(min = 1, type = IrisObjectPlacement.class) - @Desc("Objects define what schematics (iob files) iris will place in this region") - private KList objects = new KList<>(); - @Desc("Procedural objects (trees, ruins, formations, coral, fungi, crystals) iris generates from scratch and places across this region") - private IrisProceduralObjects proceduralObjects = new IrisProceduralObjects(); @ArrayType(min = 1, type = IrisStructurePlacement.class) @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this region") private KList structures = new KList<>(); @@ -129,36 +120,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { return name; } - public KList getSurfaceObjects() { - return getSurfaceObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for (IrisObjectPlacement i : o.copy()) { - if (!i.getCarvingSupport().supportsSurface()) { - o.remove(i); - } - } - - return o; - }); - } - - public KList getCarvingObjects() { - return getCarveObjectsCache().aquire(() -> - { - KList o = getObjects().copy(); - - for (IrisObjectPlacement i : o.copy()) { - if (!i.getCarvingSupport().supportsCarving()) { - o.remove(i); - } - } - - return o; - }); - } - public CNG getShoreHeightGenerator() { return shoreHeightGenerator.aquire(() -> CNG.signature(new RNG((long) (getName().length() + getLandBiomeZoom() + getLandBiomes().size() + 3458612)))); From ef893e0ebf0067663a4afa67ca378289073a6233 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:09:14 +0200 Subject: [PATCH 076/139] The object placement stages move into the built-ins jar iris:prepare, anchor, validate, bore, blocks, stilt, vacuum and snow read the placement through the ObjectPlacement facade of art.arcane.iris.builtin.placement (object size, settings, terrain questions, surface warp, the block operations only the platform can do) and through IrisApi block states and traits, so they pass the jar check. PreparedPlacement, ObjectSpinKernel and TransformedBounds move into the exposed prepare package, and IrisStages' SLOPE output is an ObjectRotation and TRANSFORMS a PreparedPlacement. PlacementModules.all() goes. --- README.md | 22 ++- builtin-modules.txt | 17 +- .../art/arcane/iris/builtin/IrisStages.java | 8 +- .../art/arcane/iris/builtin/package-info.java | 7 +- .../iris/builtin/placement/BlockTraits.java | 59 +++++++ .../iris/builtin/placement/CaveSpace.java | 23 +++ .../iris/builtin/placement/MarkerRule.java | 37 ++++ .../builtin/placement/ObjectPlacement.java | 105 ++++++++++++ .../iris/builtin/placement/ObjectShape.java | 45 +++++ .../builtin/placement/PlacementBinding.java | 40 +++++ .../builtin/placement/PlacementSettings.java | 92 ++++++++++ .../builtin/placement/PlacementTerrain.java | 72 ++++++++ .../iris/builtin/placement/PlaneNoise.java | 24 +++ .../builtin/placement/StructureVolumes.java | 30 ++++ .../iris/builtin/placement/SurfaceWarp.java | 28 ++++ .../iris/builtin/prepare/ObjectRotation.java | 34 ++++ .../prepare}/ObjectSpinKernel.java | 44 ++--- .../iris/builtin/prepare/ObjectTranslate.java | 14 ++ .../prepare}/PreparedPlacement.java | 95 +++++++---- .../prepare}/TransformedBounds.java | 4 +- .../engine/object/placement/AnchorModule.java | 67 ++++---- .../engine/object/placement/BlocksModule.java | 158 +++++++++--------- .../engine/object/placement/BoreModule.java | 20 ++- .../object/placement/IrisSurfaceSupport.java | 70 ++++---- .../engine/object/placement/ObjectEdits.java | 54 +++--- .../object/placement/PlacementModules.java | 13 +- .../object/placement/PlacementWorld.java | 40 +++-- .../object/placement/PrepareModule.java | 143 ++++++++-------- .../object/placement/ResolvedReplace.java | 31 ++-- .../object/placement/ResolvedReplaces.java | 21 +-- .../engine/object/placement/SnowModule.java | 17 +- .../engine/object/placement/StiltModule.java | 91 +++++----- .../engine/object/placement/VacuumModule.java | 63 ++++--- .../object/placement/ValidateModule.java | 141 +++++++--------- .../engine/object/placement/WorldVolume.java | 12 +- 35 files changed, 1186 insertions(+), 555 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java create mode 100644 src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java rename src/main/java/art/arcane/iris/{engine/object/placement => builtin/prepare}/ObjectSpinKernel.java (68%) rename src/main/java/art/arcane/iris/{engine/object/placement => builtin/prepare}/PreparedPlacement.java (53%) rename src/main/java/art/arcane/iris/{engine/object/placement => builtin/prepare}/TransformedBounds.java (86%) diff --git a/README.md b/README.md index 3c3ad9e5f..2ac7bf997 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ direct dependencies on Iris internals. 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`, -`iris:vacuum`, `iris:snow`), the mantle, and chunk generation. Every mantle stage is a pass of Iris's +`iris:vacuum`, `iris:snow`, shipped in the built-ins jar), the mantle, and chunk generation. Every mantle stage is a pass of Iris's mantle of its own, in the stage graph's order: `iris:carve/caves`, `iris:objects/place`, `iris:floating/objects`, `iris:structure/place`, so a pack's mantle stage can order itself after any of them. Chunk generation then runs, in this order: `iris:biome`, `iris:terrain`, `iris:carve` (cutting the @@ -68,8 +68,10 @@ palette, ore checks, clump shapes per world seed) lives in the module's own code Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, -`.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). The module registers each with -`registry.registerHeldType(...)` so studio describes it from the module's own annotations; packs write the same JSON as before. Behaviour +`.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). A module compiled into Iris registers each with +`registry.registerHeldType(...)` so studio describes it from the module's own annotations; only such a module may, so the classes +Iris's `IrisObjectPlacement` holds are described by the host module `iris:placement-settings` (the placement stages ship in the +built-ins jar). Packs write the same JSON as before. Behaviour that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`). @@ -137,9 +139,11 @@ naming the class and what it uses. A VolmLib class that Iris's Bukkit jar strips `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. -The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and +The jar holds `iris:post`, `iris:perfection` and `iris:matter`, and the object placement stages `iris:prepare`, `iris:anchor`, +`iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain -sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. +sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks; the +placement stages read the placement being run through the `ObjectPlacement` facade (below). Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting `iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, `iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder @@ -149,5 +153,11 @@ when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, wh `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the same) and `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same -layers, and a layer's noise is built once per world by whichever asks first). `iris:post` reads its switches +layers, and a layer's noise is built once per world by whichever asks first). The placement stages need more of the object being +placed than IrisApi describes, so `placement.ObjectPlacement` is the facade Iris implements for each placement and binds to the placing +thread (`ObjectPlacement.current()`): the object's size (`ObjectShape`), the placement's settings (`PlacementSettings`, read from +Iris's `IrisObjectPlacement`), the terrain questions of its placer and the world around it (`PlacementTerrain`), the surface warp, +and the block operations only the platform can do (turning a state with the object, merging two states, matching, traits of the +placement's own states). Its types answer with IrisApi, VolmLib and built-in values only. `prepare.PreparedPlacement`, the output of +`iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. \ No newline at end of file diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..134d0871f 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -12,9 +12,24 @@ # (art.arcane.iris.builtin), the JDK and the other classes of the jar. `./gradlew builtinModulesJar` checks # that with IrisApi's pack class checks and fails naming the class and what it uses. # -# Moving a module here means removing it from IrisModuleHost.generationModules() or PlacementModules.all() in Iris. +# Moving a module here means removing it from IrisModuleHost.generationModules() in Iris. module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.object.placement.PrepareModule +module art.arcane.iris.engine.object.placement.AnchorModule +module art.arcane.iris.engine.object.placement.ValidateModule +module art.arcane.iris.engine.object.placement.BoreModule +module art.arcane.iris.engine.object.placement.BlocksModule +module art.arcane.iris.engine.object.placement.StiltModule +module art.arcane.iris.engine.object.placement.VacuumModule +module art.arcane.iris.engine.object.placement.SnowModule +include art/arcane/iris/engine/object/placement/PlacementModules.class +include art/arcane/iris/engine/object/placement/PlacementWorld.class +include art/arcane/iris/engine/object/placement/WorldVolume.class +include art/arcane/iris/engine/object/placement/ObjectEdits*.class +include art/arcane/iris/engine/object/placement/ResolvedReplace*.class +include art/arcane/iris/engine/object/placement/IrisSurfaceSupport*.class +include art/arcane/iris/engine/object/placement/IrisObjectVacuum.class diff --git a/src/main/java/art/arcane/iris/builtin/IrisStages.java b/src/main/java/art/arcane/iris/builtin/IrisStages.java index c22aedd5e..180132bc0 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisStages.java +++ b/src/main/java/art/arcane/iris/builtin/IrisStages.java @@ -20,9 +20,9 @@ package art.arcane.iris.builtin; import art.arcane.iris.builtin.anchor.AnchorHeight; import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.stilt.StiltLayers; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.PreparedPlacement; import com.volmit.stage.BlockStage; import com.volmit.stage.ChunkStage; import com.volmit.stage.MantleStage; @@ -40,8 +40,8 @@ public final class IrisStages { /** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ public static final class Prepare { - /** The settings the placement uses: the requested ones, turned downhill when they ask to face the slope. Rejects {@code slope}. */ - public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", IrisObjectPlacement.class); + /** The rotation the placement uses: the requested one, turned downhill when the settings ask to face the slope. Rejects {@code slope}. */ + public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", ObjectRotation.class); /** The random rotation, translation and height offset, chosen once per placement. */ public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 4e62e77b1..e68f723ce 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -32,8 +32,9 @@ * ({@link art.arcane.iris.builtin.IrisSeed}), and per-world state several of them use * ({@link art.arcane.iris.builtin.terrain.LayerBlocks}). Keep them few: each is a promise. *

- * Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A - * pack module can require such a stage to run after it, but cannot read its output: the pack load rejects - * a pack class that uses a type Iris hides. + * The placement stages ({@code iris:prepare} to {@code iris:snow}) reach the object being placed through + * {@link art.arcane.iris.builtin.placement.ObjectPlacement}, a facade Iris implements for each placement. Its types + * answer with IrisApi, VolmLib and built-in values only, and the stages' outputs ({@link art.arcane.iris.builtin.prepare.PreparedPlacement}) + * are built-in types too, so a pack module can require a placement stage and read what it chose. */ package art.arcane.iris.builtin; diff --git a/src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java b/src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java new file mode 100644 index 000000000..89cc8057b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java @@ -0,0 +1,59 @@ +/* + * 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.builtin.placement; + +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * The traits of the block states one placement handles, asked of the placement once per state instance. A placement + * reads the same few states over and over and the platform looks every state up by its value, so the answers are kept by + * identity. For one placement on one thread. + */ +public final class BlockTraits { + private final ObjectPlacement placement; + private final Map answers = new IdentityHashMap<>(); + + public BlockTraits(ObjectPlacement placement) { + this.placement = placement; + } + + public boolean has(BlockState state, BlockTrait trait) { + return answers.computeIfAbsent(state, ignored -> new TraitAnswers()).has(placement, state, trait); + } + + private static final class TraitAnswers { + private int asked; + private int held; + + boolean has(ObjectPlacement placement, BlockState state, BlockTrait trait) { + int flag = 1 << trait.ordinal(); + if ((asked & flag) == 0) { + if (placement.hasTrait(state, trait)) { + held |= flag; + } + asked |= flag; + } + return (held & flag) != 0; + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java b/src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java new file mode 100644 index 000000000..c03884dfa --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java @@ -0,0 +1,23 @@ +/* + * 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.builtin.placement; + +/** The cave an object is placed in: the height of its floor and how many blocks it is high. */ +public record CaveSpace(int surface, int height) { +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java b/src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java new file mode 100644 index 000000000..560ddae3b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java @@ -0,0 +1,37 @@ +/* + * 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.builtin.placement; + +import com.volmit.block.BlockState; + +import java.util.List; + +/** One marker of a placement, an entry of its {@code markers}: the blocks it marks and how many. */ +public interface MarkerRule { + /** The pack's marker to add. */ + String marker(); + + /** The blocks to mark. */ + List targets(); + + /** Whether a block must match a target exactly; otherwise its material is enough. */ + boolean exact(); + + int maximum(); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java new file mode 100644 index 000000000..2a8520599 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java @@ -0,0 +1,105 @@ +/* + * 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.builtin.placement; + +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.world.BlockPosition; + +import java.util.Optional; +import java.util.function.Supplier; + +/** + * The object placement being run, as Iris's built-in placement stages see it: what is placed and with which settings, the + * terrain it is placed on, and the few block operations that only the platform can do. Iris implements it for each + * placement and binds it to the placing thread while the placement graph runs; the stages read it through {@link #current()}. + * Heights are in the coordinates of the placement stages: above the dimension's bottom. + *

+ * It never hands out an engine, pack data or a platform type; everything it answers is an IrisApi, VolmLib or + * {@code art.arcane.iris.builtin} value. + */ +public interface ObjectPlacement { + /** The placement running on this thread. */ + static ObjectPlacement current() { + return PlacementBinding.current(); + } + + /** Runs {@code placement} with {@code inputs} as {@link #current()} on this thread. */ + static T runBound(ObjectPlacement inputs, Supplier placement) { + return PlacementBinding.run(inputs, placement); + } + + ObjectShape object(); + + /** The settings as the caller passed them; the stages derive what they change (the rotation) themselves. */ + PlacementSettings settings(); + + int x(); + + /** The height the caller asked for, negative when the placement samples it. */ + int requestedY(); + + int z(); + + /** The cave the object is placed in; empty outside caves. */ + Optional cave(); + + /** Answers the questions of the terrain the placement was asked to place on. */ + PlacementTerrain terrain(); + + /** + * The terrain the placement anchors against: {@link #terrain()}, or, when the settings place on a heightmap, the same + * terrain with its heights from the heightmap's noise, seeded from {@code rng}. + */ + PlacementTerrain terrainFor(RNG rng); + + /** The noise that warps the placement's columns; empty when the settings do not warp. */ + Optional surfaceWarp(RNG rng); + + /** Iris's simplex noise of {@code seed}, whose signed reads fill -1 to 1. */ + PlaneNoise simplex(long seed); + + /** {@code state} turned with the object by {@code rotation}, as the platform turns stairs, logs and other facing blocks. */ + BlockState rotate(BlockState state, ObjectRotation rotation, int spinX, int spinY, int spinZ); + + /** {@code update} laid over {@code base}: the platform's merge of two states of one block, else {@code update}. */ + BlockState merge(BlockState base, BlockState update); + + /** Whether {@code state}, as the platform's own state, matches {@code other}: {@code state.matches(other)} of the platform. */ + boolean matches(BlockState state, BlockState other); + + /** + * Whether {@code state} has {@code trait}, as the platform's own state answers it. Unlike the block registry it keeps + * the identity of the states this placement handed out, so a content plugin's block, which shares its key with the + * block it is drawn as, answers as itself ({@link BlockTrait#CUSTOM}). + */ + boolean hasTrait(BlockState state, BlockTrait trait); + + /** The marker of the pack named {@code key}, if the pack has one. */ + Optional marker(String key); + + /** Reports a buffered write as one of the object's own blocks, which Iris's placement listener hears after the commit. */ + void objectBlockWritten(BlockPosition position); + + /** Reports the height the object was anchored at, which the placement returns to its caller. */ + void anchoredAt(int y); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java new file mode 100644 index 000000000..9cae1d581 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java @@ -0,0 +1,45 @@ +/* + * 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.builtin.placement; + +import art.arcane.volmlib.util.math.IrisBlockVector; + +import java.util.List; + +/** The object being placed: its declared size, the block its offsets count from, and where it must stand on solid ground. */ +public interface ObjectShape { + int width(); + + int height(); + + int depth(); + + /** The block the object's offsets count from, relative to its corner. */ + int centerX(); + + int centerY(); + + int centerZ(); + + /** The pack's key of the object, or null for an object without one. */ + String key(); + + /** The columns of the object's lowest solid layer, as offsets from its anchor before any transform; empty for the origin only. */ + List surfaceSupportOffsets(); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java new file mode 100644 index 000000000..899f4b341 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java @@ -0,0 +1,40 @@ +/* + * 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.builtin.placement; + +import java.util.function.Supplier; + +/** The placement bound to the placing thread. */ +final class PlacementBinding { + private static final ScopedValue CURRENT = ScopedValue.newInstance(); + + private PlacementBinding() { + } + + static ObjectPlacement current() { + if (!CURRENT.isBound()) { + throw new IllegalStateException("No Iris object placement is running on this thread"); + } + return CURRENT.get(); + } + + static T run(ObjectPlacement placement, Supplier body) { + return ScopedValue.where(CURRENT, placement).call(body::get); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java new file mode 100644 index 000000000..a8907bd54 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java @@ -0,0 +1,92 @@ +/* + * 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.builtin.placement; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; + +import java.util.List; +import java.util.Optional; + +/** The settings of one object placement, as the placement stages read them. */ +public interface PlacementSettings { + boolean forcePlace(); + + SlopeClip slopeCondition(); + + boolean rotateTowardsSlope(); + + ObjectRotation rotation(); + + ObjectTranslate translate(); + + ObjectPlaceMode mode(); + + boolean fromBottom(); + + /** Whether the object places from the ground up instead of by height checks. */ + boolean bottom(); + + CarvingMode carvingSupport(); + + boolean underwater(); + + boolean onwater(); + + boolean requireSurfaceSupport(); + + int surfaceSupportBuffer(); + + int surfaceSupportDepth(); + + ObjectLimit clamp(); + + /** Whether air is placed before the object. */ + boolean bore(); + + int boreExtendMinY(); + + int boreExtendMaxY(); + + List edit(); + + boolean waterloggable(); + + boolean meld(); + + List markers(); + + Optional stilt(); + + Optional vacuum(); + + /** The snow filter's depth, 0 for none. */ + double snow(); + + List allowedCollisions(); + + List forbiddenCollisions(); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java new file mode 100644 index 000000000..5334cf82c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java @@ -0,0 +1,72 @@ +/* + * 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.builtin.placement; + +import com.volmit.block.BlockState; + +/** + * What a placement asks of the terrain and the world around it: heights, carving and water at a column, and the + * world's own facts. A placement made without a world ({@link #hasWorld()} is false) answers its terrain questions from + * the placer alone and the world's facts with nothing. + */ +public interface PlacementTerrain { + /** The surface height of the column, counting fluid unless {@code ignoreFluid}. */ + int highest(int x, int z, boolean ignoreFluid); + + boolean isCarved(int x, int y, int z); + + /** Whether the block is real, solid ground; the height field alone cannot say at mantle time. */ + boolean isSurfaceSolid(int x, int y, int z); + + boolean isUnderwater(int x, int z); + + /** The height up to which the dimension is filled with fluid. */ + int fluidHeight(); + + /** Whether leaves the placement writes never decay. */ + boolean preventsDecay(); + + /** Whether bored air is written as a visible block, to see where smart boring bored. */ + boolean debugsSmartBore(); + + boolean hasWorld(); + + /** The terrain's slope at the column, as the dimension's slope field gives it. */ + double slopeAt(int x, int z); + + /** The terrain height at a position between columns, as the dimension's height field gives it. */ + double heightAt(double x, double z); + + /** Whether the dimension has a bedrock floor. */ + boolean hasBedrock(); + + /** The real Y of the dimension's bottom. */ + int minHeight(); + + /** The dimension's height in blocks. */ + int worldHeight(); + + /** The rock the dimension has at the column; air when it has none to say. */ + BlockState rockAt(int x, int z); + + StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ); + + /** The pack's key of the object placed at the block, or null when none was. */ + String objectKeyAt(int x, int y, int z); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java b/src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java new file mode 100644 index 000000000..b5b20a0c7 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java @@ -0,0 +1,24 @@ +/* + * 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.builtin.placement; + +/** Noise over a plane that swings between -1 and 1, such as the rolling wave of a terrain bend. */ +public interface PlaneNoise { + double signed(double x, double z); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java b/src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java new file mode 100644 index 000000000..71a92b00f --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java @@ -0,0 +1,30 @@ +/* + * 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.builtin.placement; + +/** The world-space bounds of the native structure pieces around a placement, in the world's real Y. */ +public interface StructureVolumes { + boolean isEmpty(); + + /** Whether any piece meets the box, bounds inclusive. */ + boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ); + + /** Whether any piece contains the block or comes within {@code margin} blocks of it. */ + boolean containsWithin(int x, int y, int z, int margin); +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java b/src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java new file mode 100644 index 000000000..d5b47456a --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java @@ -0,0 +1,28 @@ +/* + * 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.builtin.placement; + +/** Noise that moves the columns of a placement sideways, so a square object warps like a flag. */ +public interface SurfaceWarp { + /** How far, in blocks, the warp may move a column in total. */ + double multiplier(); + + /** The noise at the position, fitted to the range from {@code min} to {@code max}. */ + double fit(double min, double max, double x, double y, double z); +} diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java index 71f972ab0..8cde2c559 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java @@ -42,6 +42,16 @@ public final class ObjectRotation { public ObjectRotation() { } + /** A rotation with the given axes, as Iris's own rotation model hands them to the placement stages. */ + public static ObjectRotation of(boolean enabled, AxisRotationClamp xAxis, AxisRotationClamp yAxis, AxisRotationClamp zAxis) { + ObjectRotation rotation = new ObjectRotation(); + rotation.enabled = enabled; + rotation.xAxis = xAxis; + rotation.yAxis = yAxis; + rotation.zAxis = zAxis; + return rotation; + } + public boolean enabled() { return enabled; } @@ -57,4 +67,28 @@ public final class ObjectRotation { public AxisRotationClamp zAxis() { return zAxis; } + + public boolean canRotateX() { + return enabled && xAxis.enabled(); + } + + public boolean canRotateY() { + return enabled && yAxis.enabled(); + } + + public boolean canRotateZ() { + return enabled && zAxis.enabled(); + } + + public boolean canRotate() { + return canRotateX() || canRotateY() || canRotateZ(); + } + + /** The angle, in radians, the object turns around {@code axis} for the random {@code spin}; 0 when the rotation or the axis is off. */ + public double radians(AxisRotationClamp axis, int spin) { + if (!enabled || !axis.enabled()) { + return 0; + } + return axis.getRadians(spin); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectSpinKernel.java similarity index 68% rename from src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java rename to src/main/java/art/arcane/iris/builtin/prepare/ObjectSpinKernel.java index c763bfc81..9c1decba9 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectSpinKernel.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectSpinKernel.java @@ -1,31 +1,24 @@ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.prepare; -import art.arcane.iris.builtin.prepare.AxisRotationClamp; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.IrisBlockVector; /** * Precomputed vector rotation for a single placement. *

- * This mirrors {@link IrisObjectRotation#rotate(IrisBlockVector, int, int, int)} branch for branch, with two - * differences: it mutates the vector handed to it instead of cloning, and the per-axis angle plus its cosine - * and sine are resolved once instead of once per block. The angle is a pure function of the axis clamp and the - * spin, both fixed for the placement, and Math.cos/Math.sin are pure, so every produced double is identical to - * the value the per-call form would have produced. + * Turns vectors branch for branch as Iris's object rotation does, with two differences: it mutates the vector + * handed to it instead of cloning, and the per-axis angle plus its cosine and sine are resolved once instead of once + * per block. The angle is a pure function of the axis clamp and the spin, both fixed for the placement, and + * Math.cos/Math.sin are pure, so every produced double is identical to the value the per-call form would have produced. */ - final class ObjectSpinKernel { +public final class ObjectSpinKernel { private static final int MODE_NONE = 0; private static final int MODE_FLIP = 1; private static final int MODE_QUARTER = 2; private static final int MODE_THREE_QUARTER = 3; private static final int MODE_ANGLE = 4; - IrisObjectRotation rotation; + private final ObjectRotation rotation; - private final int spinX ; - private final int spinY; - private final int spinZ; private final int xMode; private final int yMode; private final int zMode; @@ -36,17 +29,14 @@ import art.arcane.volmlib.util.math.IrisBlockVector; private final double zCos; private final double zSin; - ObjectSpinKernel(IrisObjectRotation rotation, int spinX, int spinY, int spinZ) { + public ObjectSpinKernel(ObjectRotation rotation, int spinX, int spinY, int spinZ) { this.rotation = rotation; - xMode = rotation.canRotateX() ? modeOf(rotation.getXAxis()) : MODE_NONE; - zMode = rotation.canRotateZ() ? modeOf(rotation.getZAxis()) : MODE_NONE; - yMode = rotation.canRotateY() ? modeOf(rotation.getYAxis()) : MODE_NONE; - this.spinX = spinX; - this.spinY = spinY; - this.spinZ = spinZ; - double xAngle = xMode == MODE_ANGLE ? rotation.getXRotation(spinX) : 0; - double zAngle = zMode == MODE_ANGLE ? rotation.getZRotation(spinZ) : 0; - double yAngle = yMode == MODE_ANGLE ? rotation.getYRotation(spinY) : 0; + xMode = rotation.canRotateX() ? modeOf(rotation.xAxis()) : MODE_NONE; + zMode = rotation.canRotateZ() ? modeOf(rotation.zAxis()) : MODE_NONE; + yMode = rotation.canRotateY() ? modeOf(rotation.yAxis()) : MODE_NONE; + double xAngle = xMode == MODE_ANGLE ? rotation.radians(rotation.xAxis(), spinX) : 0; + double zAngle = zMode == MODE_ANGLE ? rotation.radians(rotation.zAxis(), spinZ) : 0; + double yAngle = yMode == MODE_ANGLE ? rotation.radians(rotation.yAxis(), spinY) : 0; xCos = Math.cos(xAngle); xSin = Math.sin(xAngle); zCos = Math.cos(zAngle); @@ -75,14 +65,10 @@ import art.arcane.volmlib.util.math.IrisBlockVector; return MODE_ANGLE; } - PlatformBlockState rotate(PlatformBlockState state) { - return rotation.rotate(state, spinX, spinY, spinZ); - } - /** * Rotates in place. Axis order (X, then Z, then Y) is load bearing. */ - void rotate(IrisBlockVector v) { + public void rotate(IrisBlockVector v) { if (!rotation.canRotate()) { return; } diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java index 45afcef6d..f1f542d3b 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java @@ -52,6 +52,20 @@ public final class ObjectTranslate { public ObjectTranslate() { } + /** A shift of the given size, as Iris's own translate model hands it to the placement stages. */ + public static ObjectTranslate of(int x, int y, int yRandom, int z) { + ObjectTranslate translate = new ObjectTranslate(); + translate.x = x; + translate.y = y; + translate.yRandom = yRandom; + translate.z = z; + return translate; + } + + public boolean canTranslate() { + return x != 0 || y != 0 || z != 0; + } + public int x() { return x; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java b/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java similarity index 53% rename from src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java rename to src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java index e2b04c00b..a518639f1 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PreparedPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java @@ -16,24 +16,32 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.prepare; import art.arcane.iris.builtin.anchor.PlaceMode; import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.builtin.placement.BlockTraits; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.placement.SurfaceWarp; import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.project.noise.CNG; +import com.volmit.block.BlockState; import com.volmit.world.BlockPosition; /** - * What one placement chose before it is anchored: the settings it uses, the placer that answers its - * terrain questions, its random rotation and height offsets, and the bounds of the transformed object - * around its anchor. Object blocks are transformed by rotating them, flipping them for a ceiling hang and - * translating them. + * What one placement chose before it is anchored: the settings it uses, the rotation it ended up with, the terrain + * that answers its height, water and carving questions, its random spin and height offsets, and the bounds of the + * transformed object around its anchor. Object blocks are transformed by rotating them, flipping them for a ceiling + * hang and translating them. */ public final class PreparedPlacement { - private final IrisObjectPlacement config; - private final IObjectPlacer terrain; + private final ObjectPlacement placement; + private final PlacementSettings settings; + private final PlaceMode mode; + private final ObjectRotation rotation; + private final BlockTraits traits; + private final PlacementTerrain terrain; private final ObjectSpinKernel spin; private final int spinX; private final int spinY; @@ -44,12 +52,17 @@ public final class PreparedPlacement { private final int randomY; private final int warpMargin; private final TransformedBounds bounds; - private final CNG surfaceWarp; + private final SurfaceWarp surfaceWarp; - PreparedPlacement(IrisObjectPlacement config, IObjectPlacer terrain, ObjectSpinKernel spin, int spinX, int spinY, - int spinZ, IrisBlockVector translation, int rotatedCenterY, int translatedCenterY, int randomY, - int warpMargin, TransformedBounds bounds, CNG surfaceWarp) { - this.config = config; + /** Everything the preparation worked out; {@code translation} and {@code surfaceWarp} are null when the placement has none. */ + public PreparedPlacement(ObjectPlacement placement, ObjectRotation rotation, BlockTraits traits, PlacementTerrain terrain, + ObjectSpinKernel spin, int spinX, int spinY, int spinZ, IrisBlockVector translation, int rotatedCenterY, + int translatedCenterY, int randomY, int warpMargin, TransformedBounds bounds, SurfaceWarp surfaceWarp) { + this.placement = placement; + this.settings = placement.settings(); + this.mode = settings.mode().placeMode(); + this.rotation = rotation; + this.traits = traits; this.terrain = terrain; this.spin = spin; this.spinX = spinX; @@ -64,72 +77,82 @@ public final class PreparedPlacement { this.surfaceWarp = surfaceWarp; } - /** The settings this placement uses, which may differ from the requested ones. */ - public IrisObjectPlacement config() { - return config; + /** The settings the placement was asked for; the rotation may differ, see {@link #rotation()}. */ + public PlacementSettings settings() { + return settings; + } + + /** The rotation the placement uses, which may differ from the requested one. */ + public ObjectRotation rotation() { + return rotation; + } + + /** The traits of the block states this placement handles. */ + public BlockTraits traits() { + return traits; } /** Answers height, water and carving questions; a heightmap placement answers heights from its noise. */ - IObjectPlacer terrain() { + public PlacementTerrain terrain() { return terrain; } - PlaceMode mode() { - return config.getMode().placeMode(); + public PlaceMode mode() { + return mode; } - int spinX() { + public int spinX() { return spinX; } - int spinY() { + public int spinY() { return spinY; } - int spinZ() { + public int spinZ() { return spinZ; } /** The rotated translation, or null when the placement does not translate. */ - IrisBlockVector translation() { + public IrisBlockVector translation() { return translation; } /** The height of the object's center after rotation. */ - int rotatedCenterY() { + public int rotatedCenterY() { return rotatedCenterY; } /** The height of the object's center after translation. */ - int translatedCenterY() { + public int translatedCenterY() { return translatedCenterY; } /** The random height offset added once the anchor is final. */ - int randomY() { + public int randomY() { return randomY; } - int warpMargin() { + public int warpMargin() { return warpMargin; } - TransformedBounds bounds() { + public TransformedBounds bounds() { return bounds; } - boolean isWarped() { + public boolean isWarped() { return surfaceWarp != null; } /** Moves a world column by the surface warp, along X for {@code x} and along Z for the swapped call. */ - int warpOffset(double along, double y, double across) { - double half = config.getWarp().getMultiplier() / 2D; - return (int) surfaceWarp.fitDouble(-half, half, along, y, across); + public int warpOffset(double along, double y, double across) { + double half = surfaceWarp.multiplier() / 2D; + return (int) surfaceWarp.fit(-half, half, along, y, across); } /** An object block's offset from the anchor after this placement's transforms. */ - BlockPosition transform(BlockPosition local) { + public BlockPosition transform(BlockPosition local) { IrisBlockVector offset = new IrisBlockVector(local.x(), local.y(), local.z()); spin.rotate(offset); if (mode().has(PlaceTrait.UPSIDE_DOWN)) { @@ -142,7 +165,7 @@ public final class PreparedPlacement { } /** A block state turned with the object, so stairs and logs face the way the object does. */ - PlatformBlockState rotate(PlatformBlockState state) { - return spin.rotate(state); + public BlockState rotate(BlockState state) { + return placement.rotate(state, rotation, spinX, spinY, spinZ); } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java b/src/main/java/art/arcane/iris/builtin/prepare/TransformedBounds.java similarity index 86% rename from src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java rename to src/main/java/art/arcane/iris/builtin/prepare/TransformedBounds.java index 0b9d659e5..a594181fb 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/TransformedBounds.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/TransformedBounds.java @@ -16,8 +16,8 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.placement; +package art.arcane.iris.builtin.prepare; /** The bounds of a transformed object around its anchor, inclusive, widened by the surface warp along X and Z. */ -record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { +public record TransformedBounds(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index e85c47696..41bef35b7 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -18,17 +18,24 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.AnchorHeight; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.placement.CaveSpace; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.ObjectShape; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.prepare.TransformedBounds; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; +import java.util.Optional; + /** * Module {@code iris:anchor}: the height an object is placed at, requested by the caller, counted from the * bottom of the world, or sampled from the terrain the way the placement mode says. A surface-anchored @@ -54,24 +61,24 @@ public final class AnchorModule implements IrisModule { } private static AnchorHeight height(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); + PlacementSettings settings = prepared.settings(); boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); - if (!config.isFromBottom() && placement.requestedY() < 0) { + if (!settings.fromBottom() && placement.requestedY() < 0) { return new AnchorHeight(sampled(context, placement, prepared)); } - IrisObject object = placement.object(); - int y = config.isFromBottom() ? object.getH() + 1 + prepared.rotatedCenterY() : placement.requestedY(); - if (!config.isForcePlace() && !structurePiece && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { + ObjectShape object = placement.object(); + int y = settings.fromBottom() ? object.height() + 1 + prepared.rotatedCenterY() : placement.requestedY(); + if (!settings.forcePlace() && !structurePiece && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { context.reject(CARVING_ANCHOR); return new AnchorHeight(y); } - if (placement.requestedY() < 0 || !config.isBottom() || structurePiece) { + if (placement.requestedY() < 0 || !settings.bottom() || structurePiece) { return new AnchorHeight(y); } - y += Math.floorDiv(object.h, 2); - if (!config.isForcePlace() && config.getCarvingSupport() != CarvingMode.CARVING_ONLY + y += Math.floorDiv(object.height(), 2); + if (!settings.forcePlace() && settings.carvingSupport() != CarvingMode.CARVING_ONLY && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { context.reject(CARVING_ANCHOR); } @@ -80,14 +87,14 @@ public final class AnchorModule implements IrisModule { private static AnchorHeight finalHeight(PlacementStageContext context) { int y = context.output(IrisStages.Anchor.HEIGHT).y() + context.output(IrisStages.Prepare.TRANSFORMS).randomY(); - IrisPlacement.current().anchoredAt(y); + ObjectPlacement.current().anchoredAt(y); return new AnchorHeight(y); } - private static int sampled(PlacementStageContext context, IrisPlacement placement, PreparedPlacement prepared) { + private static int sampled(PlacementStageContext context, ObjectPlacement placement, PreparedPlacement prepared) { return switch (prepared.mode().anchor()) { case CENTER -> checked(context, prepared, placement.x(), centerSurface(placement, prepared), placement.z()); - case SURFACE -> checked(context, prepared, placement.x(), surface(placement, prepared, placement.x(), placement.z()), placement.z()); + case SURFACE -> checked(context, prepared, placement.x(), surface(prepared, placement.x(), placement.z()), placement.z()); case HIGHEST -> extremeSurface(context, placement, prepared, true, false); case HIGHEST_CORNER -> extremeSurface(context, placement, prepared, true, true); case LOWEST -> extremeSurface(context, placement, prepared, false, false); @@ -98,27 +105,27 @@ public final class AnchorModule implements IrisModule { } /** The floor of the cave the object is placed in, otherwise the surface at its center. */ - private static int centerSurface(IrisPlacement placement, PreparedPlacement prepared) { - if (placement.cave() != null) { - return placement.cave().getSurface() + prepared.rotatedCenterY(); + private static int centerSurface(ObjectPlacement placement, PreparedPlacement prepared) { + Optional cave = placement.cave(); + if (cave.isPresent()) { + return cave.get().surface() + prepared.rotatedCenterY(); } - return surface(placement, prepared, placement.x(), placement.z()); + return surface(prepared, placement.x(), placement.z()); } - private static int surface(IrisPlacement placement, PreparedPlacement prepared, int x, int z) { - return prepared.terrain().getHighest(x, z, placement.object().getLoader(), prepared.config().isUnderwater()) - + prepared.rotatedCenterY(); + private static int surface(PreparedPlacement prepared, int x, int z) { + return prepared.terrain().highest(x, z, prepared.settings().underwater()) + prepared.rotatedCenterY(); } private static int checked(PlacementStageContext context, PreparedPlacement prepared, int x, int y, int z) { - if (!prepared.config().isForcePlace() && rejectsCarvingAnchor(prepared, x, y, z)) { + if (!prepared.settings().forcePlace() && rejectsCarvingAnchor(prepared, x, y, z)) { context.reject(CARVING_ANCHOR); } return y; } /** The highest or lowest surface under the object's columns, or under its four corners only. */ - private static int extremeSurface(PlacementStageContext context, IrisPlacement placement, PreparedPlacement prepared, + private static int extremeSurface(PlacementStageContext context, ObjectPlacement placement, PreparedPlacement prepared, boolean highest, boolean cornersOnly) { TransformedBounds bounds = prepared.bounds(); int minX = placement.x() + bounds.minX(); @@ -130,8 +137,8 @@ public final class AnchorModule implements IrisModule { int y = highest ? -1 : Integer.MAX_VALUE; for (int x = minX; x <= maxX; x += xStep) { for (int z = minZ; z <= maxZ; z += zStep) { - int column = surface(placement, prepared, x, z); - if (!prepared.config().isForcePlace() && rejectsCarvingAnchor(prepared, x, column, z)) { + int column = surface(prepared, x, z); + if (!prepared.settings().forcePlace() && rejectsCarvingAnchor(prepared, x, column, z)) { context.reject(CARVING_ANCHOR); return y; } @@ -143,15 +150,15 @@ public final class AnchorModule implements IrisModule { /** Whether the placement's carving support forbids anchoring at this block. */ private static boolean rejectsCarvingAnchor(PreparedPlacement prepared, int x, int y, int z) { - IObjectPlacer terrain = prepared.terrain(); - return switch (prepared.config().getCarvingSupport()) { + PlacementTerrain terrain = prepared.terrain(); + return switch (prepared.settings().carvingSupport()) { case SURFACE_ONLY -> terrain.isCarved(x, y, z); case CARVING_ONLY -> !carvedWithin(terrain, x, y, z); case ANYWHERE -> false; }; } - private static boolean carvedWithin(IObjectPlacer terrain, int x, int y, int z) { + private static boolean carvedWithin(PlacementTerrain terrain, int x, int y, int z) { for (int depth = 0; depth < CARVING_CLEARANCE_BLOCKS; depth++) { if (terrain.isCarved(x, y - depth, z)) { return true; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index d04debcb6..21206dc03 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,28 +18,24 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.engine.spawn.SpawnResources; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.blocks.ObjectReplace; -import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.core.modules.BlockEntities; -import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.placement.MarkerRule; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.spawn.SpawnMarker; -import art.arcane.iris.engine.object.marker.IrisObjectMarker; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.BlockEntityData; import com.volmit.object.ObjectBlock; import com.volmit.placement.PlacedBlock; import com.volmit.stage.BlockStageContext; @@ -47,6 +43,8 @@ import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; +import java.util.Map; +import java.util.Optional; import java.util.Set; /** @@ -57,23 +55,24 @@ import java.util.Set; */ public final class BlocksModule implements IrisModule { private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + private static final BlockState VOID_AIR = new BlockState("minecraft:void_air"); + private static final BlockState VOID_AIR_DEBUG = new BlockState("minecraft:cobweb"); private static final String DISTANCE = "distance"; private static final String PERSISTENT = "persistent"; - private static final String WATERLOGGED = "waterlogged"; - private static final String TRUE = "true"; + static final String WATERLOGGED = "waterlogged"; + static final String TRUE = "true"; private static final String FALSE = "false"; private static final int MARKER_HEADROOM_BLOCKS = 2; + private static final Map FACE_OFFSETS = Map.of( + "north", new int[]{0, 0, -1}, "east", new int[]{1, 0, 0}, "south", new int[]{0, 0, 1}, + "west", new int[]{-1, 0, 0}, "up", new int[]{0, 1, 0}, "down", new int[]{0, -1, 0}); + private static final String[] FACE_PROPERTIES = {"north", "east", "south", "west", "up", "down"}; @Override public ModuleInfo info() { return ModuleInfo.of("iris:blocks", "Object blocks", PlacementModules.VERSION); } - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(ObjectReplace.class); - } - @Override public void install(StageGraph graph) { graph.define(IrisStages.Blocks.WRITE) @@ -89,20 +88,21 @@ public final class BlocksModule implements IrisModule { } private static void write(BlockStageContext context, WrittenBlocks written) { - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); - PlacementWorld world = new PlacementWorld(context.access(), placement.states()); + PlacementSettings settings = prepared.settings(); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); ObjectBlock block = context.block(); BlockPosition offset = prepared.transform(block.position()); int anchorY = context.output(IrisStages.Anchor.FINAL).y(); - PlatformBlockState data = sourceState(block, placement, prepared); - TileData tile = block.blockEntity().map(BlockEntities::tileOf).orElse(null); - if (!config.getEdit().isEmpty()) { - ObjectEdits.Edited edited = ObjectEdits.apply(config, data, tile, new RNG(context.random().nextLong()), - offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z(), placement.data()); + BlockState data = sourceState(block, placement, prepared); + Optional blockEntity = block.blockEntity(); + if (!settings.edit().isEmpty()) { + ObjectEdits.Edited edited = ObjectEdits.apply(settings.edit(), data, blockEntity, new RNG(context.random().nextLong()), + offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z(), + ResolvedReplaces.of(context, prepared.terrain()), placement); data = edited.data(); - tile = edited.tile(); + blockEntity = edited.blockEntity(); } data = prepared.rotate(data); int x = placement.x() + offset.x(); @@ -112,48 +112,48 @@ public final class BlocksModule implements IrisModule { x += prepared.warpOffset(offset.x() + placement.x(), y, offset.z() + placement.z()); z += prepared.warpOffset(offset.z() + placement.z(), y, offset.x() + placement.x()); } - if (WorldVolume.isPainted(placement, prepared) && !B.isVineBlock(data)) { - y = offset.y() + Math.floorDiv(placement.object().h, 2) - + prepared.terrain().getHighest(x, z, placement.object().getLoader(), config.isUnderwater()); + if (WorldVolume.isPainted(placement, prepared) && !world.has(data, BlockTrait.VINE)) { + y = offset.y() + Math.floorDiv(placement.object().height(), 2) + + prepared.terrain().highest(x, z, settings.underwater()); } boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); - if (config.isMeld() && !structurePiece && !world.isSolid(x, y, z)) { + if (settings.meld() && !structurePiece && !world.isSolid(x, y, z)) { return; } - if (IrisProceduralBlocks.hasProperty(data, WATERLOGGED) && shouldWaterlog(world, config, placement.requestedY(), x, y, z)) { + if (data.properties().containsKey(WATERLOGGED) && shouldWaterlog(world, settings, placement.requestedY(), x, y, z)) { data = data.withProperty(WATERLOGGED, TRUE); } - if (B.isVineBlock(data)) { + if (world.has(data, BlockTrait.VINE)) { data = attachVineFaces(world, data, x, y, z); } if (!shouldWrite(world, data, x, y, z, structurePiece)) { return; } - PlacedBlock placed = world.set(x, y, z, data, tile); + PlacedBlock placed = world.set(x, y, z, data, blockEntity); placement.objectBlockWritten(placed.position()); written.add(placed); } /** The object block as Iris places it: debug air shows where smart boring bored, and leaves never decay where the placer prevents it. */ - private static PlatformBlockState sourceState(ObjectBlock block, IrisPlacement placement, PreparedPlacement prepared) { - PlatformBlockState data = placement.states().toPlatform(block.state()); - IObjectPlacer terrain = prepared.terrain(); - if (terrain.isDebugSmartBore() && data.matches(IrisObject.States.VAIR)) { - data = IrisObject.States.VAIR_DEBUG; + private static BlockState sourceState(ObjectBlock block, ObjectPlacement placement, PreparedPlacement prepared) { + BlockState data = block.state(); + PlacementTerrain terrain = prepared.terrain(); + if (terrain.debugsSmartBore() && placement.matches(data, VOID_AIR)) { + data = VOID_AIR_DEBUG; } - if (terrain.isPreventingDecay() && IrisProceduralBlocks.hasProperty(data, DISTANCE) - && FALSE.equals(IrisProceduralBlocks.propertyValue(data, PERSISTENT))) { + if (terrain.preventsDecay() && data.properties().containsKey(DISTANCE) + && FALSE.equals(data.properties().get(PERSISTENT))) { data = data.withProperty(PERSISTENT, TRUE); } return data; } - private static boolean shouldWrite(PlacementWorld world, PlatformBlockState data, int x, int y, int z, boolean structurePiece) { - if (data.isCustom()) { + private static boolean shouldWrite(PlacementWorld world, BlockState data, int x, int y, int z, boolean structurePiece) { + if (world.has(data, BlockTrait.CUSTOM)) { return true; } - boolean vineIntoSolid = B.isVineBlock(data) && world.isSolid(x, y, z); - return shouldPlaceObjectBlock(structurePiece, AIR_MATERIALS.contains(IrisObjectShaping.materialKey(data)), vineIntoSolid); + boolean vineIntoSolid = world.has(data, BlockTrait.VINE) && world.isSolid(x, y, z); + return shouldPlaceObjectBlock(structurePiece, AIR_MATERIALS.contains(data.material().toString()), vineIntoSolid); } /** Air is written only by structure pieces, and a vine never replaces a solid block. */ @@ -162,27 +162,27 @@ public final class BlocksModule implements IrisModule { } /** Whether a waterloggable block lands in water a waterloggable or underwater placement keeps. */ - static boolean shouldWaterlog(PlacementWorld world, IrisObjectPlacement config, int requestedY, int x, int y, int z) { - if (!(config.isWaterloggable() || config.isUnderwater())) { + static boolean shouldWaterlog(PlacementWorld world, PlacementSettings settings, int requestedY, int x, int y, int z) { + if (!(settings.waterloggable() || settings.underwater())) { return false; } - if (requestedY >= 0 && config.getCarvingSupport() == CarvingMode.CARVING_ONLY) { + if (requestedY >= 0 && settings.carvingSupport() == CarvingMode.CARVING_ONLY) { return false; } - PlatformBlockState existing = world.get(x, y, z); - return B.isWater(existing) || B.isWaterLogged(existing); + BlockState existing = world.get(x, y, z); + return world.has(existing, BlockTrait.WATER) || TRUE.equals(existing.properties().get(WATERLOGGED)); } /** {@code vine} hanging from each neighboring solid block it has a face property for. */ - static PlatformBlockState attachVineFaces(PlacementWorld world, PlatformBlockState vine, int x, int y, int z) { - PlatformBlockState attached = vine; - for (String face : IrisProceduralBlocks.FACE_PROPERTIES) { - if (!IrisProceduralBlocks.hasProperty(vine, face)) { + static BlockState attachVineFaces(PlacementWorld world, BlockState vine, int x, int y, int z) { + BlockState attached = vine; + for (String face : FACE_PROPERTIES) { + if (!vine.properties().containsKey(face)) { continue; } - int[] offset = IrisProceduralBlocks.faceOffset(face); - PlatformBlockState facing = world.get(x + offset[0], y + offset[1], z + offset[2]); - if (B.isSolid(facing) && !B.isVineBlock(facing)) { + int[] offset = FACE_OFFSETS.get(face); + BlockState facing = world.get(x + offset[0], y + offset[1], z + offset[2]); + if (world.has(facing, BlockTrait.SOLID) && !world.has(facing, BlockTrait.VINE)) { attached = attached.withProperty(face, TRUE); } } @@ -194,57 +194,55 @@ public final class BlocksModule implements IrisModule { * where the marker either allows anything above or finds two blocks of air. */ private static void placeMarkers(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); - if (config.getMarkers().isEmpty() || prepared.terrain().getEngine() == null) { + PlacementSettings settings = prepared.settings(); + if (settings.markers().isEmpty() || !prepared.terrain().hasWorld()) { return; } WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); - PlacementWorld world = new PlacementWorld(context.access(), placement.states()); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; - for (IrisObjectMarker markerConfig : config.getMarkers()) { - SpawnMarker marker = SpawnResources.marker(placement.object().getLoader(), markerConfig.getMarker()); + for (MarkerRule rule : settings.markers()) { + Optional marker = placement.marker(rule.marker()); int markerSalt = salt++; - if (marker == null) { + if (marker.isEmpty()) { continue; } - KList candidates = candidates(written, markerConfig, markerConfig.getMark(placement.data()), placement); - int remaining = markerConfig.getMaximumMarkers(); + KList candidates = candidates(written, rule, placement); + int remaining = rule.maximum(); for (BlockPosition position : candidates.shuffleCopy(markerRandom.nextParallelRNG(markerSalt))) { if (remaining <= 0) { break; } - if (!marker.emptyAbove() || hasAirAbove(world, position)) { - context.access().marker(ObjectMarkers.of(position, markerConfig.getMarker())); + if (!marker.get().emptyAbove() || hasAirAbove(world, position)) { + context.access().marker(ObjectMarkers.of(position, rule.marker())); remaining--; } } } } - private static KList candidates(WrittenBlocks written, IrisObjectMarker markerConfig, - KList targets, IrisPlacement placement) { + private static KList candidates(WrittenBlocks written, MarkerRule rule, ObjectPlacement placement) { KList candidates = new KList<>(); for (PlacedBlock block : written.blocks()) { - PlatformBlockState state = placement.states().toPlatform(block.state()); - if (targets.stream().anyMatch(target -> marks(markerConfig, target, state))) { + if (rule.targets().stream().anyMatch(target -> marks(placement, rule, target, block.state()))) { candidates.add(block.position()); } } return candidates; } - private static boolean marks(IrisObjectMarker markerConfig, PlatformBlockState target, PlatformBlockState state) { - return markerConfig.isExact() - ? target.matches(state) - : IrisObjectShaping.materialKey(target).equals(IrisObjectShaping.materialKey(state)); + private static boolean marks(ObjectPlacement placement, MarkerRule rule, BlockState target, BlockState state) { + return rule.exact() + ? placement.matches(target, state) + : target.material().equals(state.material()); } private static boolean hasAirAbove(PlacementWorld world, BlockPosition position) { for (int above = 1; above <= MARKER_HEADROOM_BLOCKS; above++) { - if (!B.isAir(world.get(position.x(), position.y() + above, position.z()))) { + if (!world.has(world.get(position.x(), position.y() + above, position.z()), BlockTrait.AIR)) { return false; } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java index 838153804..9f4887f93 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -19,15 +19,19 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.prepare.PreparedPlacement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; /** Module {@code iris:bore}: fills the object's volume with air, extended up and down as configured. */ public final class BoreModule implements IrisModule { + private static final BlockState AIR = new BlockState("minecraft:cave_air"); + @Override public ModuleInfo info() { return ModuleInfo.of("iris:bore", "Bore", PlacementModules.VERSION); @@ -42,17 +46,17 @@ public final class BoreModule implements IrisModule { private static void clear(PlacementStageContext context) { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); - if (!config.isBore()) { + PlacementSettings settings = prepared.settings(); + if (!settings.bore()) { return; } - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.FINAL).y()); - PlacementWorld world = new PlacementWorld(context.access(), placement.states()); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); for (int x = volume.minX(); x <= volume.maxX(); x++) { - for (int y = volume.minY() - config.getBoreExtendMinY(); y <= volume.maxY() + config.getBoreExtendMaxY(); y++) { + for (int y = volume.minY() - settings.boreExtendMinY(); y <= volume.maxY() + settings.boreExtendMaxY(); y++) { for (int z = volume.minZ(); z <= volume.maxZ(); z++) { - world.set(x, y, z, IrisObject.States.AIR); + world.set(x, y, z, AIR); } } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java index 67ab79b97..780dd222d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java @@ -1,8 +1,9 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectSpinKernel; +import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.volmlib.util.math.IrisBlockVector; import java.util.Arrays; @@ -20,29 +21,41 @@ public final class IrisSurfaceSupport { private IrisSurfaceSupport() { } - public static boolean isUnsupported(IObjectPlacer placer, IrisData data, int x, int z, - IrisObjectTranslate translate, IrisObjectRotation rotation, + public static boolean isUnsupported(PlacementTerrain terrain, int x, int z, + ObjectTranslate translate, ObjectRotation rotation, int spinX, int spinY, int spinZ, List supportOffsets, int buffer, int minSolidDepth) { Stencil stencil = STENCIL.get(); - if (!stencil.build(supportOffsets, translate, rotation, spinX, spinY, spinZ, Math.max(0, buffer))) { + Transform transform = new Transform(translate, new ObjectSpinKernel(rotation, spinX, spinY, spinZ)); + if (!stencil.build(supportOffsets, transform, Math.max(0, buffer))) { return true; } - return stencil.anyColumnUnsupported(placer, data, x, z, Math.max(1, minSolidDepth)); + return stencil.anyColumnUnsupported(terrain, x, z, Math.max(1, minSolidDepth)); } - private static IrisBlockVector transform(IrisBlockVector offset, IrisObjectTranslate translate, - IrisObjectRotation rotation, int spinX, int spinY, int spinZ) { - IrisBlockVector transformed = offset.clone(); - if (rotation != null) { - transformed = rotation.rotate(transformed, spinX, spinY, spinZ); + /** The placement's rotation and translation, as they move a support offset. */ + private static final class Transform { + private final ObjectSpinKernel spin; + private final IrisBlockVector translation; + + private Transform(ObjectTranslate translate, ObjectSpinKernel spin) { + this.spin = spin; + if (translate.canTranslate()) { + translation = new IrisBlockVector(translate.x(), translate.y(), translate.z()); + spin.rotate(translation); + } else { + translation = null; + } } - if (translate == null) { + + private IrisBlockVector apply(IrisBlockVector offset) { + IrisBlockVector transformed = offset.clone(); + spin.rotate(transformed); + if (translation != null) { + transformed.add(translation); + } return transformed; } - return rotation == null - ? translate.translate(transformed) - : translate.translate(transformed, rotation, spinX, spinY, spinZ); } /** @@ -61,8 +74,7 @@ public final class IrisSurfaceSupport { private int centerX; private int centerZ; - private boolean build(List supportOffsets, IrisObjectTranslate translate, - IrisObjectRotation rotation, int spinX, int spinY, int spinZ, int buffer) { + private boolean build(List supportOffsets, Transform transform, int buffer) { boolean originOnly = supportOffsets == null || supportOffsets.isEmpty(); int count = originOnly ? 1 : supportOffsets.size(); if (offsetX.length < count) { @@ -76,7 +88,7 @@ public final class IrisSurfaceSupport { int highZ = Integer.MIN_VALUE; for (int i = 0; i < count; i++) { IrisBlockVector source = originOnly ? new IrisBlockVector(0, 0, 0) : supportOffsets.get(i); - IrisBlockVector transformed = transform(source, translate, rotation, spinX, spinY, spinZ); + IrisBlockVector transformed = transform.apply(source); int transformedX = transformed.getBlockX(); int transformedZ = transformed.getBlockZ(); offsetX[i] = transformedX; @@ -150,13 +162,13 @@ public final class IrisSurfaceSupport { } /** Centre-outward so the common failure, a hole right under the anchor, costs one column. */ - private boolean anyColumnUnsupported(IObjectPlacer placer, IrisData data, int x, int z, int minSolidDepth) { + private boolean anyColumnUnsupported(PlacementTerrain terrain, int x, int z, int minSolidDepth) { int maxRing = Math.max( Math.max(centerX, width - 1 - centerX), Math.max(centerZ, depth - 1 - centerZ)); for (int ring = 0; ring <= maxRing; ring++) { if (ring == 0) { - if (isColumnUnsupported(placer, data, x, z, centerX, centerZ, minSolidDepth)) { + if (isColumnUnsupported(terrain, x, z, centerX, centerZ, minSolidDepth)) { return true; } continue; @@ -167,14 +179,14 @@ public final class IrisSurfaceSupport { int lowZ = centerZ - ring; int highZ = centerZ + ring; for (int sx = lowX; sx <= highX; sx++) { - if (isColumnUnsupported(placer, data, x, z, sx, lowZ, minSolidDepth) - || isColumnUnsupported(placer, data, x, z, sx, highZ, minSolidDepth)) { + if (isColumnUnsupported(terrain, x, z, sx, lowZ, minSolidDepth) + || isColumnUnsupported(terrain, x, z, sx, highZ, minSolidDepth)) { return true; } } for (int sz = lowZ + 1; sz < highZ; sz++) { - if (isColumnUnsupported(placer, data, x, z, lowX, sz, minSolidDepth) - || isColumnUnsupported(placer, data, x, z, highX, sz, minSolidDepth)) { + if (isColumnUnsupported(terrain, x, z, lowX, sz, minSolidDepth) + || isColumnUnsupported(terrain, x, z, highX, sz, minSolidDepth)) { return true; } } @@ -182,7 +194,7 @@ public final class IrisSurfaceSupport { return false; } - private boolean isColumnUnsupported(IObjectPlacer placer, IrisData data, int x, int z, + private boolean isColumnUnsupported(PlacementTerrain terrain, int x, int z, int stencilX, int stencilZ, int minSolidDepth) { if (stencilX < 0 || stencilX >= width || stencilZ < 0 || stencilZ >= depth || !cells[(stencilX * depth) + stencilZ]) { @@ -191,13 +203,13 @@ public final class IrisSurfaceSupport { int columnX = x + minX + stencilX; int columnZ = z + minZ + stencilZ; - int surfaceY = placer.getHighest(columnX, columnZ, data, true); + int surfaceY = terrain.highest(columnX, columnZ, true); for (int below = 0; below < minSolidDepth; below++) { - if (placer.isCarved(columnX, surfaceY - below, columnZ)) { + if (terrain.isCarved(columnX, surfaceY - below, columnZ)) { return true; } } - return !placer.isSurfaceSolid(columnX, surfaceY, columnZ); + return !terrain.isSurfaceSolid(columnX, surfaceY, columnZ); } } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java index b6bf61863..166b8fed2 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java @@ -19,12 +19,14 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.material.BlockDataMergeSupport; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.builtin.placement.ObjectPlacement; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.BlockEntityData; + +import java.util.List; +import java.util.Optional; /** * A placement's block replacements ({@code edit}): each replacement, by its chance, swaps the blocks it @@ -35,42 +37,44 @@ final class ObjectEdits { private ObjectEdits() { } - /** {@code tile} may be null; the result's tile is the last replacement's tile, if it has one. */ - static Edited apply(IrisObjectPlacement config, PlatformBlockState data, TileData tile, RNG rng, - double x, double y, double z, IrisData rdata) { - ResolvedReplaces replaces = ResolvedReplaces.of(rdata); - PlatformBlockState edited = data; - TileData editedTile = tile; - for (ObjectReplace settings : config.getEdit()) { + /** The result's block entity is the last replacement's, if it has one. */ + static Edited apply(List edits, BlockState data, Optional blockEntity, RNG rng, + double x, double y, double z, ResolvedReplaces replaces, ObjectPlacement placement) { + BlockState edited = data; + Optional editedEntity = blockEntity; + for (ObjectReplace settings : edits) { ResolvedReplace replace = replaces.of(settings); if (!rng.chance(replace.chance())) { continue; } - for (PlatformBlockState find : replace.find()) { - if (!finds(replace, find, edited)) { + for (BlockState find : replace.find()) { + if (!finds(placement, replace, find, edited)) { continue; } - edited = replaced(edited, replace.replacement(rng, x, y, z)); - editedTile = replace.tile(rng).orElse(editedTile); + edited = replaced(placement, edited, replace.replacement(rng, x, y, z)); + Optional picked = replace.tile(rng); + if (picked.isPresent()) { + editedEntity = picked; + } } } - return new Edited(edited, editedTile); + return new Edited(edited, editedEntity); } - private static boolean finds(ResolvedReplace replace, PlatformBlockState find, PlatformBlockState data) { + private static boolean finds(ObjectPlacement placement, ResolvedReplace replace, BlockState find, BlockState data) { return replace.exact() - ? find.matches(data) - : IrisObjectShaping.materialKey(find).equals(IrisObjectShaping.materialKey(data)); + ? placement.matches(find, data) + : find.material().equals(data.material()); } - private static PlatformBlockState replaced(PlatformBlockState data, PlatformBlockState replacement) { - boolean sameMaterial = IrisObjectShaping.materialKey(replacement).equals(IrisObjectShaping.materialKey(data)); - if (sameMaterial && !replacement.isCustom() && !data.isCustom()) { - return BlockDataMergeSupport.merge(data, replacement); + private static BlockState replaced(ObjectPlacement placement, BlockState data, BlockState replacement) { + boolean sameMaterial = replacement.material().equals(data.material()); + if (sameMaterial && !placement.hasTrait(replacement, BlockTrait.CUSTOM) && !placement.hasTrait(data, BlockTrait.CUSTOM)) { + return placement.merge(data, replacement); } return replacement; } - record Edited(PlatformBlockState data, TileData tile) { + record Edited(BlockState data, Optional blockEntity) { } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java index 7ca2ab130..72be39ff6 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementModules.java @@ -18,19 +18,10 @@ package art.arcane.iris.engine.object.placement; -import com.volmit.IrisModule; - -import java.util.List; - -/** Iris's built-in object placement, as the IrisApi modules every pack's placement graph starts from. */ -public final class PlacementModules { +/** What Iris's built-in object placement modules share: the version they report. The modules ship in the built-ins jar. */ +final class PlacementModules { static final String VERSION = "built-in"; private PlacementModules() { } - - public static List all() { - return List.of(new PrepareModule(), new AnchorModule(), new ValidateModule(), new BoreModule(), - new BlocksModule(), new StiltModule(), new VacuumModule(), new SnowModule()); - } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java index 49b0b6625..3e06a34f5 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java @@ -18,46 +18,44 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.core.modules.BlockEntities; -import art.arcane.iris.core.modules.PlatformBlockStates; -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.iris.builtin.placement.BlockTraits; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.object.BlockEntityData; import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacementAccess; import com.volmit.world.BlockPosition; import java.util.Optional; -/** - * A placement stage's buffered world in Iris's block states: reads see the placement's earlier writes, - * writes wait for the placement to commit. - */ +/** A placement stage's buffered world: reads see the placement's earlier writes, writes wait for the placement to commit. */ final class PlacementWorld { private final PlacementAccess access; - private final PlatformBlockStates states; + private final BlockTraits traits; - PlacementWorld(PlacementAccess access, PlatformBlockStates states) { + PlacementWorld(PlacementAccess access, BlockTraits traits) { this.access = access; - this.states = states; + this.traits = traits; } - PlatformBlockState get(int x, int y, int z) { - return states.toPlatform(access.get(x, y, z)); + BlockState get(int x, int y, int z) { + return access.get(x, y, z); + } + + boolean has(BlockState state, BlockTrait trait) { + return traits.has(state, trait); } boolean isSolid(int x, int y, int z) { - return B.isSolid(get(x, y, z)); + return has(get(x, y, z), BlockTrait.SOLID); } - PlacedBlock set(int x, int y, int z, PlatformBlockState state) { - return set(x, y, z, state, null); + PlacedBlock set(int x, int y, int z, BlockState state) { + return set(x, y, z, state, Optional.empty()); } - /** {@code tile} may be null for a block without tile data. */ - PlacedBlock set(int x, int y, int z, PlatformBlockState state, TileData tile) { - PlacedBlock block = new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), - Optional.ofNullable(tile).map(BlockEntities::of)); + PlacedBlock set(int x, int y, int z, BlockState state, Optional blockEntity) { + PlacedBlock block = new PlacedBlock(new BlockPosition(x, y, z), state, blockEntity); access.set(block); return block; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 6a4dc7e9d..470a2c539 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -18,26 +18,29 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.prepare.SlopeClip; -import com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.placer.HeightmapObjectPlacer; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.placement.BlockTraits; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.ObjectShape; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.placement.SurfaceWarp; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectSpinKernel; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.stream.ProceduralStream; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; +import java.util.Optional; + /** * Module {@code iris:prepare}: checks the slope, turns the object downhill when asked, and chooses the * placement's rotation, translation and random height offset. @@ -55,12 +58,6 @@ public final class PrepareModule implements IrisModule { return ModuleInfo.of("iris:prepare", "Placement preparation", PlacementModules.VERSION); } - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(SlopeClip.class); - registry.registerHeldType(AxisRotationClamp.class); - } - @Override public void install(StageGraph graph) { graph.define(IrisStages.Prepare.SLOPE).produce(PrepareModule::slope); @@ -69,76 +66,78 @@ public final class PrepareModule implements IrisModule { .produce(PrepareModule::transforms); } - private static IrisObjectPlacement slope(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); - IrisObjectPlacement config = placement.config(); - boolean checksSlope = !config.isForcePlace() && !config.getSlopeCondition().isDefault(); - if (!checksSlope && !config.isRotateTowardsSlope()) { - return config; + private static ObjectRotation slope(PlacementStageContext context) { + ObjectPlacement placement = ObjectPlacement.current(); + PlacementSettings settings = placement.settings(); + ObjectRotation requested = settings.rotation(); + boolean checksSlope = !settings.forcePlace() && !settings.slopeCondition().isDefault(); + if (!checksSlope && !settings.rotateTowardsSlope()) { + return requested; } - Engine engine = placement.placer().getEngine(); - if (engine == null) { + if (!placement.terrain().hasWorld()) { throw new IllegalStateException("Object placement requires an active Iris engine for slope settings."); } - if (checksSlope && !config.getSlopeCondition().isValid(engine.getComplex().getSlopeStream().get(placement.x(), placement.z()))) { + if (checksSlope && !settings.slopeCondition().isValid(placement.terrain().slopeAt(placement.x(), placement.z()))) { context.reject("slope"); - return config; + return requested; } - return config.isRotateTowardsSlope() ? turnedDownhill(placement.object(), config, engine, placement.x(), placement.z()) : config; + return settings.rotateTowardsSlope() ? turnedDownhill(placement, requested) : requested; } - /** A copy of {@code config} whose Y rotation faces the lowest side of the rectangle around the object. */ - private static IrisObjectPlacement turnedDownhill(IrisObject object, IrisObjectPlacement config, Engine engine, int x, int z) { - ProceduralStream heights = engine.getComplex().getHeightStream(); - double north = heights.get(x, z + ((float) object.d) / 2); - double east = heights.get(x + ((float) object.w) / 2, z); - double south = heights.get(x, z - ((float) object.d) / 2); - double west = heights.get(x - ((float) object.w) / 2, z); + /** A copy of {@code requested} whose Y rotation faces the lowest side of the rectangle around the object. */ + private static ObjectRotation turnedDownhill(ObjectPlacement placement, ObjectRotation requested) { + PlacementTerrain terrain = placement.terrain(); + ObjectShape object = placement.object(); + int x = placement.x(); + int z = placement.z(); + double north = terrain.heightAt(x, z + ((float) object.depth()) / 2); + double east = terrain.heightAt(x + ((float) object.width()) / 2, z); + double south = terrain.heightAt(x, z - ((float) object.depth()) / 2); + double west = terrain.heightAt(x - ((float) object.width()) / 2, z); double lowest = Math.min(Math.min(north, east), Math.min(south, west)); double downhill = lowest == north ? NORTH : lowest == east ? EAST : lowest == south ? SOUTH : WEST; - IrisObjectRotation requested = config.getRotation(); - double turn = requested.getYAxis().min() + downhill; - IrisObjectRotation rotation = new IrisObjectRotation(); - rotation.setXAxis(requested.getXAxis()); - rotation.setZAxis(requested.getZAxis()); + double turn = requested.yAxis().min() + downhill; if (turn == 0) { - rotation.setYAxis(AxisRotationClamp.of(false, false, 0, 0, QUARTER_TURN)); - rotation.setEnabled(requested.canRotateX() || requested.canRotateZ()); - } else { - rotation.setYAxis(AxisRotationClamp.of(true, false, turn, turn, QUARTER_TURN)); - rotation.setEnabled(true); + return ObjectRotation.of(requested.canRotateX() || requested.canRotateZ(), requested.xAxis(), + AxisRotationClamp.of(false, false, 0, 0, QUARTER_TURN), requested.zAxis()); } - IrisObjectPlacement turned = config.toPlacement(config.getPlace().toArray(new String[0])); - turned.setRotation(rotation); - return turned; + return ObjectRotation.of(true, requested.xAxis(), AxisRotationClamp.of(true, false, turn, turn, QUARTER_TURN), + requested.zAxis()); } private static PreparedPlacement transforms(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); - IrisObjectPlacement config = context.output(IrisStages.Prepare.SLOPE); - IrisObject object = placement.object(); + ObjectPlacement placement = ObjectPlacement.current(); + PlacementSettings settings = placement.settings(); + ObjectRotation rotation = context.output(IrisStages.Prepare.SLOPE); + ObjectShape object = placement.object(); RNG rng = new RNG(context.random().nextLong()); - IObjectPlacer terrain = config.getHeightmap() == null ? placement.placer() - : new HeightmapObjectPlacer(rng, placement.x(), placement.requestedY(), placement.z(), config, placement.placer()); + PlacementTerrain terrain = placement.terrainFor(rng); int spinX = rng.imax() / SPIN_DIVISOR; int spinY = rng.imax() / SPIN_DIVISOR; int spinZ = rng.imax() / SPIN_DIVISOR; - IrisObjectRotation rotation = config.getRotation(); - IrisObjectTranslate translate = config.getTranslate(); - int centerY = object.getCenter().getBlockY(); - int rotatedCenterY = rotation.rotate(new IrisBlockVector(0, centerY, 0), spinX, spinY, spinZ).getBlockY(); - int translatedCenterY = translate.translate(new IrisBlockVector(0, centerY, 0), rotation, spinX, spinY, spinZ).getBlockY(); + ObjectTranslate translate = settings.translate(); ObjectSpinKernel spin = new ObjectSpinKernel(rotation, spinX, spinY, spinZ); - IrisBlockVector translation = translate.canTranslate() - ? rotation.rotate(new IrisBlockVector(translate.getX(), translate.getY(), translate.getZ()), spinX, spinY, spinZ) - : null; - int randomY = randomHeightOffset(translate.getYRandom(), rng); - int warpMargin = config.getWarp().isFlat() ? 0 : (int) Math.ceil(Math.abs(config.getWarp().getMultiplier()) / 2D); - TransformedBounds bounds = transformedBounds(object, spin, translation, config.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN), warpMargin); - CNG surfaceWarp = config.getWarp().isFlat() ? null : config.getSurfaceWarp(rng, object.getLoader()); - return new PreparedPlacement(config, terrain, spin, spinX, spinY, spinZ, translation, rotatedCenterY, - translatedCenterY, randomY, warpMargin, bounds, surfaceWarp); + IrisBlockVector rotatedCenter = new IrisBlockVector(0, object.centerY(), 0); + spin.rotate(rotatedCenter); + IrisBlockVector translation = translate.canTranslate() ? rotated(spin, translate) : null; + IrisBlockVector translatedCenter = new IrisBlockVector(0, object.centerY(), 0); + if (translation != null) { + translatedCenter = (IrisBlockVector) translatedCenter.clone().add(translation); + } + int randomY = randomHeightOffset(translate.yRandom(), rng); + Optional surfaceWarp = placement.surfaceWarp(rng); + int warpMargin = surfaceWarp.map(warp -> (int) Math.ceil(Math.abs(warp.multiplier()) / 2D)).orElse(0); + TransformedBounds bounds = transformedBounds(object, spin, translation, settings.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN), warpMargin); + return new PreparedPlacement(placement, rotation, new BlockTraits(placement), terrain, spin, + spinX, spinY, spinZ, translation, rotatedCenter.getBlockY(), translatedCenter.getBlockY(), randomY, + warpMargin, bounds, surfaceWarp.orElse(null)); + } + + private static IrisBlockVector rotated(ObjectSpinKernel spin, ObjectTranslate translate) { + IrisBlockVector shift = new IrisBlockVector(translate.x(), translate.y(), translate.z()); + spin.rotate(shift); + return shift; } /** Within {@code range} of zero, on the side its sign gives. */ @@ -149,11 +148,11 @@ public final class PrepareModule implements IrisModule { return range < 0 ? rng.i(range, 0) : 0; } - private static TransformedBounds transformedBounds(IrisObject object, ObjectSpinKernel spin, IrisBlockVector translation, + private static TransformedBounds transformedBounds(ObjectShape object, ObjectSpinKernel spin, IrisBlockVector translation, boolean ceilingHang, int margin) { - int[] sourceX = {-object.getCenter().getBlockX(), object.getW() - object.getCenter().getBlockX() - 1}; - int[] sourceY = {-object.getCenter().getBlockY(), object.getH() - object.getCenter().getBlockY() - 1}; - int[] sourceZ = {-object.getCenter().getBlockZ(), object.getD() - object.getCenter().getBlockZ() - 1}; + int[] sourceX = {-object.centerX(), object.width() - object.centerX() - 1}; + int[] sourceY = {-object.centerY(), object.height() - object.centerY() - 1}; + int[] sourceZ = {-object.centerZ(), object.depth() - object.centerZ() - 1}; int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; int minY = Integer.MAX_VALUE, maxY = Integer.MIN_VALUE; int minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java index 0dfe6050f..928a17015 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplace.java @@ -19,13 +19,9 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.core.modules.BlockEntities; -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.math.RNG; import com.volmit.block.BlockRegistry; -import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; import com.volmit.object.BlockEntityData; @@ -33,12 +29,12 @@ import java.util.List; import java.util.Optional; /** - * One {@link ObjectReplace} made ready for a pack: the blocks it finds resolved to the platform's, its palette - * picked through the pack's block registry with the seed of the {@link RNG} the placement hands in, and the tile - * data of the palette's entries resolved once. The old settings class cached the same things on itself. + * One {@link ObjectReplace} made ready for a pack: the blocks it finds resolved through the pack's block registry, its + * palette picked through the registry with the seed of the {@link RNG} the placement hands in, and the tile data of the + * palette's entries resolved once. The old settings class cached the same things on itself. */ final class ResolvedReplace { - private final List find; + private final List find; private final boolean exact; private final float chance; private final PaletteSpec replace; @@ -46,7 +42,7 @@ final class ResolvedReplace { private final List> entryTiles; private final int weightedSize; - ResolvedReplace(List find, boolean exact, float chance, PaletteSpec replace, BlockRegistry blocks) { + ResolvedReplace(List find, boolean exact, float chance, PaletteSpec replace, BlockRegistry blocks) { this.find = List.copyOf(find); this.exact = exact; this.chance = chance; @@ -57,9 +53,7 @@ final class ResolvedReplace { } static ResolvedReplace of(ObjectReplace settings, BlockRegistry blocks) { - List find = settings.find().stream() - .map(spec -> B.getState(blocks.resolve(spec).key())) - .toList(); + List find = settings.find().stream().map(blocks::resolve).toList(); return new ResolvedReplace(find, settings.exact(), settings.chance(), settings.replace(), blocks); } @@ -71,21 +65,20 @@ final class ResolvedReplace { return exact; } - List find() { + List find() { return find; } - PlatformBlockState replacement(RNG rng, double x, double y, double z) { - return B.getState(blocks.palette(replace, rng.getSeed()).at(x, y, z).key()); + BlockState replacement(RNG rng, double x, double y, double z) { + return blocks.palette(replace, rng.getSeed()).at(x, y, z); } /** The tile data of the entry picked for {@code rng}: the first entry when the palette's weights add up to one, else a uniform pick. */ - Optional tile(RNG rng) { + Optional tile(RNG rng) { if (weightedSize == 0) { return Optional.empty(); } - Optional entity = entryTiles.get(weightedSize == 1 ? 0 : pickedEntry(rng)); - return entity.map(BlockEntities::tileOf); + return entryTiles.get(weightedSize == 1 ? 0 : pickedEntry(rng)); } private int pickedEntry(RNG rng) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java index 1b1fd4ce4..27b9e24dc 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java @@ -19,33 +19,28 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.builtin.placement.PlacementTerrain; import com.volmit.block.BlockRegistry; +import com.volmit.stage.PlacementStageContext; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -/** The {@link ResolvedReplace}s of one engine runtime, one per decoded {@link ObjectReplace}, built when a placement first uses it. */ +/** The {@link ResolvedReplace}s of one pack's block registry, one per decoded {@link ObjectReplace}, built when a placement first uses it. */ final class ResolvedReplaces { private final BlockRegistry blocks; private final Map resolved = new ConcurrentHashMap<>(); - ResolvedReplaces(Engine engine) { - this(engine.getData().getPackResources().blocks()); - } - ResolvedReplaces(BlockRegistry blocks) { this.blocks = blocks; } - /** The replacements of the engine {@code data} serves, or of {@code data} alone when no engine runs it. */ - static ResolvedReplaces of(IrisData data) { - Engine engine = data.getEngine(); - if (engine == null) { - return new ResolvedReplaces(data.getPackResources().blocks()); + /** The replacements of the world {@code context} places in, or of the pack alone when the placement has no world. */ + static ResolvedReplaces of(PlacementStageContext context, PlacementTerrain terrain) { + if (!terrain.hasWorld()) { + return new ResolvedReplaces(context.resources().blocks()); } - return engine.getGeneration().state(ResolvedReplaces.class, ResolvedReplaces::new); + return context.world().state(ResolvedReplaces.class, world -> new ResolvedReplaces(world.resources().blocks())); } ResolvedReplace of(ObjectReplace settings) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java index 839c1ab0d..91aaa0461 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -20,11 +20,11 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; import com.volmit.placement.PlacedBlock; import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; @@ -32,6 +32,7 @@ import com.volmit.world.BlockPosition; import java.util.LinkedHashMap; import java.util.Map; +import java.util.stream.IntStream; /** * Module {@code iris:snow}: a random depth of snow on top of each column of the object, deeper the more @@ -39,6 +40,9 @@ import java.util.Map; */ public final class SnowModule implements IrisModule { private static final int LAYERS_PER_UNIT_OF_SNOW = 7; + private static final BlockState[] SNOW_LAYERS = IntStream.rangeClosed(1, 8) + .mapToObj(layers -> new BlockState("minecraft:snow").withProperty("layers", Integer.toString(layers))) + .toArray(BlockState[]::new); @Override public ModuleInfo info() { @@ -54,17 +58,18 @@ public final class SnowModule implements IrisModule { } private static void cover(PlacementStageContext context) { - double snow = context.output(IrisStages.Prepare.TRANSFORMS).config().getSnow(); + PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + double snow = prepared.settings().snow(); WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); if (!(snow > 0) || written.isEmpty()) { return; } - PlacementWorld world = new PlacementWorld(context.access(), IrisPlacement.current().states()); + PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); RNG rng = new RNG(context.random().nextLong()); - int maxLayer = IrisObject.States.SNOW_LAYERS.length - 1; + int maxLayer = SNOW_LAYERS.length - 1; for (BlockPosition top : columnTops(written).values()) { int layer = rng.i(0, (int) (snow * LAYERS_PER_UNIT_OF_SNOW)); - world.set(top.x(), top.y() + 1, top.z(), IrisObject.States.SNOW_LAYERS[Math.max(Math.min(layer, maxLayer), 0)]); + world.set(top.x(), top.y() + 1, top.z(), SNOW_LAYERS[Math.max(Math.min(layer, maxLayer), 0)]); } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 679b55010..6293d6176 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -18,19 +18,18 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.StiltShape; -import com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.anchor.StiltShape; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.stilt.StiltLayers; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; +import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import com.volmit.object.ObjectBlock; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; @@ -38,6 +37,7 @@ import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; import java.util.List; +import java.util.Optional; import java.util.Set; /** @@ -48,8 +48,9 @@ import java.util.Set; public final class StiltModule implements IrisModule { private static final Set SOIL_MATERIALS = Set.of("minecraft:grass_block", "minecraft:mycelium", "minecraft:podzol", "minecraft:dirt_path"); - private static final String SOIL_REPLACEMENT = "minecraft:dirt"; - private static final String WATERLOGGED = "waterlogged"; + private static final BlockState SOIL_REPLACEMENT = new BlockState("minecraft:dirt"); + private static final Set NO_STILT_SUFFIXES = Set.of("_stairs", "_slab"); + private static final String PATH_MATERIAL = "minecraft:dirt_path"; private static final long HASH_X = 341873128712L; private static final long HASH_Y = 132897987541L; private static final long HASH_Z = 735791245321L; @@ -67,11 +68,6 @@ public final class StiltModule implements IrisModule { return ModuleInfo.of("iris:stilt", "Stilts", PlacementModules.VERSION); } - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(StiltSettings.class); - } - @Override public void install(StageGraph graph) { graph.define(IrisStages.Stilt.LAYERS) @@ -90,12 +86,21 @@ public final class StiltModule implements IrisModule { return; } ObjectBlock block = context.block(); - if (!IrisObjectShaping.shouldStilt(IrisPlacement.current().states().toPlatform(block.state()))) { + if (!shouldStilt(prepared, block.state())) { return; } layers.include(new ObjectBlock(prepared.transform(block.position()), block.state(), block.blockEntity())); } + /** Whether the block is solid ground a stilt can repeat: not a stair, a slab or a path. */ + private static boolean shouldStilt(PreparedPlacement prepared, BlockState state) { + if (!prepared.traits().has(state, BlockTrait.OCCLUDING)) { + return false; + } + String material = state.material().toString(); + return NO_STILT_SUFFIXES.stream().noneMatch(material::endsWith) && !material.equals(PATH_MATERIAL); + } + private static void fill(PlacementStageContext context) { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); StiltShape shape = prepared.mode().stilt(); @@ -112,25 +117,27 @@ public final class StiltModule implements IrisModule { /** One placement's stilt, grown column by column under (or above) the blocks of its repeated layer. */ private static final class StiltColumns { - private final IrisPlacement placement; + private final ObjectPlacement placement; private final PreparedPlacement prepared; - private final IrisObjectPlacement config; + private final PlacementSettings config; private final StiltSettings settings; - private final PlatformBlockState palette; + private final BlockState palette; private final StiltShape shape; private final PlacementWorld world; + private final PlacementStageContext context; private final RNG rng; private final int anchorY; private final int layerY; private final ErodeShape erode; private StiltColumns(PlacementStageContext context, PreparedPlacement prepared, StiltLayers layers) { - this.placement = IrisPlacement.current(); + this.placement = ObjectPlacement.current(); this.prepared = prepared; - this.config = prepared.config(); - this.settings = config.getStiltSettings(); + this.context = context; + this.config = prepared.settings(); + this.settings = config.stilt().orElse(null); this.shape = prepared.mode().stilt(); - this.world = new PlacementWorld(context.access(), placement.states()); + this.world = new PlacementWorld(context.access(), prepared.traits()); this.rng = new RNG(context.random().nextLong()); this.anchorY = context.output(IrisStages.Anchor.FINAL).y(); this.palette = settings == null ? null : paletteBlock(settings); @@ -139,17 +146,17 @@ public final class StiltModule implements IrisModule { } /** The block the settings' palette picks for this placement, the same for every column; null without a palette. */ - private PlatformBlockState paletteBlock(StiltSettings stilt) { + private BlockState paletteBlock(StiltSettings stilt) { return stilt.palette() - .map(spec -> placement.data().getPackResources().blocks().palette(spec, rng.getSeed())) - .map(picker -> B.getState(picker.at(placement.x(), anchorY, placement.z()).key())) + .map(spec -> context.resources().blocks().palette(spec, rng.getSeed())) + .map(picker -> picker.at(placement.x(), anchorY, placement.z())) .orElse(null); } private void grow(ObjectBlock block) { BlockPosition offset = block.position(); - PlatformBlockState state = stiltState(block, offset); - if (state == null || !state.isOccluding()) { + BlockState state = stiltState(block, offset); + if (!world.has(state, BlockTrait.OCCLUDING)) { return; } int x = placement.x() + offset.x(); @@ -168,27 +175,27 @@ public final class StiltModule implements IrisModule { } /** The block the stilt repeats: the palette's when the settings have one, soil turned to dirt, edited and turned with the object. */ - private PlatformBlockState stiltState(ObjectBlock block, BlockPosition offset) { - PlatformBlockState state = placement.states().toPlatform(block.state()); + private BlockState stiltState(ObjectBlock block, BlockPosition offset) { + BlockState state = block.state(); if (palette != null) { state = palette; - } else if (SOIL_MATERIALS.contains(IrisObjectShaping.materialKey(state))) { - state = B.getState(SOIL_REPLACEMENT); + } else if (SOIL_MATERIALS.contains(state.material().toString())) { + state = SOIL_REPLACEMENT; } state = prepared.rotate(state); - if (config.getEdit().isEmpty() || state == null) { + if (config.edit().isEmpty()) { return state; } - return ObjectEdits.apply(config, state, null, rng, offset.x() + placement.x(), offset.y() + anchorY, - offset.z() + placement.z(), placement.data()).data(); + return ObjectEdits.apply(config.edit(), state, Optional.empty(), rng, offset.x() + placement.x(), offset.y() + anchorY, + offset.z() + placement.z(), ResolvedReplaces.of(context, prepared.terrain()), placement).data(); } - private void growToSurface(PlatformBlockState state, BlockPosition offset, int x, int z) { + private void growToSurface(BlockState state, BlockPosition offset, int x, int z) { int top = layerY + anchorY; - int highest = prepared.terrain().getHighest(x, z, placement.object().getLoader(), true); - if (IrisProceduralBlocks.hasProperty(state, WATERLOGGED) + int highest = prepared.terrain().highest(x, z, true); + if (state.properties().containsKey(BlocksModule.WATERLOGGED) && BlocksModule.shouldWaterlog(world, config, placement.requestedY(), x, highest, z)) { - state = state.withProperty(WATERLOGGED, "true"); + state = state.withProperty(BlocksModule.WATERLOGGED, BlocksModule.TRUE); } int lowerBound = highest - 1; if (settings != null) { @@ -201,13 +208,13 @@ public final class StiltModule implements IrisModule { lowerBound = top - erode.depth(offset, top - lowerBound); } for (int y = top; y > lowerBound; y--) { - if (B.isFluid(world.get(x, y, z))) { + if (world.has(world.get(x, y, z), BlockTrait.FLUID)) { return; } if (erode != null && erode.breaksAt(x, y, z, top - y, top - lowerBound)) { continue; } - if (B.isVineBlock(state)) { + if (world.has(state, BlockTrait.VINE)) { state = BlocksModule.attachVineFaces(world, state, x, y, z); } world.set(x, y, z, state); @@ -215,7 +222,7 @@ public final class StiltModule implements IrisModule { } /** Grows from the layer toward the first solid block in {@code direction}, -1 down or 1 up. */ - private void growOrganic(PlatformBlockState state, int x, int z, int direction) { + private void growOrganic(BlockState state, int x, int z, int direction) { int maxScan = settings != null ? Math.max(1, settings.organicMaxScan()) : DEFAULT_ORGANIC_MAX_SCAN; int jitterMax = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; double scratch = settings != null ? Math.max(0, Math.min(1, settings.organicScratch())) : DEFAULT_ORGANIC_SCRATCH; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 35d1b7cb6..aaca1167a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -18,20 +18,19 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.anchor.VacuumProfile; -import com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.anchor.VacuumProfile; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.terrain.TerrainPalettes; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.noise.SimplexNoise; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.placement.PlaneNoise; +import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.builtin.vacuum.VacuumSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; @@ -46,17 +45,14 @@ public final class VacuumModule implements IrisModule { private static final long HASH_Z = 132897987541L; private static final int HASH_BUCKETS = 1000; private static final double HALF = 0.5; + private static final BlockState STONE = new BlockState("minecraft:stone"); + private static final BlockState AIR = new BlockState("minecraft:cave_air"); @Override public ModuleInfo info() { return ModuleInfo.of("iris:vacuum", "Vacuum", PlacementModules.VERSION); } - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(VacuumSettings.class); - } - @Override public void install(StageGraph graph) { graph.define(IrisStages.Vacuum.TERRAIN) @@ -68,47 +64,46 @@ public final class VacuumModule implements IrisModule { private static void bendTerrain(PlacementStageContext context) { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); - Engine engine = prepared.terrain().getEngine(); - if (!prepared.mode().bendsTerrain() || written.isEmpty() || engine == null) { + if (!prepared.mode().bendsTerrain() || written.isEmpty() || !prepared.terrain().hasWorld()) { return; } int baseY = written.blocks().stream().mapToInt(block -> block.position().y()).min().orElseThrow(); int topY = written.blocks().stream().mapToInt(block -> block.position().y()).max().orElseThrow(); - new Bend(context, prepared, engine).apply(baseY, topY); + new Bend(context, prepared).apply(baseY, topY); } /** One placement's terrain bend over the columns within its radius of the object's footprint. */ private static final class Bend { - private final IrisPlacement placement; + private final ObjectPlacement placement; private final PreparedPlacement prepared; + private final PlacementTerrain terrain; private final PlacementWorld world; - private final TerrainPalettes palettes; private final int radius; private final int step; private final double falloff; private final int jitter; private final double waveAmplitude; private final double waveScale; - private final SimplexNoise waves; + private final PlaneNoise waves; private final int lowestY; private final int highestY; - private Bend(PlacementStageContext context, PreparedPlacement prepared, Engine engine) { + private Bend(PlacementStageContext context, PreparedPlacement prepared) { VacuumProfile vacuum = prepared.mode().vacuum(); - this.placement = IrisPlacement.current(); + this.placement = ObjectPlacement.current(); this.prepared = prepared; - this.world = new PlacementWorld(context.access(), placement.states()); - this.palettes = engine.getComplex() == null ? null : TerrainPalettes.of(engine); - VacuumSettings settings = prepared.config().getVacuumSettings(); + this.terrain = prepared.terrain(); + this.world = new PlacementWorld(context.access(), prepared.traits()); + VacuumSettings settings = prepared.settings().vacuum().orElse(null); this.radius = IrisObjectVacuum.resolveRadius(vacuum, settings); this.step = vacuum.columnStepBlocks(); this.falloff = IrisObjectVacuum.resolveFalloff(settings); this.jitter = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); - this.waves = vacuum.edge() == VacuumProfile.Edge.WAVY && waveAmplitude > 0 ? new SimplexNoise(WAVE_SEED) : null; + this.waves = vacuum.edge() == VacuumProfile.Edge.WAVY && waveAmplitude > 0 ? placement.simplex(WAVE_SEED) : null; this.lowestY = IrisObjectVacuum.LOWEST_TARGET_Y; - this.highestY = engine.getHeight() - 1; + this.highestY = terrain.worldHeight() - 1; } private void apply(int baseY, int topY) { @@ -124,7 +119,7 @@ public final class VacuumModule implements IrisModule { int x = placement.x() + dx; int z = placement.z() + dz; double effectiveRadius = effectiveRadius(x, z); - int originalY = prepared.terrain().getHighest(x, z, placement.object().getLoader(), true); + int originalY = terrain.highest(x, z, true); int targetY = IrisObjectVacuum.columnTargetY(dx, dz, bounds.minX(), bounds.maxX(), bounds.minZ(), bounds.maxZ(), effectiveRadius, falloff, originalY, meetY) + waveOffset(bounds, dx, dz, x, z, effectiveRadius); if (targetY == originalY) { @@ -157,13 +152,13 @@ public final class VacuumModule implements IrisModule { int outX = IrisObjectVacuum.outset(dx, bounds.minX(), bounds.maxX()); int outZ = IrisObjectVacuum.outset(dz, bounds.minZ(), bounds.maxZ()); double distance = Math.sqrt((double) (outX * outX) + (double) (outZ * outZ)); - return IrisObjectVacuum.waveOffset(distance, effectiveRadius, waves.noiseSigned(x * waveScale, z * waveScale), waveAmplitude); + return IrisObjectVacuum.waveOffset(distance, effectiveRadius, waves.signed(x * waveScale, z * waveScale), waveAmplitude); } private void raise(int x, int z, int fromY, int toY) { - PlatformBlockState fill = palettes != null ? palettes.rockAt(x, z) : null; - if (B.isAir(fill)) { - fill = IrisObject.States.STONE; + BlockState fill = terrain.rockAt(x, z); + if (world.has(fill, BlockTrait.AIR)) { + fill = STONE; } for (int y = fromY + 1; y <= toY; y++) { world.set(x, y, z, fill); @@ -172,7 +167,7 @@ public final class VacuumModule implements IrisModule { private void carve(int x, int z, int fromY, int floorY) { for (int y = fromY; y >= floorY; y--) { - world.set(x, y, z, IrisObject.States.AIR); + world.set(x, y, z, AIR); } } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index d73057b02..cdb7cd885 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,17 +18,16 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisPlacement; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.NativeStructureVolume; -import art.arcane.iris.engine.framework.PlacedObject; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.builtin.placement.CaveSpace; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.placement.ObjectShape; +import art.arcane.iris.builtin.placement.PlacementSettings; +import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.builtin.placement.StructureVolumes; +import art.arcane.iris.builtin.prepare.PreparedPlacement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; @@ -38,6 +37,7 @@ import com.volmit.stage.PlacementStageContext; import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; +import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -56,11 +56,6 @@ public final class ValidateModule implements IrisModule { return ModuleInfo.of("iris:validate", "Placement checks", PlacementModules.VERSION); } - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(ObjectLimit.class); - } - @Override public void install(StageGraph graph) { graph.define(IrisStages.Validate.SURFACE) @@ -78,59 +73,59 @@ public final class ValidateModule implements IrisModule { } private static void checkSurface(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); - if (config.isForcePlace() || config.isFromBottom() || prepared.mode().has(PlaceTrait.FREE_HEIGHT)) { + PlacementSettings settings = prepared.settings(); + if (settings.forcePlace() || settings.fromBottom() || prepared.mode().has(PlaceTrait.FREE_HEIGHT)) { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y(); boolean sampled = placement.requestedY() < 0; - if (sampled && config.getCarvingSupport().supportsSurface() && isOnBedrock(prepared, y)) { - warnImplausibleBedrockPlacement(placement, config, y, context.log()); + if (sampled && settings.carvingSupport().supportsSurface() && isOnBedrock(prepared, y)) { + warnImplausibleBedrockPlacement(placement, settings, y, context.log()); context.reject("bedrock-anchor"); return; } - boolean surfaceAnchored = sampled ? config.getCarvingSupport().supportsSurface() - : config.getCarvingSupport() == CarvingMode.SURFACE_ONLY; - if (surfaceAnchored && !config.isUnderwater() && !config.isOnwater() && config.isRequireSurfaceSupport() + boolean surfaceAnchored = sampled ? settings.carvingSupport().supportsSurface() + : settings.carvingSupport() == CarvingMode.SURFACE_ONLY; + if (surfaceAnchored && !settings.underwater() && !settings.onwater() && settings.requireSurfaceSupport() && lacksSurfaceSupport(placement, prepared)) { context.reject("surface-support"); } } private static boolean isOnBedrock(PreparedPlacement prepared, int y) { - Engine engine = prepared.terrain().getEngine(); - return engine != null && engine.getDimension().isBedrock() && y <= BEDROCK_ROW; + PlacementTerrain terrain = prepared.terrain(); + return terrain.hasWorld() && terrain.hasBedrock() && y <= BEDROCK_ROW; } - private static boolean lacksSurfaceSupport(IrisPlacement placement, PreparedPlacement prepared) { - IrisObjectPlacement config = prepared.config(); - IrisObject object = placement.object(); - return IrisSurfaceSupport.isUnsupported(placement.placer(), object.getLoader(), placement.x(), placement.z(), - config.getTranslate(), config.getRotation(), prepared.spinX(), prepared.spinY(), prepared.spinZ(), - object.getSurfaceSupportOffsets(), config.getSurfaceSupportBuffer(), config.getSurfaceSupportDepth()); + private static boolean lacksSurfaceSupport(ObjectPlacement placement, PreparedPlacement prepared) { + PlacementSettings settings = prepared.settings(); + return IrisSurfaceSupport.isUnsupported(prepared.terrain(), placement.x(), placement.z(), settings.translate(), + prepared.rotation(), prepared.spinX(), prepared.spinY(), prepared.spinZ(), + placement.object().surfaceSupportOffsets(), settings.surfaceSupportBuffer(), settings.surfaceSupportDepth()); } private static void checkLimits(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); - if (config.isForcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP)) { + PlacementSettings settings = prepared.settings(); + if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP)) { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y(); int rotated = prepared.rotatedCenterY(); int translated = prepared.translatedCenterY(); - if (placement.requestedY() < 0 && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !config.isUnderwater() - && !config.isOnwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) { + Optional cave = placement.cave(); + if (placement.requestedY() < 0 && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !settings.underwater() + && !settings.onwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) { context.reject("underwater-anchor"); - } else if (placement.cave() != null - && Math.max(0, placement.object().h + prepared.randomY() + translated) + 1 >= placement.cave().getHeight()) { + } else if (cave.isPresent() + && Math.max(0, placement.object().height() + prepared.randomY() + translated) + 1 >= cave.get().height()) { context.reject("cave-clearance"); - } else if (config.isUnderwater() && y + rotated + translated >= prepared.terrain().getFluidHeight()) { + } else if (settings.underwater() && y + rotated + translated >= prepared.terrain().fluidHeight()) { context.reject("fluid-height"); - } else if (!config.getClamp().canPlace(y + rotated + translated, y - rotated + translated)) { + } else if (!settings.clamp().canPlace(y + rotated + translated, y - rotated + translated)) { context.reject("height-clamp"); } } @@ -141,31 +136,29 @@ public final class ValidateModule implements IrisModule { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY(); - if (meetsNativeStructure(context, IrisPlacement.current(), prepared, y)) { + if (meetsNativeStructure(context, ObjectPlacement.current(), prepared, y)) { context.reject("native-structure"); } } - private static boolean meetsNativeStructure(PlacementStageContext context, IrisPlacement placement, + private static boolean meetsNativeStructure(PlacementStageContext context, ObjectPlacement placement, PreparedPlacement prepared, int y) { - Engine engine = prepared.terrain().getEngine(); - if (engine == null) { + PlacementTerrain terrain = prepared.terrain(); + if (!terrain.hasWorld()) { return false; } int x = placement.x(); int z = placement.z(); int margin = nativeStructureMargin(placement.object(), prepared); - KList volumes = engine.getNativeStructureVolumes(x - margin, z - margin, x + margin, z + margin); - if (volumes == null || volumes.isEmpty()) { + StructureVolumes volumes = terrain.structureVolumes(x - margin, z - margin, x + margin, z + margin); + if (volumes.isEmpty()) { return false; } boolean painted = WorldVolume.isPainted(placement, prepared); - int worldY = y + engine.getMinHeight(); + int worldY = y + terrain.minHeight(); int envelopeMinY = painted ? Integer.MIN_VALUE : worldY - margin; int envelopeMaxY = painted ? Integer.MAX_VALUE : worldY + margin; - boolean envelopeMeetsPiece = volumes.stream() - .anyMatch(volume -> volume.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)); - if (!envelopeMeetsPiece) { + if (!volumes.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { return false; } for (ObjectBlock block : context.request().object().blocks()) { @@ -176,22 +169,20 @@ public final class ValidateModule implements IrisModule { int blockX = x + offset.x(); int blockZ = z + offset.z(); int blockY = painted - ? offset.y() + Math.floorDiv(placement.object().h, 2) - + prepared.terrain().getHighest(blockX, blockZ, placement.object().getLoader(), prepared.config().isUnderwater()) + ? offset.y() + Math.floorDiv(placement.object().height(), 2) + + terrain.highest(blockX, blockZ, prepared.settings().underwater()) : y + offset.y(); - int worldBlockY = blockY + engine.getMinHeight(); - for (NativeStructureVolume volume : volumes) { - if (volume.containsWithin(blockX, worldBlockY, blockZ, prepared.warpMargin())) { - return true; - } + int worldBlockY = blockY + terrain.minHeight(); + if (volumes.containsWithin(blockX, worldBlockY, blockZ, prepared.warpMargin())) { + return true; } } return false; } /** How far around the anchor any block of the transformed object can reach. */ - private static int nativeStructureMargin(IrisObject object, PreparedPlacement prepared) { - int margin = (Math.max(object.getW(), Math.max(object.getH(), object.getD())) / 2) + 1 + prepared.warpMargin(); + private static int nativeStructureMargin(ObjectShape object, PreparedPlacement prepared) { + int margin = (Math.max(object.width(), Math.max(object.height(), object.depth())) / 2) + 1 + prepared.warpMargin(); if (prepared.translation() == null) { return margin; } @@ -204,33 +195,25 @@ public final class ValidateModule implements IrisModule { } private static void checkCollisions(PlacementStageContext context) { - IrisPlacement placement = IrisPlacement.current(); + ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - IrisObjectPlacement config = prepared.config(); - if (config.isForcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP) - || (config.getAllowedCollisions().isEmpty() && config.getForbiddenCollisions().isEmpty())) { + PlacementSettings settings = prepared.settings(); + if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP) + || (settings.allowedCollisions().isEmpty() && settings.forbiddenCollisions().isEmpty())) { return; } - Engine engine = placement.data().getEngine(); - if (engine == null) { - throw new IllegalStateException("Object placement requires active Iris data for collision settings."); - } WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY()); - if (collidesWithForbiddenObject(engine, config, volume)) { + if (collidesWithForbiddenObject(prepared.terrain(), settings, volume)) { context.reject("object-collision"); } } - private static boolean collidesWithForbiddenObject(Engine engine, IrisObjectPlacement config, WorldVolume volume) { + private static boolean collidesWithForbiddenObject(PlacementTerrain terrain, PlacementSettings settings, WorldVolume volume) { for (int x = volume.minX(); x <= volume.maxX(); x++) { for (int y = volume.minY(); y <= volume.maxY(); y++) { for (int z = volume.minZ(); z <= volume.maxZ(); z++) { - PlacedObject placed = engine.getObjectPlacement(x, y, z); - if (placed == null || placed.getObject() == null) { - continue; - } - String key = placed.getObject().getLoadKey(); - if (key != null && config.getForbiddenCollisions().contains(key) && !config.getAllowedCollisions().contains(key)) { + String key = terrain.objectKeyAt(x, y, z); + if (key != null && settings.forbiddenCollisions().contains(key) && !settings.allowedCollisions().contains(key)) { return true; } } @@ -239,9 +222,9 @@ public final class ValidateModule implements IrisModule { return false; } - private static void warnImplausibleBedrockPlacement(IrisPlacement placement, IrisObjectPlacement config, int y, ModuleLog log) { - String key = placement.object().getLoadKey(); - String fingerprint = (key == null ? "" : key) + "|" + config.getMode(); + private static void warnImplausibleBedrockPlacement(ObjectPlacement placement, PlacementSettings settings, int y, ModuleLog log) { + String key = placement.object().key(); + String fingerprint = (key == null ? "" : key) + "|" + settings.mode(); long now = System.currentTimeMillis(); Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); if (last != null && now - last < IMPLAUSIBLE_BEDROCK_WARN_THROTTLE_MS) { @@ -250,8 +233,8 @@ public final class ValidateModule implements IrisModule { IMPLAUSIBLE_BEDROCK_WARNS.put(fingerprint, now); log.warn("Implausible object placement rejected: " + (key == null ? "" : key) - + " resolved anchorY=" + y + " at (" + placement.x() + "," + placement.z() + ") mode=" + config.getMode() - + " carving=" + config.getCarvingSupport() + + " resolved anchorY=" + y + " at (" + placement.x() + "," + placement.z() + ") mode=" + settings.mode() + + " carving=" + settings.carvingSupport() + ". Surface-anchored placement should never land on the bedrock row. " + "Height sampling returned a bogus value — not configured for floor placement " + "(forcePlace=false, fromBottom=false, mode!=FLOATING). Skipping to protect bedrock."); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java index d23d77bbb..ee170f8c4 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java @@ -19,14 +19,16 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.anchor.AnchorSampling; -import art.arcane.iris.core.modules.IrisPlacement; +import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.prepare.TransformedBounds; /** * The world blocks a placed object occupies, inclusive: its transformed bounds around the anchor. A painted * object follows the surface column by column, so its volume spans every surface height under it. */ record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { - static WorldVolume of(IrisPlacement placement, PreparedPlacement prepared, int anchorY) { + static WorldVolume of(ObjectPlacement placement, PreparedPlacement prepared, int anchorY) { TransformedBounds bounds = prepared.bounds(); int minX = placement.x() + bounds.minX(); int maxX = placement.x() + bounds.maxX(); @@ -39,18 +41,18 @@ record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { int highestSurface = Integer.MIN_VALUE; for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { - int surface = prepared.terrain().getHighest(x, z, placement.object().getLoader(), prepared.config().isUnderwater()); + int surface = prepared.terrain().highest(x, z, prepared.settings().underwater()); lowestSurface = Math.min(lowestSurface, surface); highestSurface = Math.max(highestSurface, surface); } } - int paintOffset = Math.floorDiv(placement.object().h, 2); + int paintOffset = Math.floorDiv(placement.object().height(), 2); return new WorldVolume(minX, maxX, lowestSurface + bounds.minY() + paintOffset, highestSurface + bounds.maxY() + paintOffset, minZ, maxZ); } /** Whether each block of the placement follows the surface of its own column. */ - static boolean isPainted(IrisPlacement placement, PreparedPlacement prepared) { + static boolean isPainted(ObjectPlacement placement, PreparedPlacement prepared) { return placement.requestedY() < 0 && prepared.mode().anchor() == AnchorSampling.SURFACE; } } From 3ac31c573b924ac2f2af6277520c3192d8225576 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:18:10 +0200 Subject: [PATCH 077/139] iris:decorant ported onto IrisApi and listed in the built-ins jar; decorate becomes a dimension setting --- builtin-modules.txt | 2 + .../builtin/decorant/DecorateSettings.java | 38 ++ .../iris/builtin/decorant/DecoratorLoad.java | 52 +++ .../iris/engine/actuator/DecorantModule.java | 144 +++----- .../engine/decorator/BiomeDecorators.java | 132 +++---- .../iris/engine/decorator/DecoratedBiome.java | 28 ++ .../engine/decorator/DecorationScene.java | 149 ++++++++ .../iris/engine/decorator/DecoratorCore.java | 330 ++++++++---------- .../decorator/DecoratorPlatformHooks.java | 62 ---- .../engine/decorator/FloatingDecorator.java | 21 +- .../decorator/IrisCeilingDecorator.java | 38 +- .../engine/decorator/IrisEngineDecorator.java | 50 ++- .../decorator/IrisSeaFloorDecorator.java | 42 +-- .../decorator/IrisSeaSurfaceDecorator.java | 39 +-- .../decorator/IrisShoreLineDecorator.java | 61 ++-- .../decorator/IrisSurfaceDecorator.java | 53 +-- .../engine/decorator/ResolvedDecorator.java | 88 +++-- .../iris/engine/modifier/CarveModule.java | 2 +- .../iris/engine/modifier/CaveApplying.java | 30 +- .../iris/engine/modifier/FloatingIslands.java | 11 +- .../iris/engine/modifier/FloatingModule.java | 7 +- .../engine/modifier/IrisCarveScratch.java | 3 + .../engine/modifier/IrisDecoratedBiomes.java | 33 ++ .../world/biome/IrisBiomeColorRenderer.java | 14 +- .../object/world/dimension/IrisDimension.java | 2 - 25 files changed, 778 insertions(+), 653 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java create mode 100644 src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java delete mode 100644 src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 7691fee17..657dd5fba 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -22,3 +22,5 @@ module art.arcane.iris.engine.modifier.DepositModule include art/arcane/iris/engine/modifier/DepositPlacer*.class include art/arcane/iris/engine/modifier/DepositClump*.class include art/arcane/iris/engine/modifier/ResolvedDeposit*.class +module art.arcane.iris.engine.actuator.DecorantModule +include art/arcane/iris/engine/decorator/** diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java new file mode 100644 index 000000000..bdcaf244c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java @@ -0,0 +1,38 @@ +/* + * 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.builtin.decorant; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension decorates at all, written as {@code "decorate": false}. A dimension without the key decorates. */ +@Desc("Generate decorations or not") +@Feature(id = "iris:decorant/decorate", name = "Decorate", key = "decorate", root = "decorate", targets = Target.DIMENSION) +public final class DecorateSettings implements IrisFeature { + @Desc("Generate decorations or not") + private boolean decorate = true; + + public DecorateSettings() { + } + + public boolean decorate() { + return decorate; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java b/src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java new file mode 100644 index 000000000..a73ef0c18 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java @@ -0,0 +1,52 @@ +/* + * 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.builtin.decorant; + +/** How loaded with decorating a biome is, which studio's decorator load view colours it by. */ +public final class DecoratorLoad { + private static final int COLUMNS_PER_CHUNK = 256; + + private DecoratorLoad() { + } + + /** The sum of the decorators' chances times their stack heights, at least one block each; 0 for a biome without decorators. */ + public static double of(DecorantSettings settings) { + if (settings == null) { + return 0D; + } + + double load = 0D; + for (Decorator decorator : settings.decorators()) { + load += Math.max(decorator.stackMax(), 1) * decorator.chance(); + } + return load; + } + + /** The sum of the decorators' chances over a chunk's columns, which is how strongly the view colours the biome. */ + public static double colour(DecorantSettings settings) { + if (settings == null) { + return 0D; + } + + double load = 0D; + for (Decorator decorator : settings.decorators()) { + load += decorator.chance() * Math.min(1, decorator.stackMax()) * COLUMNS_PER_CHUNK; + } + return load; + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index a86b1b286..9c5499e39 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -19,40 +19,36 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.core.modules.IrisPackWorld; +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorateSettings; import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineDecorator; -import art.arcane.iris.builtin.decorant.DecorantSettings; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.hunk.Hunk; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; +import com.volmit.world.BiomeKind; import com.volmit.world.PackWorld; - -import java.util.function.Predicate; +import com.volmit.world.TerrainSampler; /** * Module {@code iris:decorant}: the biomes' decorators ({@link DecorantSettings}), placed on the surface the mantle's * blocks left: the surface itself, the sea surface and floor, and the shore line. A dimension turns decorating off with - * {@code decorate}. The decorators' noise is built ahead of generation, in {@link #warmUp}. + * {@link DecorateSettings}. The decorators' noise is built ahead of generation, in {@link #warmUp}. */ public final class DecorantModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; + private static final int CHUNK_CENTRE = 7; @Override public ModuleInfo info() { @@ -62,6 +58,7 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { @Override public void register(FeatureRegistry registry) { registry.registerSettings(DecorantSettings.class); + registry.registerSettings(DecorateSettings.class); registry.registerLifecycle(this); } @@ -77,87 +74,62 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { } private static void decorate(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - decorating(context.world()).decorate(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); + if (!decorates(context)) { + return; + } + decorate(DecorationScene.of(context), context.settings(), context.originX(), context.originZ()); } - /** The world's decorating, kept in its state store. */ - static Decorating decorating(PackWorld world) { - return world.state(Decorating.class, Decorating::new); + /** A dimension decorates unless it says {@code decorate: false}. */ + private static boolean decorates(ChunkStageContext context) { + return context.settings().at(DecorateSettings.class, context.originX() + CHUNK_CENTRE, context.originZ() + CHUNK_CENTRE).stream() + .allMatch(entry -> entry.value().decorate()); } - /** What decorating keeps for one world: one decorator per kind of place. */ - static final class Decorating { - private static final Predicate PREDICATE_SOLID = (s) -> s != null && !B.isAirOrFluid(s); + /** Decorates the 16 x 16 columns of the chunk whose first block is {@code x}, {@code z}, a biome's decorators on the surface its blocks left. */ + static void decorate(DecorationScene scene, FeatureSettings settings, int x, int z) { + Hunk output = scene.blocks(); + TerrainSampler terrain = scene.terrain(); + BiomeDecorators decorators = scene.decorators(); + IrisSurfaceDecorator surfaceDecorator = new IrisSurfaceDecorator(scene); + IrisSeaSurfaceDecorator seaSurfaceDecorator = new IrisSeaSurfaceDecorator(scene); + IrisSeaFloorDecorator seaFloorDecorator = new IrisSeaFloorDecorator(scene); + IrisShoreLineDecorator shoreLineDecorator = new IrisShoreLineDecorator(scene); + int fluidHeight = scene.fluidHeight(); + int worldHeight = scene.worldHeight(); - private final Engine engine; - private final BiomeDecorators decorators; - private final IrisSurfaceDecorator surfaceDecorator; - private final EngineDecorator seaSurfaceDecorator; - private final EngineDecorator seaFloorDecorator; - private final EngineDecorator shoreLineDecorator; + for (int i = 0; i < output.getWidth(); i++) { + int realX = Math.round(x + i); + for (int j = 0; j < output.getDepth(); j++) { + int realZ = Math.round(z + j); + DecoratedBiome biome = BiomeDecorators.biomeOf(settings, realX, realZ, terrain.surfaceKind(realX, realZ)); + if (!decorators.hasDecorators(biome)) { + continue; + } + int height = (int) Math.round(terrain.surfaceY(realX, realZ)); - Decorating(PackWorld world) { - this(IrisPackWorld.of(world).engine()); - } + if (height >= 0 && height < fluidHeight && scene.isSolid(output.get(i, height, j)) + && height + 1 < output.getHeight() && scene.isWater(output.get(i, height + 1, j))) { + seaSurfaceDecorator.decorate(i, j, + realX, Math.round(i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + biome, fluidHeight, worldHeight); + seaFloorDecorator.decorate(i, j, + realX, realZ, biome, height + 1, + fluidHeight + 1); + } - Decorating(Engine engine) { - this.engine = engine; - decorators = BiomeDecorators.of(engine); - surfaceDecorator = new IrisSurfaceDecorator(engine); - seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); - shoreLineDecorator = new IrisShoreLineDecorator(engine); - seaFloorDecorator = new IrisSeaFloorDecorator(engine); - } + if (height == fluidHeight) { + shoreLineDecorator.decorate(i, j, + realX, Math.round(x + i + 1), Math.round(x + i - 1), + realZ, Math.round(z + j + 1), Math.round(z + j - 1), + biome, height, worldHeight); + } - /** Decorates the 16 x 16 columns of the chunk whose first block is {@code x}, {@code z}, a biome's decorators on the surface its blocks left. */ - @BlockCoordinates - void decorate(int x, int z, Hunk output, ChunkContext context) { - if (!engine.getDimension().isDecorate()) { - return; - } - - PrecisionStopwatch p = PrecisionStopwatch.start(); - - for (int i = 0; i < output.getWidth(); i++) { - int height; - int realX = Math.round(x + i); - int realZ; - IrisBiome biome; - for (int j = 0; j < output.getDepth(); j++) { - realZ = Math.round(z + j); - height = context.getRoundedHeight(i, j); - biome = context.getBiome().get(i, j); - - if (!decorators.hasDecorators(biome)) { - continue; - } - - if (height < engine.getDimension().getFluidHeight() && PREDICATE_SOLID.test(output.get(i, height, j)) - && height + 1 < output.getHeight() && B.isWater(output.get(i, height + 1, j))) { - seaSurfaceDecorator.decorate(i, j, - realX, Math.round(i + 1), Math.round(x + i - 1), - realZ, Math.round(z + j + 1), Math.round(z + j - 1), - output, biome, engine.getDimension().getFluidHeight(), engine.getHeight()); - seaFloorDecorator.decorate(i, j, - realX, realZ, output, biome, height + 1, - engine.getDimension().getFluidHeight() + 1); - } - - if (height == engine.getDimension().getFluidHeight()) { - shoreLineDecorator.decorate(i, j, - realX, Math.round(x + i + 1), Math.round(x + i - 1), - realZ, Math.round(z + j + 1), Math.round(z + j - 1), - output, biome, height, engine.getHeight()); - } - - if (height >= 0 && height < output.getHeight()) { - surfaceDecorator.decorate(i, j, realX, realZ, output, biome, height, engine.getHeight() - height); - } + if (height >= 0 && height < output.getHeight()) { + surfaceDecorator.decorate(i, j, realX, realZ, biome, height, worldHeight - height); } } - - engine.getMetrics().getDecoration().put(p.getMilliseconds()); } } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java index e38734947..0a346f27a 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java +++ b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -15,16 +15,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.decorant.Decorator; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.config.FeatureSettings; import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import java.util.ArrayList; @@ -35,41 +36,30 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** - * What the decorant module keeps for one world: the decorators of its biomes made ready ({@link ResolvedDecorator}), - * sorted into the places they decorate, and how loaded the busiest biome is. Built from the biomes' {@link DecorantSettings} - * when first asked for, or ahead of generation by {@link #warm()}. + * What the decorant module keeps for one world: the decorators of its biomes made ready ({@link ResolvedDecorator}), sorted into + * the places they decorate. Built from the biomes' {@link DecorantSettings} when first asked for, or ahead of generation by + * {@link #warm()}. * *

A decorator's noise seed is a function of the world's decorator seed, its biome's key and its place in the biome's * list, so it does not depend on which column or which warm-up reached it first. */ public final class BiomeDecorators { private static final ResolvedDecorator[] NO_DECORATORS = new ResolvedDecorator[0]; - private static final int COLUMNS_PER_CHUNK = 256; + private static final String BIOME_PATH_PREFIX = "biome/"; private static final long KEY_SEED_FACTOR = 0x9E3779B97F4A7C15L; private static final long INDEX_SEED_FACTOR = 0xC2B2AE3D27D4EB4FL; - private final Engine engine; + private final PackWorld world; + private final PackResources resources; private final ModuleLog log; + private final long decoratorSeed; private final Map> decorators = new ConcurrentHashMap<>(); - private volatile Double busiestBiomeLoad; - /** @param world a world of an Iris engine */ BiomeDecorators(PackWorld world) { - this(IrisPackWorld.of(world).engine(), world.log()); - } - - BiomeDecorators(Engine engine) { - this(engine, engine.getGeneration().world().log()); - } - - BiomeDecorators(Engine engine, ModuleLog log) { - this.engine = engine; - this.log = log; - } - - /** The world {@code engine} generates now. */ - public static BiomeDecorators of(Engine engine) { - return engine.getGeneration().state(BiomeDecorators.class, BiomeDecorators::new); + this.world = world; + this.resources = world.resources(); + this.log = world.log(); + this.decoratorSeed = IrisSeed.DECORATOR.of(world); } /** The world's decorators, kept in its state store. */ @@ -77,36 +67,51 @@ public final class BiomeDecorators { return world.state(BiomeDecorators.class, BiomeDecorators::new); } + /** The key of the biome a settings entry was declared by, such as {@code desert/dunes} for {@code overworld:biome/desert/dunes}. */ + public static String biomeKey(ResourceId source) { + String path = source.path(); + return path.startsWith(BIOME_PATH_PREFIX) ? path.substring(BIOME_PATH_PREFIX.length()) : path; + } + + /** The biome of the entry a column's settings gave, which is the column's surface biome; null when the biome declares nothing. */ + public static DecoratedBiome biomeOf(FeatureSettings settings, int worldX, int worldZ, com.volmit.world.BiomeKind kind) { + List> entries = settings.at(DecorantSettings.class, worldX, worldZ); + if (entries.isEmpty()) { + return null; + } + Entry entry = entries.getLast(); + return new DecoratedBiome(biomeKey(entry.source()), entry.value(), kind); + } + /** The log of the module that decorates, which the decorators write to. */ ModuleLog log() { return log; } /** Whether the biome declares any decorator. */ - public boolean hasDecorators(IrisBiome biome) { - DecorantSettings settings = settingsOf(biome); - return settings != null && !settings.decorators().isEmpty(); + public boolean hasDecorators(DecoratedBiome biome) { + return biome != null && biome.settings() != null && !biome.settings().decorators().isEmpty(); } /** The biome's decorators for {@code part}, in the order the biome lists them. */ - ResolvedDecorator[] decorators(IrisBiome biome, DecorationPart part) { - DecorantSettings settings = settingsOf(biome); - if (settings == null) { + ResolvedDecorator[] decorators(DecoratedBiome biome, DecorationPart part) { + if (biome == null || biome.settings() == null) { return NO_DECORATORS; } - return decorators.computeIfAbsent(settings, declared -> resolve(biome.getLoadKey(), declared)).getOrDefault(part, NO_DECORATORS); + return decorators.computeIfAbsent(biome.settings(), declared -> resolve(biome.key(), declared)).getOrDefault(part, NO_DECORATORS); } /** Whether the biome has a decorator for {@code part}. */ - public boolean hasDecorators(IrisBiome biome, DecorationPart part) { + public boolean hasDecorators(DecoratedBiome biome, DecorationPart part) { return decorators(biome, part).length > 0; } /** Resolves every decorator of every biome the dimension reaches and builds its noise, so that generation finds them ready. */ public void warm() { - List biomes = engine.getAllBiomes(); - biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); - for (IrisBiome biome : biomes) { + List> declared = new ArrayList<>(world.settings().declared(DecorantSettings.class)); + declared.sort(Comparator.comparing(entry -> biomeKey(entry.source()))); + for (Entry entry : declared) { + DecoratedBiome biome = new DecoratedBiome(biomeKey(entry.source()), entry.value(), null); for (DecorationPart part : DecorationPart.values()) { for (ResolvedDecorator decorator : decorators(biome, part)) { decorator.warm(); @@ -115,53 +120,6 @@ public final class BiomeDecorators { } } - /** The most decorating any reachable biome does, as the sum of its decorators' chances times their stack heights. */ - public double busiestBiomeLoad() { - Double cached = busiestBiomeLoad; - if (cached != null) { - return cached; - } - - double busiest = 0D; - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - busiest = Math.max(busiest, load(biome)); - } - busiestBiomeLoad = busiest; - return busiest; - } - - /** How loaded the biome is with decorators: the sum of their chances times their stack heights, at least one block each. */ - public double load(IrisBiome biome) { - DecorantSettings settings = settingsOf(biome); - if (settings == null) { - return 0D; - } - - double load = 0D; - for (Decorator decorator : settings.decorators()) { - load += Math.max(decorator.stackMax(), 1) * decorator.chance(); - } - return load; - } - - /** How strongly studio's decorator load view colours the biome: the sum of its decorators' chances over a chunk's columns. */ - public double colourLoad(IrisBiome biome) { - DecorantSettings settings = settingsOf(biome); - if (settings == null) { - return 0D; - } - - double load = 0D; - for (Decorator decorator : settings.decorators()) { - load += decorator.chance() * Math.min(1, decorator.stackMax()) * COLUMNS_PER_CHUNK; - } - return load; - } - - private static DecorantSettings settingsOf(IrisBiome biome) { - return biome.getModuleSettings().find(DecorantSettings.class).orElse(null); - } - private Map resolve(String biomeKey, DecorantSettings settings) { Map> staging = new EnumMap<>(DecorationPart.class); List declared = settings.decorators(); @@ -170,7 +128,7 @@ public final class BiomeDecorators { if (decorator == null) { continue; } - ResolvedDecorator resolved = ResolvedDecorator.of(decorator, engine, decoratorSeed(biomeKey, index), log); + ResolvedDecorator resolved = ResolvedDecorator.of(decorator, resources, seedOf(biomeKey, index), log, biomeKey); staging.computeIfAbsent(decorator.partOf(), part -> new ArrayList<>()).add(resolved); } @@ -179,7 +137,7 @@ public final class BiomeDecorators { return buckets; } - private long decoratorSeed(String biomeKey, int index) { - return engine.getSeedManager().getDecorator() + (biomeKey.hashCode() * KEY_SEED_FACTOR) + (index * INDEX_SEED_FACTOR); + private long seedOf(String biomeKey, int index) { + return decoratorSeed + (biomeKey.hashCode() * KEY_SEED_FACTOR) + (index * INDEX_SEED_FACTOR); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java new file mode 100644 index 000000000..2bad9d80c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratedBiome.java @@ -0,0 +1,28 @@ +/* + * 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.decorator; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import com.volmit.world.BiomeKind; + +/** + * A biome as the decorators see it: the key the pack names it by, which seeds its decorators' noise, the decorators it declares + * (none when it declares no {@link DecorantSettings}) and what it was generated as. + */ +public record DecoratedBiome(String key, DecorantSettings settings, BiomeKind kind) { +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java new file mode 100644 index 000000000..7df79fdc1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -0,0 +1,149 @@ +/* + * 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.decorator; + +import art.arcane.iris.builtin.IrisSeed; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleLayer; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.TerrainSampler; + +import java.util.EnumMap; +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * Everything the decorators of one chunk look at: its blocks, the blocks the mantle planned around it, the terrain, the pack's + * block rules and the biomes' decorators. A decorator places into {@link #blocks()} only. What it asks of a block is asked + * once for each distinct block instance, since a chunk holds few. + */ +public final class DecorationScene { + private final Hunk blocks; + private final BlockRegistry registry; + private final TerrainSampler terrain; + private final MantleLayer planned; + private final BiomeDecorators decorators; + private final long seed; + private final ModuleLog log; + private final Map> traits = new EnumMap<>(BlockTrait.class); + private final Map> supports = new IdentityHashMap<>(); + + /** The chunk of {@code context}, decorated with the world's decorators. */ + public static DecorationScene of(ChunkStageContext context) { + Mantle mantle = context.mantle(); + return new DecorationScene(context.hunk(BlockState.class), context.resources().blocks(), context.terrain(), + mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), IrisSeed.COMPONENT.of(context.world()), + context.log()); + } + + public DecorationScene(Hunk blocks, BlockRegistry registry, TerrainSampler terrain, MantleLayer planned, + BiomeDecorators decorators, long seed, ModuleLog log) { + this.blocks = blocks; + this.registry = registry; + this.terrain = terrain; + this.planned = planned; + this.decorators = decorators; + this.seed = seed; + this.log = log; + } + + public Hunk blocks() { + return blocks; + } + + public BlockRegistry registry() { + return registry; + } + + public TerrainSampler terrain() { + return terrain; + } + + public BiomeDecorators decorators() { + return decorators; + } + + /** The seed the decorators of every place draw from, each shifted by its own part. */ + long seed() { + return seed; + } + + ModuleLog log() { + return log; + } + + /** The height of the chunk's volume. */ + public int worldHeight() { + return blocks.getHeight(); + } + + public int fluidHeight() { + return terrain.fluidHeight(); + } + + /** The slope of the terrain at the column. */ + double slopeAt(int worldX, int worldZ) { + return terrain.column(worldX, worldZ).slope(); + } + + /** The height of the terrain at the column, rounded. */ + long roundedHeightAt(int worldX, int worldZ) { + return Math.round(terrain.surfaceY(worldX, worldZ)); + } + + /** The block a placement planned at the position, or air; positions the mantle does not cover read as air. */ + BlockState plannedAt(int worldX, int y, int worldZ) { + if (planned == null || y < 0 || y >= worldHeight()) { + return null; + } + return planned.get(worldX, y, worldZ); + } + + boolean has(BlockTrait trait, BlockState block) { + return traits.computeIfAbsent(trait, ignored -> new IdentityHashMap<>()) + .computeIfAbsent(block, known -> registry.hasTrait(known, trait)); + } + + public boolean isAir(BlockState block) { + return has(BlockTrait.AIR, block); + } + + public boolean isFluid(BlockState block) { + return has(BlockTrait.FLUID, block); + } + + public boolean isSolid(BlockState block) { + return has(BlockTrait.SOLID, block); + } + + public boolean isWater(BlockState block) { + return has(BlockTrait.WATER, block); + } + + /** Whether {@code decoration} may stand on {@code surface}: its kind of block on that kind of block, and the surface carries a block on its top face. */ + boolean canGoOn(BlockState decoration, BlockState surface) { + return supports.computeIfAbsent(decoration, ignored -> new IdentityHashMap<>()) + .computeIfAbsent(surface, known -> registry.canPlaceOn(decoration, known) + && registry.canAttach(decoration, known, com.volmit.block.BlockFace.UP)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java index 26fc4aa2a..0dee08c3f 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,35 +15,41 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockSupport; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.MultipleFacing; +import com.volmit.block.BlockFace; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; + +import java.util.List; +import java.util.Map; final class DecoratorCore { private static final long SEED_OFFSET = 29356788L; private static final long PART_FACTOR = 10439677L; - private static final String WEEPING_VINES = "minecraft:weeping_vines"; - private static final String WEEPING_VINES_PLANT = "minecraft:weeping_vines_plant"; - private static final String TWISTING_VINES = "minecraft:twisting_vines"; - private static final String TWISTING_VINES_PLANT = "minecraft:twisting_vines_plant"; - private static volatile PlatformBlockState weepingVines; - private static volatile PlatformBlockState weepingVinesPlant; - private static volatile PlatformBlockState twistingVines; - private static volatile PlatformBlockState twistingVinesPlant; + private static final String HALF = "half"; + private static final ResourceId WEEPING_VINES = ResourceId.parse("minecraft:weeping_vines"); + private static final ResourceId WEEPING_VINES_PLANT = ResourceId.parse("minecraft:weeping_vines_plant"); + private static final ResourceId TWISTING_VINES = ResourceId.parse("minecraft:twisting_vines"); + private static final ResourceId TWISTING_VINES_PLANT = ResourceId.parse("minecraft:twisting_vines_plant"); + private static final ResourceId POINTED_DRIPSTONE = ResourceId.parse("minecraft:pointed_dripstone"); + private static final String[] DRIPSTONE_THICKNESS = {"tip", "frustum", "base"}; + private static final BlockState[] DRIPSTONE_UP = dripstones("up"); + private static final BlockState[] DRIPSTONE_DOWN = dripstones("down"); + private static final BlockState AIR = new BlockState("minecraft:air"); + /** The faces a vine can grow on, in the order Iris looks at them, with the neighbour each faces. */ + private static final List FACES = List.of(new Face(BlockFace.NORTH, "north", 0, 0, -1), new Face(BlockFace.EAST, "east", 1, 0, 0), + new Face(BlockFace.SOUTH, "south", 0, 0, 1), new Face(BlockFace.WEST, "west", -1, 0, 0), new Face(BlockFace.UP, "up", 0, 1, 0), + new Face(BlockFace.DOWN, "down", 0, -1, 0)); + private static final Map OPPOSITES = Map.of(BlockFace.NORTH, BlockFace.SOUTH, BlockFace.SOUTH, BlockFace.NORTH, + BlockFace.EAST, BlockFace.WEST, BlockFace.WEST, BlockFace.EAST, BlockFace.UP, BlockFace.DOWN, BlockFace.DOWN, BlockFace.UP); + private static final int CHUNK_LAST = 15; static final ThreadLocal SCRATCH_OPTS = ThreadLocal.withInitial(PlaceOpts::new); @@ -59,6 +65,9 @@ final class DecoratorCore { } } + private record Face(BlockFace face, String property, int dx, int dy, int dz) { + } + static long partSeed(long baseSeed, int partOrdinal) { return baseSeed + SEED_OFFSET - (partOrdinal * PART_FACTOR); } @@ -96,77 +105,75 @@ final class DecoratorCore { return half.equals("upper") || half.equals("lower") ? "lower" : "bottom"; } - static void placeSurfaceSingle(ResolvedDecorator decorator, + static void placeSurfaceSingle(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int height, int realZ, - Hunk data, - boolean underwater, boolean caveSkipFluid, EngineMantle mantle, ModuleLog log) { + boolean underwater, boolean caveSkipFluid) { + Hunk data = scene.blocks(); if (height < 0 || height >= data.getHeight()) { return; } - PlatformBlockState bdx = data.get(x, height, z); - PlatformBlockState bd = decorator.pickBlock(realX, realZ); + BlockState bdx = data.get(x, height, z); + BlockState bd = decorator.pickBlock(realX, realZ); - if (!underwater && !canGoOn(bd, bdx) + if (!underwater && !canGoOn(scene, bd, bdx) && !decorator.isForcePlace() && decorator.forceBlock() == null) { return; } if (decorator.forceBlock() != null) { - if (caveSkipFluid && B.isFluid(bdx)) { + if (caveSkipFluid && scene.isFluid(bdx)) { return; } - data.set(x, height, z, fixFacesForHunk( - decorator.forceBlock(), data, x, z, realX, height, realZ, mantle)); + data.set(x, height, z, fixFacesForHunk(scene, decorator.forceBlock(), x, z, realX, height, realZ)); } if (!decorator.isForcePlace() && decorator.rejectsSurface(bdx)) { return; } - String half = bd == null ? null : IrisProceduralBlocks.propertyValue(bd, "half"); + String half = bd == null ? null : bd.properties().get(HALF); if (half != null) { int lowerY = height + 1; int upperY = height + 2; - if (!canPlaceTwoBlockPlant(data, x, z, lowerY, upperY, caveSkipFluid)) { + if (!canPlaceTwoBlockPlant(scene, x, z, lowerY, upperY, caveSkipFluid)) { return; } try { - PlatformBlockState upper = bd.withProperty("half", topHalfValue(half)); - PlatformBlockState lower = fixFacesForHunk( - bd.withProperty("half", bottomHalfValue(half)), - data, x, z, realX, lowerY, realZ, mantle); + BlockState upper = bd.withProperty(HALF, topHalfValue(half)); + BlockState lower = fixFacesForHunk(scene, + bd.withProperty(HALF, bottomHalfValue(half)), + x, z, realX, lowerY, realZ); data.set(x, lowerY, z, lower); data.set(x, upperY, z, upper); } catch (Throwable e) { - log.error("Failed to place a two-block plant", e); + scene.log().error("Failed to place a two-block plant", e); } return; } int targetY = height + 1; - if (targetY < data.getHeight() && B.isAir(data.get(x, targetY, z))) { - data.set(x, targetY, z, fixFacesForHunk(bd, data, x, z, realX, targetY, realZ, mantle)); + if (bd != null && targetY < data.getHeight() && scene.isAir(data.get(x, targetY, z))) { + data.set(x, targetY, z, fixFacesForHunk(scene, bd, x, z, realX, targetY, realZ)); } } - static void placeSingleAt(ResolvedDecorator decorator, int x, int z, - int realX, int height, int realZ, Hunk data, - boolean applyFixFaces, EngineMantle mantle) { - PlatformBlockState bd = decorator.pickBlock(realX, realZ); + static void placeSingleAt(ResolvedDecorator decorator, DecorationScene scene, int x, int z, + int realX, int height, int realZ, boolean applyFixFaces) { + BlockState bd = decorator.pickBlock(realX, realZ); if (bd == null) { return; } if (applyFixFaces) { - bd = fixFacesForHunk(bd, data, x, z, realX, height, realZ, mantle); + bd = fixFacesForHunk(scene, bd, x, z, realX, height, realZ); } - data.set(x, height, z, bd); + scene.blocks().set(x, height, z, bd); } - static void placeStackUp(ResolvedDecorator decorator, int x, int z, int realX, int realZ, - int height, int max, Hunk data, - PlaceOpts opts) { + static void placeStackUp(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ, + int height, int max, PlaceOpts opts) { + Hunk data = scene.blocks(); if (height < 0 || height >= data.getHeight()) { return; } @@ -184,14 +191,14 @@ final class DecoratorCore { return; } - PlatformBlockState existing = data.get(x, targetY, z); - if (!canReplaceStackTarget(existing, opts.underwater) - || (opts.caveSkipFluid && B.isFluid(existing))) { + BlockState existing = data.get(x, targetY, z); + if (!canReplaceStackTarget(scene, existing, opts.underwater) + || (opts.caveSkipFluid && scene.isFluid(existing))) { return; } - PlatformBlockState block = decorator.pickTopBlock(realX, realZ); - if (block == null || (!opts.underwater && !canGoOn(block, data.get(x, height, z)))) { + BlockState block = decorator.pickTopBlock(realX, realZ); + if (block == null || (!opts.underwater && !canGoOn(scene, block, data.get(x, height, z)))) { return; } @@ -200,12 +207,11 @@ final class DecoratorCore { return; } - PlatformBlockState bdx = data.get(x, height, z); + BlockState bdx = data.get(x, height, z); for (int i = 0; i < stack; i++) { - int h = height + i; double threshold = ((double) i) / (stack - 1); - PlatformBlockState bd = threshold >= decorator.topThreshold() + BlockState bd = threshold >= decorator.topThreshold() ? decorator.pickTopBlock(realX, realZ) : decorator.pickBlock(realX, realZ); @@ -213,7 +219,7 @@ final class DecoratorCore { break; } - if (i == 0 && !opts.underwater && !canGoOn(bd, bdx)) { + if (i == 0 && !opts.underwater && !canGoOn(scene, bd, bdx)) { break; } @@ -225,14 +231,14 @@ final class DecoratorCore { break; } - PlatformBlockState existing = data.get(x, height + 1 + i, z); - if (!canReplaceStackTarget(existing, opts.underwater) - || (opts.caveSkipFluid && B.isFluid(existing))) { + BlockState existing = data.get(x, height + 1 + i, z); + if (!canReplaceStackTarget(scene, existing, opts.underwater) + || (opts.caveSkipFluid && scene.isFluid(existing))) { break; } - if (IrisProceduralBlocks.materialKey(bd).equals("minecraft:pointed_dripstone")) { - bd = dripstoneBlock(stack, i, "up"); + if (bd.material().equals(POINTED_DRIPSTONE)) { + bd = dripstoneBlock(stack, i, DRIPSTONE_UP); } bd = stackedVineBlock(bd, stack, i); @@ -240,9 +246,9 @@ final class DecoratorCore { } } - static void placeStackDown(ResolvedDecorator decorator, int x, int z, int realX, int realZ, - int height, int minHeight, Hunk data, - int max, PlaceOpts opts, EngineMantle mantle) { + static void placeStackDown(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ, + int height, int minHeight, int max, PlaceOpts opts) { + Hunk data = scene.blocks(); if (height < 0 || height >= data.getHeight()) { return; } @@ -250,15 +256,15 @@ final class DecoratorCore { int stack = computeStack(decorator, realX, realZ, max); if (stack == 1) { - if (opts.caveSkipFluid && B.isFluid(data.get(x, height, z))) { + if (opts.caveSkipFluid && scene.isFluid(data.get(x, height, z))) { return; } - PlatformBlockState block = decorator.pickTopBlock(realX, realZ); + BlockState block = decorator.pickTopBlock(realX, realZ); if (block == null) { return; } block = stackedVineBlock(block, stack, 0); - data.set(x, height, z, fixFacesForHunk(block, data, x, z, realX, height, realZ, mantle)); + data.set(x, height, z, fixFacesForHunk(scene, block, x, z, realX, height, realZ)); return; } @@ -269,7 +275,7 @@ final class DecoratorCore { } double threshold = ((double) i) / (double) (stack - 1); - PlatformBlockState bd = threshold >= decorator.topThreshold() + BlockState bd = threshold >= decorator.topThreshold() ? decorator.pickTopBlock(realX, realZ) : decorator.pickBlock(realX, realZ); @@ -277,41 +283,42 @@ final class DecoratorCore { break; } - if (IrisProceduralBlocks.materialKey(bd).equals("minecraft:pointed_dripstone")) { - bd = dripstoneBlock(stack, i, "down"); + if (bd.material().equals(POINTED_DRIPSTONE)) { + bd = dripstoneBlock(stack, i, DRIPSTONE_DOWN); } bd = stackedVineBlock(bd, stack, i); - if (opts.caveSkipFluid && B.isFluid(data.get(x, h, z))) { + if (opts.caveSkipFluid && scene.isFluid(data.get(x, h, z))) { break; } - data.set(x, h, z, fixFacesForHunk(bd, data, x, z, realX, h, realZ, mantle)); + data.set(x, h, z, fixFacesForHunk(scene, bd, x, z, realX, h, realZ)); } } - static void placeFloatingSimple(ResolvedDecorator decorator, + static void placeFloatingSimple(ResolvedDecorator decorator, DecorationScene scene, int xf, int zf, int realX, int realZ, - int height, int max, Hunk data, ModuleLog log) { - PlatformBlockState bd = decorator.pickBlock(realX, realZ); + int height, int max) { + Hunk data = scene.blocks(); + BlockState bd = decorator.pickBlock(realX, realZ); if (bd == null) { return; } - String half = IrisProceduralBlocks.propertyValue(bd, "half"); + String half = bd.properties().get(HALF); if (half != null) { int lowerY = height + 1; int upperY = height + 2; - if (max <= 2 || !canPlaceTwoBlockPlant(data, xf, zf, lowerY, upperY, false)) { + if (max <= 2 || !canPlaceTwoBlockPlant(scene, xf, zf, lowerY, upperY, false)) { return; } try { - PlatformBlockState upper = bd.withProperty("half", topHalfValue(half)); - PlatformBlockState lower = bd.withProperty("half", bottomHalfValue(half)); + BlockState upper = bd.withProperty(HALF, topHalfValue(half)); + BlockState lower = bd.withProperty(HALF, bottomHalfValue(half)); data.set(xf, lowerY, zf, lower); data.set(xf, upperY, zf, upper); } catch (Throwable e) { - log.error("Failed to place a two-block plant", e); + scene.log().error("Failed to place a two-block plant", e); } return; } @@ -321,9 +328,10 @@ final class DecoratorCore { } } - static int placeFloatingStacked(ResolvedDecorator decorator, + static int placeFloatingStacked(ResolvedDecorator decorator, DecorationScene scene, int xf, int zf, int realX, int realZ, - int height, int max, Hunk data) { + int height, int max) { + Hunk data = scene.blocks(); int stack = decorator.stackHeight(realX, realZ); if (decorator.isScaleStack()) { stack = Math.min((int) Math.ceil((double) max * ((double) stack / 100)), decorator.absoluteMaxStack()); @@ -338,7 +346,7 @@ final class DecoratorCore { break; } double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1); - PlatformBlockState bd = threshold >= decorator.topThreshold() + BlockState bd = threshold >= decorator.topThreshold() ? decorator.pickTopBlock(realX, realZ) : decorator.pickBlock(realX, realZ); if (bd == null) { @@ -351,94 +359,85 @@ final class DecoratorCore { return placed; } - static PlatformBlockState fixFacesForHunk(PlatformBlockState b, Hunk hunk, int rX, int rZ, - int x, int y, int z, EngineMantle mantle) { - if (!B.isVineBlock(b)) { + /** + * A vine placed at {@code x}, {@code y}, {@code z} (the chunk's local column {@code rX}, {@code rZ}) faces the neighbours that + * can hold it: the blocks the mantle planned there, else the chunk's own blocks. A vine with no such neighbour faces down, + * or up when it cannot face down. Any other block is returned as it is. + */ + static BlockState fixFacesForHunk(DecorationScene scene, BlockState b, int rX, int rZ, int x, int y, int z) { + if (b == null || !scene.has(BlockTrait.VINE, b)) { return b; } - DecoratorPlatformHooks.FaceFixer fixer = DecoratorPlatformHooks.faceFixer(); - if (fixer != null) { - return fixer.fixFaces(b, hunk, rX, rZ, x, y, z, mantle); + Hunk hunk = scene.blocks(); + BlockState fixed = b; + for (Face face : FACES) { + if (b.properties().containsKey(face.property())) { + fixed = fixed.withProperty(face.property(), "false"); + } } - BlockData rawB = (BlockData) b.nativeHandle(); - BlockData cloned = rawB.clone(); - MultipleFacing data = (MultipleFacing) cloned; - data.getFaces().forEach(f -> data.setFace(f, false)); boolean found = false; - for (BlockFace f : BlockFace.values()) { - if (!f.isCartesian()) { - continue; - } - int yy = y + f.getModY(); + for (Face face : FACES) { + int yy = y + face.dy(); + BlockFace opposite = OPPOSITES.get(face.face()); - PlatformBlockState rs = null; - if (mantle != null) { - rs = mantle.getMantle().get(x + f.getModX(), yy, z + f.getModZ(), PlatformBlockState.class); - } - BlockData r = rs == null ? (BlockData) EngineMantle.AIR.nativeHandle() : (BlockData) rs.nativeHandle(); - if (r.isFaceSturdy(f.getOppositeFace(), BlockSupport.FULL)) { - if (data.getAllowedFaces().contains(f)) { + BlockState planned = scene.plannedAt(x + face.dx(), yy, z + face.dz()); + BlockState support = planned == null ? AIR : planned; + if (scene.registry().canAttach(b, support, opposite)) { + if (b.properties().containsKey(face.property())) { found = true; - data.setFace(f, true); + fixed = fixed.withProperty(face.property(), "true"); } continue; } - int xx = rX + f.getModX(); - int zz = rZ + f.getModZ(); - if (xx < 0 || xx > 15 || zz < 0 || zz > 15 || yy < 0 || yy >= hunk.getHeight()) { + int xx = rX + face.dx(); + int zz = rZ + face.dz(); + if (xx < 0 || xx > CHUNK_LAST || zz < 0 || zz > CHUNK_LAST || yy < 0 || yy >= hunk.getHeight()) { continue; } - r = (BlockData) hunk.get(xx, yy, zz).nativeHandle(); - if (r.isFaceSturdy(f.getOppositeFace(), BlockSupport.FULL)) { - if (data.getAllowedFaces().contains(f)) { + if (scene.registry().canAttach(b, hunk.get(xx, yy, zz), opposite)) { + if (b.properties().containsKey(face.property())) { found = true; - data.setFace(f, true); + fixed = fixed.withProperty(face.property(), "true"); } } } if (!found) { - BlockFace fallback = data.getAllowedFaces().contains(BlockFace.DOWN) ? BlockFace.DOWN : BlockFace.UP; - if (data.getAllowedFaces().contains(fallback)) { - data.setFace(fallback, true); + String fallback = b.properties().containsKey("down") ? "down" : "up"; + if (b.properties().containsKey(fallback)) { + fixed = fixed.withProperty(fallback, "true"); } } - return BukkitBlockState.of(cloned); + return fixed; } - static boolean canGoOn(PlatformBlockState decorator, PlatformBlockState surface) { - if (!B.canPlaceOnto(decorator, surface)) { - return false; - } - DecoratorPlatformHooks.SurfaceSturdiness sturdiness = DecoratorPlatformHooks.surfaceSturdiness(); - if (sturdiness != null) { - return sturdiness.canGoOn(surface); - } - return ((BlockData) surface.nativeHandle()).isFaceSturdy(BlockFace.UP, BlockSupport.FULL); + static boolean canGoOn(DecorationScene scene, BlockState decorator, BlockState surface) { + return decorator != null && surface != null && scene.canGoOn(decorator, surface); } - static boolean isValidShorelineSupport(ResolvedDecorator decorator, PlatformBlockState decorant, PlatformBlockState surface) { + static boolean isValidShorelineSupport(DecorationScene scene, ResolvedDecorator decorator, BlockState decorant, BlockState surface) { return surface != null - && B.isSolid(surface) - && (decorator.isForcePlace() || canGoOn(decorant, surface)); + && scene.isSolid(surface) + && (decorator.isForcePlace() || canGoOn(scene, decorant, surface)); } - static boolean canReplaceStackTarget(PlatformBlockState state, boolean allowFluid) { - return B.isAir(state) || allowFluid && B.isFluid(state); + static boolean canReplaceStackTarget(DecorationScene scene, BlockState state, boolean allowFluid) { + return scene.isAir(state) || allowFluid && scene.isFluid(state); } - private static boolean canPlaceTwoBlockPlant(Hunk data, int x, int z, + private static boolean canPlaceTwoBlockPlant(DecorationScene scene, int x, int z, int lowerY, int upperY, boolean caveSkipFluid) { + Hunk data = scene.blocks(); if (lowerY < 0 || upperY >= data.getHeight()) { return false; } - PlatformBlockState lower = data.get(x, lowerY, z); - PlatformBlockState upper = data.get(x, upperY, z); - return B.isAir(lower) && B.isAir(upper) - && (!caveSkipFluid || !B.isFluid(lower) && !B.isFluid(upper)); + BlockState lower = data.get(x, lowerY, z); + BlockState upper = data.get(x, upperY, z); + return scene.isAir(lower) && scene.isAir(upper) + && (!caveSkipFluid || !scene.isFluid(lower) && !scene.isFluid(upper)); } private static int computeStack(ResolvedDecorator decorator, double realX, double realZ, int max) { @@ -451,19 +450,15 @@ final class DecoratorCore { return stack; } - private static volatile PlatformBlockState[] dripstoneUp; - private static volatile PlatformBlockState[] dripstoneDown; - - private static PlatformBlockState[] buildDripstoneArr(String direction) { - String[] order = {"tip", "frustum", "base"}; - PlatformBlockState[] arr = new PlatformBlockState[3]; - for (int k = 0; k < 3; k++) { - arr[k] = B.getState("minecraft:pointed_dripstone[thickness=" + order[k] + ",vertical_direction=" + direction + "]"); + private static BlockState[] dripstones(String direction) { + BlockState[] arr = new BlockState[DRIPSTONE_THICKNESS.length]; + for (int k = 0; k < arr.length; k++) { + arr[k] = BlockState.parse("minecraft:pointed_dripstone[thickness=" + DRIPSTONE_THICKNESS[k] + ",vertical_direction=" + direction + "]"); } return arr; } - private static PlatformBlockState dripstoneBlock(int stack, int i, String direction) { + private static BlockState dripstoneBlock(int stack, int i, BlockState[] byThickness) { int thIdx; if (i == stack - 1) { thIdx = 0; @@ -472,39 +467,24 @@ final class DecoratorCore { } else { thIdx = 2; } - if (direction.equals("up")) { - if (dripstoneUp == null) { - dripstoneUp = buildDripstoneArr("up"); - } - return dripstoneUp[thIdx]; - } - if (dripstoneDown == null) { - dripstoneDown = buildDripstoneArr("down"); - } - return dripstoneDown[thIdx]; + return byThickness[thIdx]; } - static String stackedVineKey(PlatformBlockState state, int stack, int index) { - String material = IrisProceduralBlocks.materialKey(state); + /** The key of the vine block that fills a stack of vines at {@code index}: the tip at the end, the plant before it; null for other blocks. */ + static ResourceId stackedVineMaterial(BlockState state, int stack, int index) { + ResourceId material = state.material(); boolean tip = index == stack - 1; - return switch (material) { - case WEEPING_VINES, WEEPING_VINES_PLANT -> tip ? WEEPING_VINES : WEEPING_VINES_PLANT; - case TWISTING_VINES, TWISTING_VINES_PLANT -> tip ? TWISTING_VINES : TWISTING_VINES_PLANT; - default -> null; - }; + if (material.equals(WEEPING_VINES) || material.equals(WEEPING_VINES_PLANT)) { + return tip ? WEEPING_VINES : WEEPING_VINES_PLANT; + } + if (material.equals(TWISTING_VINES) || material.equals(TWISTING_VINES_PLANT)) { + return tip ? TWISTING_VINES : TWISTING_VINES_PLANT; + } + return null; } - private static PlatformBlockState stackedVineBlock(PlatformBlockState state, int stack, int index) { - String key = stackedVineKey(state, stack, index); - if (key == null) { - return state; - } - return switch (key) { - case WEEPING_VINES -> weepingVines == null ? weepingVines = B.getState(key) : weepingVines; - case WEEPING_VINES_PLANT -> weepingVinesPlant == null ? weepingVinesPlant = B.getState(key) : weepingVinesPlant; - case TWISTING_VINES -> twistingVines == null ? twistingVines = B.getState(key) : twistingVines; - case TWISTING_VINES_PLANT -> twistingVinesPlant == null ? twistingVinesPlant = B.getState(key) : twistingVinesPlant; - default -> state; - }; + private static BlockState stackedVineBlock(BlockState state, int stack, int index) { + ResourceId material = stackedVineMaterial(state, stack, index); + return material == null ? state : new BlockState(material.toString()); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java deleted file mode 100644 index b14f63ab0..000000000 --- a/src/main/java/art/arcane/iris/engine/decorator/DecoratorPlatformHooks.java +++ /dev/null @@ -1,62 +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.decorator; - -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.project.hunk.Hunk; - -public final class DecoratorPlatformHooks { - private static volatile FaceFixer FACE_FIXER = null; - private static volatile SurfaceSturdiness SURFACE_STURDINESS = null; - - private DecoratorPlatformHooks() { - } - - public interface FaceFixer { - PlatformBlockState fixFaces(PlatformBlockState state, Hunk hunk, int rX, int rZ, int x, int y, int z, EngineMantle mantle); - } - - public interface SurfaceSturdiness { - boolean canGoOn(PlatformBlockState surface); - } - - public static synchronized Bindings bind(FaceFixer faceFixer, SurfaceSturdiness surfaceSturdiness) { - Bindings previous = new Bindings(FACE_FIXER, SURFACE_STURDINESS); - FACE_FIXER = faceFixer; - SURFACE_STURDINESS = surfaceSturdiness; - return previous; - } - - public static synchronized void restore(Bindings bindings) { - FACE_FIXER = bindings.faceFixer(); - SURFACE_STURDINESS = bindings.surfaceSturdiness(); - } - - static FaceFixer faceFixer() { - return FACE_FIXER; - } - - static SurfaceSturdiness surfaceSturdiness() { - return SURFACE_STURDINESS; - } - - public record Bindings(FaceFixer faceFixer, SurfaceSturdiness surfaceSturdiness) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java index dac61cbe9..c5c9ec635 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/FloatingDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,28 +15,23 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.hunk.Hunk; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.spi.PlatformBlockState; /* * Floating island decoration path. Bypasses all canGoOn, slope, whitelist, and blacklist - * gating from IrisSurfaceDecorator — the island top IS the biome's designated surface by + * gating from IrisSurfaceDecorator: the island top IS the biome's designated surface by * construction, so those material-compatibility checks are never meaningful here. */ public class FloatingDecorator { - public static int decorateColumn(Engine engine, IrisBiome target, DecorationPart part, + public static int decorateColumn(DecorationScene scene, DecoratedBiome target, DecorationPart part, int xf, int zf, int realX, int realZ, - int height, int max, Hunk data, RNG rng, + int height, int max, RNG rng, Runnable candidatesNullCallback) { - BiomeDecorators decorators = BiomeDecorators.of(engine); + BiomeDecorators decorators = scene.decorators(); ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(target, part), rng, realX, realZ, decorators.log()); if (decorator == null) { @@ -45,10 +40,10 @@ public class FloatingDecorator { } if (!decorator.isStacking()) { - DecoratorCore.placeFloatingSimple(decorator, xf, zf, realX, realZ, height, max, data, decorators.log()); + DecoratorCore.placeFloatingSimple(decorator, scene, xf, zf, realX, realZ, height, max); return max > 1 ? 1 : 0; } - return DecoratorCore.placeFloatingStacked(decorator, xf, zf, realX, realZ, height, max, data); + return DecoratorCore.placeFloatingStacked(decorator, scene, xf, zf, realX, realZ, height, max); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java index ed02dcee9..1883d62e3 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisCeilingDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,35 +15,20 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.spi.PlatformBlockState; public class IrisCeilingDecorator extends IrisEngineDecorator { - public IrisCeilingDecorator(Engine engine) { - super(engine, "Ceiling", DecorationPart.CEILING); + public IrisCeilingDecorator(DecorationScene scene) { + super(scene, DecorationPart.CEILING); } - @BlockCoordinates @Override public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, int height, int max) { - decorate(x, z, realX, realX1, realX_1, realZ, realZ1, realZ_1, data, biome, biome.getInferredType(), height, max); - } - - @BlockCoordinates - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { - boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(inferredType); + DecoratedBiome biome, int height, int max) { + boolean caveSkipFluid = IrisSurfaceDecorator.skipsFluid(biome.kind()); RNG rng = getRNG(realX, realZ); ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); @@ -52,19 +37,16 @@ public class IrisCeilingDecorator extends IrisEngineDecorator { } if (!decorator.isStacking()) { - if (caveSkipFluid) { - PlatformBlockState state = data.get(x, height, z); - if (B.isFluid(state)) { - return; - } + if (caveSkipFluid && scene.isFluid(scene.blocks().get(x, height, z))) { + return; } - DecoratorCore.placeSingleAt(decorator, x, z, realX, height, realZ, data, true, getEngine().getMantle()); + DecoratorCore.placeSingleAt(decorator, scene, x, z, realX, height, realZ, true); return; } DecoratorCore.PlaceOpts opts = DecoratorCore.SCRATCH_OPTS.get(); opts.reset(); opts.caveSkipFluid = caveSkipFluid; - DecoratorCore.placeStackDown(decorator, x, z, realX, realZ, height, 0, data, max, opts, getEngine().getMantle()); + DecoratorCore.placeStackDown(decorator, scene, x, z, realX, realZ, height, 0, max, opts); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java index 5c07087a6..a34881b2e 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisEngineDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,33 +15,49 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineAssignedComponent; -import art.arcane.iris.engine.framework.EngineDecorator; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; -import lombok.Getter; -public abstract class IrisEngineDecorator extends EngineAssignedComponent implements EngineDecorator { - @Getter +/** A decorator of one kind of place, placing into the blocks of a {@link DecorationScene}. */ +public abstract class IrisEngineDecorator { + private static final long COLUMN_X_FACTOR = 29356788L; + private static final long COLUMN_Z_FACTOR = 10439677L; + private static final int X_PART_OFFSET = 6; + private static final int Z_PART_OFFSET = 1; + private final DecorationPart part; + protected final DecorationScene scene; protected final BiomeDecorators decorators; - public IrisEngineDecorator(Engine engine, String name, DecorationPart part) { - super(engine, name + " Decorator"); + protected IrisEngineDecorator(DecorationScene scene, DecorationPart part) { + this.scene = scene; this.part = part; - this.decorators = BiomeDecorators.of(engine); + this.decorators = scene.decorators(); + } + + public DecorationPart getPart() { + return part; + } + + /** + * Decorates one column. {@code x} and {@code z} are the column in the chunk, {@code realX} and {@code realZ} in the world, + * with the world columns next to it on either side; {@code height} is the Y to decorate from and {@code max} how much room + * there is. + */ + public abstract void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, + DecoratedBiome biome, int height, int max); + + /** {@link #decorate} for a decorator that looks at no neighbouring column. */ + public void decorate(int x, int z, int realX, int realZ, DecoratedBiome biome, int height, int max) { + decorate(x, z, realX, realX, realX, realZ, realZ, realZ, biome, height, max); } - @BlockCoordinates protected RNG getRNG(int x, int z) { - long seed = DecoratorCore.partSeed(getSeed(), part); - long modX = 29356788L ^ (part.ordinal() + 6); - long modZ = 10439677L ^ (part.ordinal() + 1); + long seed = DecoratorCore.partSeed(scene.seed(), part); + long modX = COLUMN_X_FACTOR ^ (part.ordinal() + X_PART_OFFSET); + long modZ = COLUMN_Z_FACTOR ^ (part.ordinal() + Z_PART_OFFSET); return new RNG(x * modX + z * modZ + seed); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java index 5f943c85c..61050f085 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaFloorDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,26 +15,20 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; public class IrisSeaFloorDecorator extends IrisEngineDecorator { - public IrisSeaFloorDecorator(Engine engine) { - super(engine, "Sea Floor", DecorationPart.SEA_FLOOR); + public IrisSeaFloorDecorator(DecorationScene scene) { + super(scene, DecorationPart.SEA_FLOOR); } - @BlockCoordinates @Override public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, int height, int max) { + DecoratedBiome biome, int height, int max) { RNG rng = getRNG(realX, realZ); ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); @@ -42,12 +36,13 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { return; } + var data = scene.blocks(); if (!decorator.isStacking()) { - if (decorator.slopeBlocks(() -> getComplex().getSlopeStream().get(realX, realZ))) { + if (decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ))) { return; } - if (height >= 0 && height < getEngine().getHeight()) { - data.set(x, height, z, decorator.blockAt(biome, realX, height, realZ)); + if (height >= 0 && height < scene.worldHeight()) { + place(x, height, z, decorator.blockAt(realX, height, realZ)); } return; } @@ -60,20 +55,27 @@ public class IrisSeaFloorDecorator extends IrisEngineDecorator { } if (stack == 1) { - data.set(x, height, z, decorator.topBlockAt(biome, realX, height, realZ)); + place(x, height, z, decorator.topBlockAt(realX, height, realZ)); return; } - int engineHeight = getEngine().getHeight(); + int engineHeight = scene.worldHeight(); for (int i = 0; i < stack; i++) { int h = height + i; if (h > max || h > engineHeight) { continue; } double threshold = ((double) i) / (stack - 1); - data.set(x, h, z, threshold >= decorator.topThreshold() - ? decorator.topBlockAt(biome, realX, h, realZ) - : decorator.blockAt(biome, realX, h, realZ)); + place(x, h, z, threshold >= decorator.topThreshold() + ? decorator.topBlockAt(realX, h, realZ) + : decorator.blockAt(realX, h, realZ)); + } + } + + /** A block the decorator has none of leaves the water as it is. */ + private void place(int x, int y, int z, BlockState block) { + if (block != null && y < scene.worldHeight()) { + scene.blocks().set(x, y, z, block); } } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java index 89e2f4459..42f7574a2 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,26 +15,20 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { - public IrisSeaSurfaceDecorator(Engine engine) { - super(engine, "Sea Surface", DecorationPart.SEA_SURFACE); + public IrisSeaSurfaceDecorator(DecorationScene scene) { + super(scene, DecorationPart.SEA_SURFACE); } - @BlockCoordinates @Override public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, int height, int max) { + DecoratedBiome biome, int height, int max) { RNG rng = getRNG(realX, realZ); ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); @@ -42,11 +36,12 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { return; } + var data = scene.blocks(); if (!decorator.isStacking()) { int targetY = height + 1; - if (height >= 0 && targetY < getEngine().getHeight() - && DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { - PlatformBlockState block = decorator.blockAt(biome, realX, height, realZ); + if (height >= 0 && targetY < scene.worldHeight() + && DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + BlockState block = decorator.blockAt(realX, height, realZ); if (block != null) { data.set(x, targetY, z, block); } @@ -61,29 +56,29 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { if (stack == 1) { int targetY = height + 1; - if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { return; } - PlatformBlockState block = decorator.topBlockAt(biome, realX, height, realZ); + BlockState block = decorator.topBlockAt(realX, height, realZ); if (block != null) { data.set(x, targetY, z, block); } return; } - int engineHeight = getEngine().getHeight(); + int engineHeight = scene.worldHeight(); for (int i = 0; i < stack; i++) { int h = height + i; int targetY = h + 1; if (h >= max || targetY >= engineHeight - || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { break; } double threshold = ((double) i) / (stack - 1); - PlatformBlockState block = threshold >= decorator.topThreshold() - ? decorator.topBlockAt(biome, realX, h, realZ) - : decorator.blockAt(biome, realX, h, realZ); + BlockState block = threshold >= decorator.topThreshold() + ? decorator.topBlockAt(realX, h, realZ) + : decorator.blockAt(realX, h, realZ); if (block == null) { break; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java index 944cf0213..667807d2e 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,37 +15,29 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.iris.util.project.stream.ProceduralStream; -import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; public class IrisShoreLineDecorator extends IrisEngineDecorator { - public IrisShoreLineDecorator(Engine engine) { - super(engine, "Shore Line", DecorationPart.SHORE_LINE); + public IrisShoreLineDecorator(DecorationScene scene) { + super(scene, DecorationPart.SHORE_LINE); } - @BlockCoordinates @Override public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, int height, int max) { - if (height != getDimension().getFluidHeight()) { + DecoratedBiome biome, int height, int max) { + if (height != scene.fluidHeight()) { return; } - double complexFluidHeight = getComplex().getFluidHeight(); - ProceduralStream heightStream = getComplex().getHeightStream(); - if (Math.round(heightStream.get(realX1, realZ)) >= complexFluidHeight - && Math.round(heightStream.get(realX_1, realZ)) >= complexFluidHeight - && Math.round(heightStream.get(realX, realZ1)) >= complexFluidHeight - && Math.round(heightStream.get(realX, realZ_1)) >= complexFluidHeight) { + double complexFluidHeight = scene.fluidHeight(); + if (scene.roundedHeightAt(realX1, realZ) >= complexFluidHeight + && scene.roundedHeightAt(realX_1, realZ) >= complexFluidHeight + && scene.roundedHeightAt(realX, realZ1) >= complexFluidHeight + && scene.roundedHeightAt(realX, realZ_1) >= complexFluidHeight) { return; } @@ -56,23 +48,24 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { return; } - if (decorator.slopeBlocks(() -> getComplex().getSlopeStream().get(realX, realZ))) { + if (decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ))) { return; } - PlatformBlockState support = data.get(x, height, z); - if (support == null || !support.isSolid()) { + var data = scene.blocks(); + BlockState support = data.get(x, height, z); + if (support == null || !scene.isSolid(support)) { return; } if (!decorator.isStacking()) { int targetY = height + 1; if (targetY >= data.getHeight() - || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { return; } - PlatformBlockState block = decorator.blockAt(biome, realX, height, realZ); - if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) { + BlockState block = decorator.blockAt(realX, height, realZ); + if (block != null && DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) { data.set(x, targetY, z, block); } return; @@ -87,12 +80,12 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { if (stack == 1) { int targetY = height + 1; - if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { return; } - PlatformBlockState block = decorator.topBlockAt(biome, realX, height, realZ); - if (block != null && DecoratorCore.isValidShorelineSupport(decorator, block, support)) { + BlockState block = decorator.topBlockAt(realX, height, realZ); + if (block != null && DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) { data.set(x, targetY, z, block); } return; @@ -102,17 +95,17 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { int h = height + i; int targetY = h + 1; if (targetY >= data.getHeight() - || !DecoratorCore.canReplaceStackTarget(data.get(x, targetY, z), false)) { + || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { break; } double threshold = ((double) i) / (stack - 1); - PlatformBlockState block = threshold >= decorator.topThreshold() - ? decorator.topBlockAt(biome, realX, h, realZ) - : decorator.blockAt(biome, realX, h, realZ); + BlockState block = threshold >= decorator.topThreshold() + ? decorator.topBlockAt(realX, h, realZ) + : decorator.blockAt(realX, h, realZ); if (block == null) { break; } - if (i == 0 && !DecoratorCore.isValidShorelineSupport(decorator, block, support)) { + if (i == 0 && !DecoratorCore.isValidShorelineSupport(scene, decorator, block, support)) { break; } data.set(x, targetY, z, block); diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java index 296d5e533..041a13731 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSurfaceDecorator.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -15,48 +15,32 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.decorator; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.InferredType; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.documentation.BlockCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.world.BiomeKind; public class IrisSurfaceDecorator extends IrisEngineDecorator { - public IrisSurfaceDecorator(Engine engine) { - super(engine, "Surface", DecorationPart.NONE); - } - - protected IrisSurfaceDecorator(Engine engine, String name) { - super(engine, name, DecorationPart.NONE); + public IrisSurfaceDecorator(DecorationScene scene) { + super(scene, DecorationPart.NONE); } protected boolean isSlopeValid(ResolvedDecorator decorator, int realX, int realZ) { - return !decorator.slopeBlocks(() -> getComplex().getSlopeStream().get(realX, realZ)); + return !decorator.slopeBlocks(() -> scene.slopeAt(realX, realZ)); } - @BlockCoordinates @Override public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, int height, int max) { - decorate(x, z, realX, realX1, realX_1, realZ, realZ1, realZ_1, data, biome, biome.getInferredType(), height, max); - } - - @BlockCoordinates - public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, - Hunk data, IrisBiome biome, InferredType inferredType, int height, int max) { - int fluidHeight = getDimension().getFluidHeight(); - if (inferredType == InferredType.SHORE && height < fluidHeight) { + DecoratedBiome biome, int height, int max) { + BiomeKind kind = biome.kind(); + int fluidHeight = scene.fluidHeight(); + if (kind == BiomeKind.SHORE && height < fluidHeight) { return; } - boolean underwater = isUnderwater(inferredType, height, fluidHeight); - boolean caveSkipFluid = skipsFluid(inferredType); + boolean underwater = isUnderwater(kind, height, fluidHeight); + boolean caveSkipFluid = skipsFluid(kind); RNG rng = getRNG(realX, realZ); ResolvedDecorator decorator = DecoratorCore.pickDecorator(decorators.decorators(biome, getPart()), rng, realX, realZ, decorators.log()); @@ -70,19 +54,18 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator { opts.underwater = underwater; opts.fluidHeight = fluidHeight; opts.caveSkipFluid = caveSkipFluid; - DecoratorCore.placeStackUp(decorator, x, z, realX, realZ, height, max, data, opts); + DecoratorCore.placeStackUp(decorator, scene, x, z, realX, realZ, height, max, opts); return; } - DecoratorCore.placeSurfaceSingle(decorator, x, z, realX, height, realZ, - data, underwater, caveSkipFluid, getEngine().getMantle(), decorators.log()); + DecoratorCore.placeSurfaceSingle(decorator, scene, x, z, realX, height, realZ, underwater, caveSkipFluid); } - static boolean isUnderwater(InferredType inferredType, int height, int fluidHeight) { - return height < fluidHeight && inferredType != InferredType.CAVE; + static boolean isUnderwater(BiomeKind kind, int height, int fluidHeight) { + return height < fluidHeight && kind != BiomeKind.CAVE; } - static boolean skipsFluid(InferredType inferredType) { - return inferredType == InferredType.CAVE; + static boolean skipsFluid(BiomeKind kind) { + return kind == BiomeKind.CAVE; } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java index f5166ba37..b9e19e593 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -21,22 +21,20 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.decorant.Decorator; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; import java.util.ArrayList; import java.util.List; import java.util.function.DoubleSupplier; /** - * One {@link Decorator} made ready for one world: its palettes resolved to the platform's blocks, and the noise that + * One {@link Decorator} made ready for one world: its palettes resolved to blocks, and the noise that * decides where it places, which block of the palette it picks and how tall it stacks, built when first asked for. What * the decorator describes stays in the settings; everything that needs the platform, the pack or the world seed is here. * @@ -47,17 +45,18 @@ final class ResolvedDecorator { private final Decorator settings; private final long seed; private final NoiseFactory noise; - private final List blocks; - private final List topBlocks; - private final PlatformBlockState[] blockArray; - private final PlatformBlockState[] topBlockArray; - private final PlatformBlockState forceBlock; - private final PlatformBlockState[] whitelist; - private final PlatformBlockState[] blacklist; + private final List blocks; + private final List topBlocks; + private final BlockState[] blockArray; + private final BlockState[] topBlockArray; + private final BlockState forceBlock; + private final BlockState[] whitelist; + private final BlockState[] blacklist; private final AtomicCache chanceNoise = new AtomicCache<>(); private final AtomicCache varianceNoise = new AtomicCache<>(); private final AtomicCache heightNoise = new AtomicCache<>(); private final ModuleLog log; + private final String biomeKey; /** * @param blocks the palette as the platform's blocks, each repeated by its weight @@ -66,43 +65,38 @@ final class ResolvedDecorator { * @param whitelist the blocks it may only be placed onto; ignored unless the decorator has a whitelist * @param blacklist the blocks it is never placed onto; ignored unless the decorator has a blacklist * @param log the log of the module that decorates + * @param biomeKey the key of the biome that declares the decorator, which names it in the log */ - ResolvedDecorator(Decorator settings, long seed, NoiseFactory noise, List blocks, List topBlocks, - PlatformBlockState forceBlock, List whitelist, List blacklist, - ModuleLog log) { + ResolvedDecorator(Decorator settings, long seed, NoiseFactory noise, List blocks, List topBlocks, + BlockState forceBlock, List whitelist, List blacklist, + ModuleLog log, String biomeKey) { this.settings = settings; this.seed = seed; this.noise = noise; this.blocks = List.copyOf(blocks); this.topBlocks = List.copyOf(topBlocks); - this.blockArray = blocks.toArray(new PlatformBlockState[0]); - this.topBlockArray = topBlocks.toArray(new PlatformBlockState[0]); + this.blockArray = blocks.toArray(new BlockState[0]); + this.topBlockArray = topBlocks.toArray(new BlockState[0]); this.forceBlock = forceBlock; - this.whitelist = whitelist.toArray(new PlatformBlockState[0]); - this.blacklist = blacklist.toArray(new PlatformBlockState[0]); + this.whitelist = whitelist.toArray(new BlockState[0]); + this.blacklist = blacklist.toArray(new BlockState[0]); this.log = log; + this.biomeKey = biomeKey; } - /** {@code settings} ready for {@code engine}: its blocks resolved through the pack, its noise seeded from {@code seed}. */ - static ResolvedDecorator of(Decorator settings, Engine engine, long seed, ModuleLog log) { - var resources = engine.getData().getPackResources(); + /** {@code settings} ready for a world with {@code resources}: its blocks resolved through the pack, its noise seeded from {@code seed}. */ + static ResolvedDecorator of(Decorator settings, PackResources resources, long seed, ModuleLog log, String biomeKey) { BlockRegistry registry = resources.blocks(); - PlatformBlockState forced = settings.forceBlock().map(spec -> platformState(registry, spec)).orElse(null); + BlockState forced = settings.forceBlock().map(registry::resolve).orElse(null); return new ResolvedDecorator(settings, seed, resources.noise(), weighted(registry, settings.palette()), - weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist()), log); + weighted(registry, settings.topPalette()), forced, each(registry, settings.whitelist()), each(registry, settings.blacklist()), log, + biomeKey); } - private static PlatformBlockState platformState(BlockRegistry registry, BlockSpec spec) { - return B.getState(registry.resolve(spec).key()); - } - - private static List weighted(BlockRegistry registry, List palette) { - List weighted = new ArrayList<>(); + private static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); for (BlockSpec spec : palette) { - PlatformBlockState state = platformState(registry, spec); - if (state == null) { - continue; - } + BlockState state = registry.resolve(spec); for (int n = 0; n < spec.weight(); n++) { weighted.add(state); } @@ -110,8 +104,8 @@ final class ResolvedDecorator { return weighted; } - private static List each(BlockRegistry registry, List palette) { - return palette.stream().map(spec -> platformState(registry, spec)).toList(); + private static List each(BlockRegistry registry, List palette) { + return palette.stream().map(registry::resolve).toList(); } Decorator settings() { @@ -148,7 +142,7 @@ final class ResolvedDecorator { } /** The block it forces onto the surface instead of the one found there, or null. */ - PlatformBlockState forceBlock() { + BlockState forceBlock() { return forceBlock; } @@ -161,15 +155,15 @@ final class ResolvedDecorator { } /** Whether the white and black lists keep the decorator off {@code surface}. */ - boolean rejectsSurface(PlatformBlockState surface) { + boolean rejectsSurface(BlockState surface) { if (settings.hasWhitelist() && !matches(whitelist, surface)) { return true; } return settings.hasBlacklist() && matches(blacklist, surface); } - private static boolean matches(PlatformBlockState[] palette, PlatformBlockState surface) { - for (PlatformBlockState state : palette) { + private static boolean matches(BlockState[] palette, BlockState surface) { + for (BlockState state : palette) { if (state.equals(surface)) { return true; } @@ -197,9 +191,9 @@ final class ResolvedDecorator { } /** The block of the palette at the position, for decorations that fill a column block by block; null when the palette has no block. */ - PlatformBlockState blockAt(IrisBiome biome, double x, double y, double z) { + BlockState blockAt(double x, double y, double z) { if (blocks.isEmpty()) { - log.warnOnce("decorator-empty:" + biome.getName(), "Empty Block Data for " + biome.getName()); + log.warnOnce("decorator-empty:" + biomeKey, "Empty Block Data for " + biomeKey); return null; } @@ -211,9 +205,9 @@ final class ResolvedDecorator { } /** The top palette's block at the position, or the palette's when there is no top palette; null where the chance noise declines. */ - PlatformBlockState topBlockAt(IrisBiome biome, double x, double y, double z) { + BlockState topBlockAt(double x, double y, double z) { if (topBlocks.isEmpty()) { - return blockAt(biome, x, y, z); + return blockAt(x, y, z); } double zoom = settings.style().zoom(); @@ -229,19 +223,19 @@ final class ResolvedDecorator { } /** The palette's block for the column, or null when the palette has no block. */ - PlatformBlockState pickBlock(double x, double z) { + BlockState pickBlock(double x, double z) { return pick(blockArray, x, z); } /** The top palette's block for the column; the palette's when there is no top palette. */ - PlatformBlockState pickTopBlock(double x, double z) { + BlockState pickTopBlock(double x, double z) { if (topBlockArray.length == 0) { return pickBlock(x, z); } return pick(topBlockArray, x, z); } - private PlatformBlockState pick(PlatformBlockState[] palette, double x, double z) { + private BlockState pick(BlockState[] palette, double x, double z) { if (palette.length == 0) { return null; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 41dd78bc4..e0af25ba4 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -85,7 +85,7 @@ public final class CarveModule implements IrisModule { } ModuleLog log = context.log(); chunk.state(CaveApplying.class, generating -> new CaveApplying(generating, log)).apply(chunk.originX() >> CHUNK_SHIFT, chunk.originZ() >> CHUNK_SHIFT, - chunk.blocks(), chunk.multicore(), chunk.context()); + chunk.blocks(), chunk.multicore(), chunk.context(), context); } /** diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 306822d7d..acd76e0bc 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -20,13 +20,13 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.engine.terrain.BiomeLayers; import art.arcane.iris.engine.terrain.TerrainPalettes; import art.arcane.iris.engine.decorator.IrisCeilingDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.InferredType; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.common.data.B; @@ -45,6 +45,8 @@ import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.slices.MarkerMatter; import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.ModuleLog; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeKind; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import lombok.Data; import art.arcane.iris.spi.PlatformBlockState; @@ -67,30 +69,25 @@ public class CaveApplying { private final RNG rng; private final PlatformBlockState AIR = B.getState("CAVE_AIR"); private final PlatformBlockState LAVA = B.getState("LAVA"); - private final BiomeDecorators decorators; private final BiomeLayers layers; private final TerrainPalettes palettes; - private final IrisSurfaceDecorator surfaceDecorator; - private final IrisCeilingDecorator ceilingDecorator; public CaveApplying(Engine engine, ModuleLog log) { this.engine = engine; rng = new RNG(engine.getSeedManager().getCarve()); - decorators = BiomeDecorators.of(engine); layers = BiomeLayers.of(engine, log); palettes = TerrainPalettes.of(engine); - surfaceDecorator = new IrisSurfaceDecorator(engine); - ceilingDecorator = new IrisCeilingDecorator(engine); } /** Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}. */ @ChunkCoordinates - public void apply(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + public void apply(int x, int z, Hunk output, boolean multicore, ChunkContext context, ChunkStageContext chunk) { PrecisionStopwatch caveStopwatch = PrecisionStopwatch.start(); Mantle mantle = engine.getMantle().getMantle(); Long2ObjectOpenHashMap caveBiomeCache = new Long2ObjectOpenHashMap<>(2048); IrisCarveScratch scratch = SCRATCH.get(); scratch.reset(); + scratch.decoration = DecorationScene.of(chunk); CarveWallBuffer walls = scratch.walls; CarveColumnMask[] columnMasks = scratch.columnMasks; CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; @@ -644,12 +641,19 @@ public class CaveApplying { } } - if (floorBiome != null && decorators.hasDecorators(floorBiome, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { - surfaceDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, floorBiome, InferredType.CAVE, zone.getFloor() - 1, zone.airThickness()); + DecorationScene scene = SCRATCH.get().decoration; + if (floorBiome != null) { + DecoratedBiome floor = IrisDecoratedBiomes.of(floorBiome, BiomeKind.CAVE); + if (scene.decorators().hasDecorators(floor, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { + new IrisSurfaceDecorator(scene).decorate(rx, rz, xx, xx, xx, zz, zz, zz, floor, zone.getFloor() - 1, zone.airThickness()); + } } - if (ceilingBiome != null && decorators.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { - ceilingDecorator.decorate(rx, rz, xx, xx, xx, zz, zz, zz, output, ceilingBiome, InferredType.CAVE, zone.getCeiling(), zone.airThickness()); + if (ceilingBiome != null) { + DecoratedBiome ceiling = IrisDecoratedBiomes.of(ceilingBiome, BiomeKind.CAVE); + if (scene.decorators().hasDecorators(ceiling, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY && B.isSolid(output.getRaw(rx, zone.getCeiling() + 1, rz))) { + new IrisCeilingDecorator(scene).decorate(rx, rz, xx, xx, xx, zz, zz, zz, ceiling, zone.getCeiling(), zone.airThickness()); + } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index f82faea84..f6c97f1ea 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -27,10 +27,10 @@ import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.engine.decorator.FloatingDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineDecorator; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -51,6 +51,7 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; import com.volmit.ModuleLog; +import com.volmit.world.BiomeKind; import java.util.IdentityHashMap; import static art.arcane.iris.engine.mantle.EngineMantle.AIR; @@ -66,7 +67,6 @@ public class FloatingIslands { }; private final Engine engine; private final RNG rng; - private final EngineDecorator seaSurfaceDecorator; private final BiomeLayers biomeLayers; private final ModuleLog log; @@ -212,7 +212,6 @@ public class FloatingIslands { this.engine = engine; this.log = log; rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); - seaSurfaceDecorator = new IrisSeaSurfaceDecorator(engine); biomeLayers = BiomeLayers.of(engine, log); } @@ -305,7 +304,7 @@ public class FloatingIslands { } /** Decorates the tops of the islands in the chunk whose first block is {@code x}, {@code z}. */ - public void decorateColumns(int x, int z, Hunk output, boolean multicore, ChunkContext context) { + public void decorateColumns(int x, int z, Hunk output, boolean multicore, ChunkContext context, DecorationScene scene) { int chunkHeight = output.getHeight(); IrisData data = engine.getData(); IrisComplex complex = engine.getComplex(); @@ -338,7 +337,7 @@ public class FloatingIslands { if (above == null || above.isAir()) { try { RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(baseSeed, wx, wz)); - FloatingDecorator.decorateColumn(engine, target, DecorationPart.NONE, xf, zf, wx, wz, topY, max, output, colRng, NOOP_DECORATION_MISS); + FloatingDecorator.decorateColumn(scene, IrisDecoratedBiomes.of(target, BiomeKind.LAND), DecorationPart.NONE, xf, zf, wx, wz, topY, max, colRng, NOOP_DECORATION_MISS); } catch (Throwable e) { log.error("Failed to decorate the top of a floating island", e); } @@ -370,7 +369,7 @@ public class FloatingIslands { } if (fluidTopY > 0 && fluidTopY + 1 < chunkHeight && B.isAir(output.get(xf, fluidTopY + 1, zf))) { try { - seaSurfaceDecorator.decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, output, target, fluidTopY, chunkHeight); + new IrisSeaSurfaceDecorator(scene).decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, IrisDecoratedBiomes.of(target, BiomeKind.LAND), fluidTopY, chunkHeight); } catch (Throwable e) { log.error("Failed to decorate the sea surface of a floating island", e); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 75db8e168..3603640aa 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -23,6 +23,7 @@ import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; import com.volmit.FeatureRegistry; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisChunk; +import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; @@ -65,7 +66,8 @@ public final class FloatingModule implements IrisModule { .run(FloatingModule::objects); // Ordering only: iris:post ships in the built-ins jar, which a pack may not have. graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH.ref()).run(FloatingModule::solids); - graph.define(IrisStages.Floating.DECORATE).requires(IrisStages.Decorant.DECORATE).run(FloatingModule::decorate); + // Ordering only: iris:decorant ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Floating.DECORATE).softAfter(IrisStages.Decorant.DECORATE.ref()).run(FloatingModule::decorate); } private static void objects(MantleStageContext context) { @@ -84,7 +86,8 @@ public final class FloatingModule implements IrisModule { private static void decorate(ChunkStageContext context) { IrisChunk chunk = IrisChunk.current(); - islands(chunk, context.log()).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + islands(chunk, context.log()).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context(), + DecorationScene.of(context)); } private static FloatingObjectPlacing objectPlacing(Engine engine, ModuleLog log) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java index a2e51e88d..e488422db 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; @@ -34,6 +35,8 @@ final class IrisCarveScratch { final Map customBiomeCache = new HashMap<>(); int[] upperSurfaceHeights; boolean customCaveBiomePresent; + /** The chunk being carved, for the cave decorators; set by each apply. */ + DecorationScene decoration; IrisCarveScratch() { for (int index = 0; index < columnMasks.length; index++) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java b/src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java new file mode 100644 index 000000000..48bcd0c1d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java @@ -0,0 +1,33 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.object.world.biome.IrisBiome; +import com.volmit.world.BiomeKind; + +/** The decorators' view of a biome Iris's carving and floating islands hold as an {@link IrisBiome}. */ +final class IrisDecoratedBiomes { + private IrisDecoratedBiomes() { + } + + static DecoratedBiome of(IrisBiome biome, BiomeKind kind) { + return new DecoratedBiome(biome.getLoadKey(), biome.getModuleSettings().find(DecorantSettings.class).orElse(null), kind); + } +} 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 index a8882ca8d..2ba60b158 100644 --- 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 @@ -18,7 +18,8 @@ package art.arcane.iris.engine.object.world.biome; -import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecoratorLoad; import art.arcane.iris.engine.terrain.BiomeLayers; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.framework.Engine; @@ -77,8 +78,11 @@ final class IrisBiomeColorRenderer { } case DECORATOR_LOAD -> { return biome.getCacheColorDecoratorLoad().aquire(() -> { - BiomeDecorators decorators = BiomeDecorators.of(engine); - return Color.getHSBColor(0.41f, (float) (decorators.colourLoad(biome) / decorators.busiestBiomeLoad()), 1f); + 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 -> { @@ -91,4 +95,8 @@ final class IrisBiomeColorRenderer { return Color.black; } + + 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/dimension/IrisDimension.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java index 327edb132..67db0f231 100644 --- 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 @@ -148,8 +148,6 @@ public class IrisDimension extends IrisRegistrant { 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("Generate decorations or not") - private boolean decorate = true; @Desc("Refuse to place surface objects and trees over carved surface openings.") private boolean requireObjectSurfaceSupport = true; @MinNumber(0) From ed8c33fca785430944a6a72e5e0d40ae0507b0eb Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:19:37 +0200 Subject: [PATCH 078/139] iris:objects and iris:post only order after iris:carve; README --- README.md | 14 ++++++++--- .../mantle/components/ObjectModule.java | 3 ++- .../iris/engine/modifier/PostModule.java | 3 ++- .../floating/ResolvedFloatingChild.java | 23 +++++++++++++++---- 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 3c3ad9e5f..0ae66aff9 100644 --- a/README.md +++ b/README.md @@ -137,12 +137,12 @@ naming the class and what it uses. A VolmLib class that Iris's Bukkit jar strips `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. -The jar holds `iris:post`, `iris:perfection` and `iris:matter`. They are written against IrisApi and +The jar holds `iris:post`, `iris:perfection`, `iris:matter` and `iris:carve`. They are written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks. Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting `iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, -`iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder +`iris:objects`, `iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to `builtin-modules.txt`): add a module to the jar and to that list together. @@ -150,4 +150,12 @@ when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, wh every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the same) and `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same layers, and a layer's noise is built once per world by whichever asks first). `iris:post` reads its switches -(`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. \ No newline at end of file +(`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. + +`iris:carve` also reads the mantle's matter slices through `MatterMantle` (a facade Iris's mantle implements: the chunk of +`MatterCavern`s and markers it plans and applies, which the platform and the rest of Iris read as slices, not as module layers) and asks +`CaveDressing` for what the biome layers, decorators and fluid palette give a cave's walls, floor and ceiling. `CaveDressing` is +transitional: it goes when `iris:terrain` and `iris:decorant` are modules of the same jar and carve asks their classes directly. +A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its +absolute world Y bands convert with `PackWorld.minHeight()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read) +and `scaled(...)`. `caveLavaHeight` and `upperDimensionCarving` are its dimension settings. \ No newline at end of file diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index b4b572e9b..9566e8dfb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -63,7 +63,8 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Objects.PLACE).requires(IrisStages.Carve.CAVES).reach(this::reach).run(ObjectModule::place); + // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES.ref()).reach(this::reach).run(ObjectModule::place); } @Override diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index 7aa2578af..7b99a0856 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -45,6 +45,7 @@ public final class PostModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Post.SMOOTH).requires(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); + // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY.ref()).run(SurfaceSmoothing::smooth); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index 6949b9003..6001176fe 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -18,6 +18,8 @@ package art.arcane.iris.engine.object.terrain.floating; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.core.loader.IrisData; @@ -28,8 +30,6 @@ import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObjectScale; -import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; -import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.iris.engine.object.value.IRare; import art.arcane.iris.engine.object.world.biome.IrisBiome; @@ -37,6 +37,8 @@ import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import java.util.List; + /** * A {@link FloatingChildBiome} made ready for one engine: the noise its styles build (each from the world seed it is first * asked with), the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. The @@ -157,10 +159,10 @@ public final class ResolvedFloatingChild implements IRare { return null; } - CarvingResolver resolver = CarvingResolver.of(engine.getGeneration().world()); - ResolvedCarvingEntry entry = resolver.index().get(carving); + CarvingEntry entry = dimensionCarvingEntry(carving, engine); if (entry != null) { - return resolver.entryBiome(entry) == null || data.getBiomeLoader() == null ? null : data.getBiomeLoader().load(entry.biomeKey().trim()); + String biomeKey = entry.biome().trim(); + return biomeKey.isEmpty() || data.getBiomeLoader() == null ? null : data.getBiomeLoader().load(biomeKey); } if (data.getBiomeLoader() == null) { @@ -170,6 +172,17 @@ public final class ResolvedFloatingChild implements IRare { return data.getBiomeLoader().load(carving); } + /** The dimension's carving entry with this id (the last of several with one id); null when it declares none. */ + private static CarvingEntry dimensionCarvingEntry(String id, Engine engine) { + CarvingEntry found = null; + for (CarvingEntry entry : engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of())) { + if (entry != null && !entry.id().isBlank() && entry.id().trim().equals(id)) { + found = entry; + } + } + return found; + } + public KList resolveTopObjects(IrisBiome target) { KList surfaceObjects = (settings.inheritObjects() && target != null) ? target.getSurfaceObjects() : new KList<>(); return resolveTopObjectsFromSurface(surfaceObjects); From 965adea59e7294af5debcbc94413605b6db9cac3 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:19:49 +0200 Subject: [PATCH 079/139] Structure placements become iris:structure settings under the key packs always wrote The "structures" lists of dimensions, regions and biomes are StructurePlacementSettings (iris:structure/placements): StructurePlacement and NativeStructureSource with every option, default and description of IrisStructurePlacement and IrisNativeStructure, and StructureAnchorMode, StructureDistribution and NativeStructureSuppression with their constants in the same order (placement identities hash the ordinals). The host fields and classes are deleted, as is the RegistryListStructure annotation only they used. Every reader asks StructurePlacementScope.placementsOf(owner); the scope index of which levels declare placements lives in the world's state. --- README.md | 10 +- .../structure/NativeStructureSource.java | 64 ++++++ .../NativeStructureSuppression.java} | 24 ++- .../structure/StructureAnchorMode.java | 54 +++++ .../structure/StructureDistribution.java | 9 +- .../structure/StructurePlacement.java} | 182 +++++++++++++---- .../structure/StructurePlacementSettings.java | 48 +++++ .../framework/IrisStructureLocator.java | 184 ++++++++---------- .../StructureCaveAnchorResolver.java | 44 ++--- .../framework/StructurePlacementGrid.java | 126 ++++++------ .../framework/StructurePlacementScope.java | 109 ++++------- .../structure/NativeStartPlanner.java | 54 +++-- .../structure/StructureVanillaStructures.java | 19 +- .../mantle/components/StructureModule.java | 12 +- .../mantle/components/StructurePlacing.java | 25 +-- .../structure/IrisStructureAnchorMode.java | 34 ---- .../vanilla/IrisNativeStructure.java | 30 --- .../vanilla/NativeStructureSuppression.java | 12 -- .../engine/object/world/biome/IrisBiome.java | 4 - .../object/world/dimension/IrisDimension.java | 4 - .../object/world/region/IrisRegion.java | 4 - 21 files changed, 586 insertions(+), 466 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java rename src/main/java/art/arcane/iris/{engine/object/annotations/RegistryListStructure.java => builtin/structure/NativeStructureSuppression.java} (50%) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java rename src/main/java/art/arcane/iris/{engine/object => builtin}/structure/StructureDistribution.java (81%) rename src/main/java/art/arcane/iris/{engine/object/structure/IrisStructurePlacement.java => builtin/structure/StructurePlacement.java} (55%) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java diff --git a/README.md b/README.md index 94d9f5fed..e5babd863 100644 --- a/README.md +++ b/README.md @@ -34,11 +34,12 @@ replacement) wherever Iris validates a pack; Iris core has no loader or validato Built-in modules answer Iris through IrisApi services instead of Iris reading their features: `iris:objects` provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure` provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a -world places, and their nearest start for the find commands). `iris:structure` also has a lifecycle hook that drops a -world's structure index when the world stops, which includes every reload of the pack's structure files. +world places, and their nearest start for the find commands). A world's structure index lives in the world's state +(`engine.getGeneration().state(...)`), so every reload of the pack's structure files, which starts a new world, builds +it again. `iris:structure` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: which ones its placements replace or the dimension's `importedStructures` disables, the starts its `nativeStructures` -placements make, the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, +placements make (`startedStructures`, `locatableStarts`, `locateStart`), the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, PRESERVE, VACUUM, ENCASE, BORE, FORCE_CARVE, stilts) in `engine/framework/structure/fit`, written against IrisApi's `StructureFit` and `BlockAccess` only. A start carries its fit as a memo (its terrain and stilts JSON), so every chunk it reaches and every restart fits it the same way. `iris:vanilla-features` (`VanillaFeaturesModule`, no stages) @@ -107,7 +108,8 @@ dimension reaches learn of them without reading the settings classes; and `iris: (`CaveBiomeBands`), which Iris asks for the dimension's carving band at a position and for a biome's minimum cave depth. Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` -(biome; a list) and `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest). The feature ids +(biome; a list), `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest) and `structures` +(dimension, region, biome; a list of `StructurePlacement`s, `StructurePlacementSettings`). The feature ids (`iris:deposit`, `iris:decorant`, `iris:structure`) stay the modules' identity in the stage graph and logs. A key is unique per target across all modules and Iris's own fields, so a new built-in or pack module picks a key no field of the target uses. diff --git a/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java b/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java new file mode 100644 index 000000000..8cb515fdd --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSource.java @@ -0,0 +1,64 @@ +/* + * 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.builtin.structure; + +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.vanilla.JigsawOverrides; + +import java.util.Optional; + +/** + * One platform structure a structure placement starts itself, written as + * {@code {"structure": "minecraft:ancient_city", "weight": 2, "jigsaw": {...}}}. IrisApi types only. + */ +@Desc("A live vanilla, datapack, or modded structure generated by Minecraft at an Iris-controlled placement.") +public final class NativeStructureSource { + @Required + @Ref(Reference.STRUCTURE) + @Desc("Registered structure key. The source retains its native generator, pieces, templates, processors, entities, markers, and data.") + private String structure = ""; + + @MinNumber(1) + @Desc("Relative selection weight when a placement offers multiple native structure sources.") + private int weight = 1; + + @Desc("Optional jigsaw-only assembly overrides. Null preserves the complete registered structure definition.") + private JigsawOverrides jigsaw = null; + + public NativeStructureSource() { + } + + /** The registry key of the platform structure, as the pack wrote it. */ + public String structure() { + return structure; + } + + public int weight() { + return weight; + } + + /** The overrides of the platform's jigsaw assembly; empty to keep its own. */ + public Optional jigsaw() { + return Optional.ofNullable(jigsaw); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java b/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSuppression.java similarity index 50% rename from src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java rename to src/main/java/art/arcane/iris/builtin/structure/NativeStructureSuppression.java index 8f985907c..8522a480e 100644 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListStructure.java +++ b/src/main/java/art/arcane/iris/builtin/structure/NativeStructureSuppression.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,18 +16,16 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.annotations; +package art.arcane.iris.builtin.structure; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; +import com.volmit.config.Desc; -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 RegistryListStructure { +/** Whether a structure placement replaces the platform structure its structures stand in for. */ +@Desc("Controls whether an Iris structure placement suppresses its imported native source.") +public enum NativeStructureSuppression { + @Desc("Leaves native generation enabled alongside this Iris structure placement.") + NONE, + @Desc("Suppresses the structure's vanillaSource when used by a validated dimension-level replacement placement.") + REPLACE_SOURCE } diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java b/src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java new file mode 100644 index 000000000..7fbeb7900 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureAnchorMode.java @@ -0,0 +1,54 @@ +/* + * 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.builtin.structure; + +import com.volmit.config.Desc; + +/** How a structure placement picks the height it anchors a structure at. The placement identity hashes the order. */ +@Desc("Selects the vertical environment used to anchor an Iris structure placement.") +public enum StructureAnchorMode { + @Desc("Preserve the historical underground boolean behavior.") + LEGACY, + + @Desc("Anchor to the terrain surface and use minHeight/maxHeight as a surface gate.") + SURFACE, + + @Desc("Choose a deterministic Y inside the minHeight/maxHeight band.") + HEIGHT_BAND, + + @Desc("Anchor in carved space with solid support below.") + CAVE_FLOOR, + + @Desc("Anchor in carved space with solid support above.") + CAVE_CEILING, + + @Desc("Anchor in carved space without nearby floor or ceiling support.") + CAVE_CENTER, + + @Desc("Anchor at any carved-space position.") + CAVE_ANY; + + /** Whether the anchor looks for carved space. */ + public boolean isCave() { + return switch (this) { + case CAVE_FLOOR, CAVE_CEILING, CAVE_CENTER, CAVE_ANY -> true; + default -> false; + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java b/src/main/java/art/arcane/iris/builtin/structure/StructureDistribution.java similarity index 81% rename from src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java rename to src/main/java/art/arcane/iris/builtin/structure/StructureDistribution.java index 9add7fdf5..9a42c935a 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/StructureDistribution.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureDistribution.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,10 +16,11 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.structure; +package art.arcane.iris.builtin.structure; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; +/** How a structure placement scatters its starts. The placement identity hashes the order. */ @Desc("Controls how structure start positions are scattered across the world.") public enum StructureDistribution { @Desc("Vanilla-style spacing/separation grid. One placement attempt per grid cell, randomly offset within it by the separation. Use spacing, separation and salt.") diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java similarity index 55% rename from src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java rename to src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java index d7d5315c9..465b30ceb 100644 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructurePlacement.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -16,39 +16,37 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.structure; +package art.arcane.iris.builtin.structure; -import art.arcane.iris.builtin.structure.StructureStilts; -import art.arcane.iris.builtin.structure.StructureTerrain; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; -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.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.RegistryListStructure; -import art.arcane.volmlib.util.collection.KList; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import art.arcane.iris.engine.object.structure.IrisStructure; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.ResourceRef; -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +/** + * Where and how often the structures of a dimension, region or biome start, written as one entry of its + * {@code "structures": [...]}: the pack's own structures to assemble or the platform's to start natively, the + * distribution of the starts, the height they anchor at, and how they meet the terrain. IrisApi types only, besides + * the structure resource kind the {@code structures} keys name. + */ @Desc("Attaches structures to a biome, region or dimension and controls where and how often they generate. This is independent of a structure's own native generation, so you can add custom placements in tandem with native generation or instead of it.") -@Data -public class IrisStructurePlacement { - @ArrayType(type = String.class, min = 1) - @RegistryListStructure +public final class StructurePlacement { + @MinItems(1) + @ResourceRef(IrisStructure.class) @Desc("Editable Iris assembly resources offered by this placement. Leave empty when nativeStructures supplies the source.") - private KList structures = new KList<>(); + private List structures = List.of(); - @ArrayType(type = IrisNativeStructure.class, min = 1) + @MinItems(1) @Desc("Live registered vanilla, datapack, and modded structures offered by this placement. Minecraft runs their native generator directly, independent of normal biome or dimension eligibility.") - private KList nativeStructures = new KList<>(); + private List nativeStructures = List.of(); @Desc("Stable authored identity for this placement. Set this when multiple placements use the same structure and settings. When empty, Iris derives identity from the placement content so list reordering does not move generated structures.") private String placementId = ""; @@ -98,12 +96,12 @@ public class IrisStructurePlacement { private boolean underground = false; @Desc("Vertical anchor policy. LEGACY preserves the underground boolean. Cave modes search existing carved-space data and implicitly behave as underground placements.") - private IrisStructureAnchorMode anchor = IrisStructureAnchorMode.LEGACY; + private StructureAnchorMode anchor = StructureAnchorMode.LEGACY; - @RegistryListResource(IrisBiome.class) - @ArrayType(type = String.class, min = 1) + @MinItems(1) + @Ref(Reference.PACK_BIOME) @Desc("Optional cave-biome allowlist for cave anchor modes. Empty accepts the cave biome resolved at the selected anchor. Entries match by load key, including prefix matches.") - private KList caveBiomes = new KList<>(); + private List caveBiomes = List.of(); @MinNumber(1) @MaxNumber(64) @@ -129,27 +127,129 @@ public class IrisStructurePlacement { @Desc("If false, the placement is skipped when its selected surface or cave column is submerged.") private boolean underwater = false; + public StructurePlacement() { + } + + /** Keys of the pack's structures the placement assembles, one picked per start. */ + public List structures() { + return listOrEmpty(structures); + } + + /** The platform structures the placement starts natively, one picked per start by weight. */ + public List nativeStructures() { + return listOrEmpty(nativeStructures); + } + + public String placementId() { + return placementId; + } + + public NativeStructureSuppression nativeSuppression() { + return nativeSuppression == null ? NativeStructureSuppression.NONE : nativeSuppression; + } + + public StructureDistribution distribution() { + return distribution == null ? StructureDistribution.RANDOM_SPREAD : distribution; + } + + public int spacing() { + return spacing; + } + + public int separation() { + return separation; + } + + public int salt() { + return salt; + } + + public double density() { + return density; + } + + public int ringCount() { + return ringCount; + } + + public int ringDistance() { + return ringDistance; + } + + public int ringSpread() { + return ringSpread; + } + + public int minHeight() { + return minHeight; + } + + public int maxHeight() { + return maxHeight; + } + + public boolean underground() { + return underground; + } + + /** The anchor as written; {@link #resolvedAnchor} says what {@code LEGACY} means for this placement. */ + public StructureAnchorMode anchor() { + return anchor == null ? StructureAnchorMode.LEGACY : anchor; + } + + /** Cave biome keys or key prefixes a cave anchor accepts; empty for any. */ + public List caveBiomes() { + return listOrEmpty(caveBiomes); + } + + public int caveAnchorAttempts() { + return caveAnchorAttempts; + } + + public int caveAnchorScanStep() { + return caveAnchorScanStep; + } + + public int caveMinimumClearance() { + return caveMinimumClearance; + } + + /** How the placement's structures meet the terrain; the defaults when the pack wrote none. */ public StructureTerrain resolvedTerrain() { return terrain == null ? new StructureTerrain() : terrain; } + /** The foundation columns under the structures; empty for none. */ + public Optional stilt() { + return Optional.ofNullable(stilt); + } + + public boolean underwater() { + return underwater; + } + public boolean hasIrisStructures() { - return structures != null && !structures.isEmpty(); + return !structures().isEmpty(); } public boolean hasNativeStructures() { - return nativeStructures != null && !nativeStructures.isEmpty(); + return !nativeStructures().isEmpty(); } - public IrisStructureAnchorMode resolvedAnchor() { - if (anchor == null || anchor == IrisStructureAnchorMode.LEGACY) { - return underground ? IrisStructureAnchorMode.HEIGHT_BAND : IrisStructureAnchorMode.SURFACE; + /** The anchor this placement uses: {@code LEGACY} is the band when {@link #underground}, else the surface. */ + public StructureAnchorMode resolvedAnchor() { + if (anchor() == StructureAnchorMode.LEGACY) { + return underground ? StructureAnchorMode.HEIGHT_BAND : StructureAnchorMode.SURFACE; } - return anchor; + return anchor(); } public boolean isAnchoredUnderground() { - IrisStructureAnchorMode activeAnchor = resolvedAnchor(); - return activeAnchor == IrisStructureAnchorMode.HEIGHT_BAND || activeAnchor.isCave(); + StructureAnchorMode activeAnchor = resolvedAnchor(); + return activeAnchor == StructureAnchorMode.HEIGHT_BAND || activeAnchor.isCave(); + } + + private static List listOrEmpty(List list) { + return list == null ? List.of() : Collections.unmodifiableList(list); } } diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java new file mode 100644 index 000000000..32eaffff3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java @@ -0,0 +1,48 @@ +/* + * 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.builtin.structure; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MinItems; + +import java.util.Collections; +import java.util.List; + +/** + * The structure placements of a dimension, region or biome, written as {@code "structures": [...]}: one + * {@link StructurePlacement} per entry. IrisApi types only. + */ +@Desc("Iris structure placements of this dimension, region or biome: where and how often its structures start.") +@Feature(id = "iris:structure/placements", name = "Structure placements", key = "structures", root = "placements", + targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +public final class StructurePlacementSettings implements IrisFeature { + @MinItems(1) + @Desc("Iris structure placements, each independent of the others.") + private List placements = List.of(); + + public StructurePlacementSettings() { + } + + public List placements() { + return placements == null ? List.of() : Collections.unmodifiableList(placements); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index f40dc0d7f..f9b7df408 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -26,17 +26,17 @@ 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.engine.object.structure.vanilla.IrisNativeStructure; +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.engine.object.structure.IrisStructureAnchorMode; +import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +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.engine.object.structure.vanilla.NativeStructureSuppression; -import art.arcane.iris.engine.object.structure.StructureDistribution; +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; @@ -170,7 +170,7 @@ public final class IrisStructureLocator { if (engine == null || key == null || key.isBlank()) { return false; } - for (IrisStructurePlacement placement : index(engine).placements) { + for (StructurePlacement placement : index(engine).placements) { if (placement.hasIrisStructures() && matches(placement, key, engine.getData())) { return true; } @@ -282,8 +282,8 @@ public final class IrisStructureLocator { CandidateBudget candidateBudget) { LocatedCandidate best = null; Set checkedChunks = new LinkedHashSet<>(); - for (IrisStructurePlacement placement : catalog.concentricRings()) { - int count = Math.max(1, placement.getRingCount()); + 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( @@ -421,8 +421,8 @@ public final class IrisStructureLocator { } Set checkedRingChunks = new LinkedHashSet<>(); - for (IrisStructurePlacement placement : catalog.concentricRings) { - int count = Math.max(1, placement.getRingCount()); + 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); @@ -488,13 +488,13 @@ public final class IrisStructureLocator { && Math.abs((long) chunkZ - centerChunkZ) <= radius; } - public static ResolvedPlacement resolvePlacement(Engine engine, IrisStructurePlacement placement, int cx, int cz) { + 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() || placement.getDistribution() == null) { - throw new IllegalStateException("Iris structure placement is missing its distribution or structure list"); + 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)) { @@ -580,18 +580,18 @@ public final class IrisStructureLocator { return new ResolvedPlacement(placement, selectedKey, structure, pieces, rng, originX, baseY, originZ, exactY); } - public static boolean requirePlacementOutput(IrisStructurePlacement placement, String structureKey, + 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.getNativeSuppression()) { + || NativeStructureSuppression.REPLACE_SOURCE != placement.nativeSuppression()) { return false; } String key = structureKey == null || structureKey.isBlank() - ? String.valueOf(placement.getStructures()) : structureKey; + ? 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 @@ -614,13 +614,13 @@ public final class IrisStructureLocator { String normalizedKey = normalize(key); if (hasNativePlacement(engine, key)) { for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(engine, cx, cz)) { - if (normalize(plan.source().getStructure()).equals(normalizedKey)) { + if (normalize(plan.source().structure()).equals(normalizedKey)) { return new ResolvedStart(cx << 4, plan.baseY(), cz << 4); } } } - KList placements = StructurePlacementScope.placementsAt(engine, cx, cz); - for (IrisStructurePlacement placement : placements) { + KList placements = StructurePlacementScope.placementsAt(engine, cx, cz); + for (StructurePlacement placement : placements) { if (!matches(placement, key, data)) { continue; } @@ -638,7 +638,7 @@ public final class IrisStructureLocator { private static PlacementAnchor resolveAnchor( Engine engine, - IrisStructurePlacement placement, + StructurePlacement placement, int chunkX, int chunkZ, int originX, @@ -654,29 +654,29 @@ public final class IrisStructureLocator { return baseY == null ? null : new PlacementAnchor(originX, baseY, originZ); } - private static Integer resolveBaseY(Engine engine, IrisStructurePlacement placement, int originX, int originZ, RNG rng) { + 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.isUnderwater() + if (!placement.underwater() && NativeStartPlanner.isSubmerged(engine, originX, originZ)) { return null; } - if (placement.resolvedAnchor() == IrisStructureAnchorMode.SURFACE) { + if (placement.resolvedAnchor() == StructureAnchorMode.SURFACE) { int surfaceY = engine.getHeight(originX, originZ, true) + engine.getMinHeight(); - return surfaceY < placement.getMinHeight() || surfaceY > placement.getMaxHeight() ? null : surfaceY; + return surfaceY < placement.minHeight() || surfaceY > placement.maxHeight() ? null : surfaceY; } - int bandMin = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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, IrisStructurePlacement placement, + static Integer resolveVerticalShift(KList pieces, StructurePlacement placement, int baseY, int worldMin, int worldMax) { int[] bounds = computeBounds(pieces); if (bounds == null) { @@ -685,8 +685,8 @@ public final class IrisStructureLocator { if (!placement.isAnchoredUnderground() || placement.resolvedAnchor().isCave()) { return bounds[1] >= worldMin && bounds[4] <= worldMax ? 0 : null; } - int bandMin = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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) { @@ -702,7 +702,7 @@ public final class IrisStructureLocator { } static Integer resolveUndergroundBurialShift(Engine engine, KList pieces, - IrisStructurePlacement placement, int baseY, + StructurePlacement placement, int baseY, int worldMin, int worldMax) { int[] bounds = computeBounds(pieces); if (engine == null || bounds == null || placement == null || !placement.isAnchoredUnderground() @@ -721,8 +721,8 @@ public final class IrisStructureLocator { 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.getMinHeight(), placement.getMaxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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) { @@ -786,19 +786,19 @@ public final class IrisStructureLocator { return maximumShift; } - static String selectStructureKey(IrisStructurePlacement placement, RNG rng) { - if (placement == null || placement.getStructures() == null || placement.getStructures().isEmpty()) { + static String selectStructureKey(StructurePlacement placement, RNG rng) { + if (placement == null || placement.structures().isEmpty()) { return null; } - return placement.getStructures().get(rng.nextInt(placement.getStructures().size())); + return placement.structures().get(rng.nextInt(placement.structures().size())); } static KList alignCavePieces( KList pieces, - IrisStructurePlacement placement, + StructurePlacement placement, int anchorY ) { - IrisStructureAnchorMode mode = placement.resolvedAnchor(); + StructureAnchorMode mode = placement.resolvedAnchor(); if (!mode.isCave()) { return pieces; } @@ -816,7 +816,7 @@ public final class IrisStructureLocator { } private static KList alignSurfacePieces(KList pieces, - IrisStructurePlacement placement, + StructurePlacement placement, IrisStructure structure, int baseY) { if (placement.isAnchoredUnderground() || pieces.size() <= 1 || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) { @@ -826,7 +826,7 @@ public final class IrisStructureLocator { return bounds == null ? pieces : shiftPieces(pieces, baseY - bounds[1]); } - static boolean hasExactY(IrisStructurePlacement placement, IrisStructure structure, + static boolean hasExactY(StructurePlacement placement, IrisStructure structure, KList pieces) { return placement.isAnchoredUnderground() || pieces.size() > 1 || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT); @@ -893,39 +893,38 @@ public final class IrisStructureLocator { private static PlacementCatalog collectPlacementCatalog(Engine engine, String key) { Set randomSpread = new LinkedHashSet<>(); - List concentricRings = new ArrayList<>(); + List concentricRings = new ArrayList<>(); boolean hasDensity = false; - for (IrisStructurePlacement placement : index(engine).placements) { + for (StructurePlacement placement : index(engine).placements) { if (!isSearchablePlacement(engine, placement) || !matches(placement, key, engine.getData())) { continue; } - if (placement.getDistribution() == StructureDistribution.RANDOM_SPREAD) { + if (placement.distribution() == StructureDistribution.RANDOM_SPREAD) { randomSpread.add(new RandomSpreadParameters( - Math.max(1, placement.getSpacing()), placement.getSeparation(), + Math.max(1, placement.spacing()), placement.separation(), StructurePlacementGrid.placementSalt(placement))); - } else if (placement.getDistribution() == StructureDistribution.CONCENTRIC_RINGS) { + } else if (placement.distribution() == StructureDistribution.CONCENTRIC_RINGS) { concentricRings.add(placement); - } else if (placement.getDistribution() == StructureDistribution.DENSITY) { + } else if (placement.distribution() == StructureDistribution.DENSITY) { hasDensity = true; } } return new PlacementCatalog(List.copyOf(randomSpread), List.copyOf(concentricRings), hasDensity); } - static boolean isSearchableDensityPlacement(Engine engine, IrisStructurePlacement placement) { + static boolean isSearchableDensityPlacement(Engine engine, StructurePlacement placement) { return placement != null - && placement.getDistribution() == StructureDistribution.DENSITY + && placement.distribution() == StructureDistribution.DENSITY && isSearchablePlacement(engine, placement); } - static boolean isSearchablePlacement(Engine engine, IrisStructurePlacement placement) { - if (engine == null || placement == null || placement.getDistribution() == null - || engine.getHeight() <= 0) { + static boolean isSearchablePlacement(Engine engine, StructurePlacement placement) { + if (engine == null || placement == null || engine.getHeight() <= 0) { return false; } - if (placement.getDistribution() == StructureDistribution.DENSITY - && !(placement.getDensity() > 0.0)) { + if (placement.distribution() == StructureDistribution.DENSITY + && !(placement.density() > 0.0)) { return false; } long worldMin = (long) engine.getMinHeight() + (placement.isAnchoredUnderground() ? 1L : 0L); @@ -935,11 +934,11 @@ public final class IrisStructureLocator { return false; } long configuredMin = placement.isAnchoredUnderground() - ? Math.min(placement.getMinHeight(), placement.getMaxHeight()) - : placement.getMinHeight(); + ? Math.min(placement.minHeight(), placement.maxHeight()) + : placement.minHeight(); long configuredMax = placement.isAnchoredUnderground() - ? Math.max(placement.getMinHeight(), placement.getMaxHeight()) - : placement.getMaxHeight(); + ? Math.max(placement.minHeight(), placement.maxHeight()) + : placement.maxHeight(); return configuredMin <= configuredMax && configuredMin <= worldMax && configuredMax >= worldMin; } @@ -1017,22 +1016,17 @@ public final class IrisStructureLocator { private record PlacementAnchor(int x, int y, int z) { } - private static boolean matches(IrisStructurePlacement placement, String key, IrisData data) { + private static boolean matches(StructurePlacement placement, String key, IrisData data) { if (placement == null || key == null || data == null) { return false; } String normalizedKey = normalize(key); - if (placement.getNativeStructures() != null) { - for (IrisNativeStructure source : placement.getNativeStructures()) { - if (source != null && normalize(source.getStructure()).equals(normalizedKey)) { - return true; - } + for (NativeStructureSource source : placement.nativeStructures()) { + if (source != null && normalize(source.structure()).equals(normalizedKey)) { + return true; } } - if (placement.getStructures() == null) { - return false; - } - for (String structureKey : placement.getStructures()) { + for (String structureKey : placement.structures()) { if (structureKey == null || structureKey.isBlank()) { continue; } @@ -1085,18 +1079,18 @@ public final class IrisStructureLocator { Set normalizedEditableKeys = new LinkedHashSet<>(); Set nativeKeys = new LinkedHashSet<>(); Set normalizedNativeKeys = new LinkedHashSet<>(); - for (IrisStructurePlacement placement : index(engine).placements) { + for (StructurePlacement placement : index(engine).placements) { if (!isSearchablePlacement(engine, placement)) { continue; } if (placement.hasNativeStructures()) { - for (IrisNativeStructure source : placement.getNativeStructures()) { - addLocatableKey(source.getStructure(), keys, normalizedKeys); - addLocatableKey(source.getStructure(), nativeKeys, normalizedNativeKeys); + for (NativeStructureSource source : placement.nativeStructures()) { + addLocatableKey(source.structure(), keys, normalizedKeys); + addLocatableKey(source.structure(), nativeKeys, normalizedNativeKeys); } continue; } - for (String structureKey : placement.getStructures()) { + for (String structureKey : placement.structures()) { IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { throw new IllegalStateException( @@ -1135,13 +1129,13 @@ public final class IrisStructureLocator { Set normalizedLoadKeys = new LinkedHashSet<>(); Set vanillaAliases = new LinkedHashSet<>(); Set suppressedVanillaSources = new LinkedHashSet<>(); - List placements = new ArrayList<>(); - collect(engine.getDimension().getStructures(), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, + 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(region == null ? null : region.getStructures(), data, log, + collect(StructurePlacementScope.placementsOf(region), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, suppressedVanillaSources, placements, false); } @@ -1149,7 +1143,7 @@ public final class IrisStructureLocator { KList biomes = engine.getDimension().getReachableBiomes(engine); if (biomes != null) { for (IrisBiome biome : biomes) { - collect(biome == null ? null : biome.getStructures(), data, log, + collect(StructurePlacementScope.placementsOf(biome), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, suppressedVanillaSources, placements, false); } @@ -1163,48 +1157,42 @@ public final class IrisStructureLocator { List.copyOf(placements)); } - private static Set nativeKeys(List placements) { + private static Set nativeKeys(List placements) { Set nativeKeys = new LinkedHashSet<>(); - for (IrisStructurePlacement placement : placements) { + for (StructurePlacement placement : placements) { if (!placement.hasNativeStructures()) { continue; } - for (IrisNativeStructure source : placement.getNativeStructures()) { + for (NativeStructureSource source : placement.nativeStructures()) { if (source != null) { - nativeKeys.add(normalize(source.getStructure())); + nativeKeys.add(normalize(source.structure())); } } } return Collections.unmodifiableSet(nativeKeys); } - private static void collect(KList source, IrisData data, ModuleLog log, Set loadKeys, + private static void collect(List source, IrisData data, ModuleLog log, Set loadKeys, Set normalizedLoadKeys, Set vanillaAliases, Set suppressedVanillaSources, - List placements, boolean allowNativeSuppression) { - if (source == null) { - return; - } - for (IrisStructurePlacement placement : source) { + List placements, boolean allowNativeSuppression) { + for (StructurePlacement placement : source) { if (placement == null) { throw new IllegalStateException("Iris structure placement list contains a null placement"); } - if (placement.getDistribution() == null) { - throw new IllegalStateException("Iris structure placement is missing its distribution"); - } NativeStartPlanner.validateBackend(placement); - boolean replacesNative = NativeStructureSuppression.REPLACE_SOURCE == placement.getNativeSuppression(); + 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 (IrisNativeStructure nativeStructure : placement.getNativeStructures()) { + for (NativeStructureSource nativeStructure : placement.nativeStructures()) { if (nativeStructure == null - || nativeStructure.getStructure() == null - || !NAMESPACED_RESOURCE_KEY.matcher(nativeStructure.getStructure()).matches()) { + || nativeStructure.structure() == null + || !NAMESPACED_RESOURCE_KEY.matcher(nativeStructure.structure()).matches()) { throw new IllegalStateException("Native structure placement contains an invalid structure key"); } - String sourceKey = nativeStructure.getStructure(); + String sourceKey = nativeStructure.structure(); loadKeys.add(sourceKey); normalizedLoadKeys.add(normalize(sourceKey)); vanillaAliases.add(normalize(sourceKey)); @@ -1215,7 +1203,7 @@ public final class IrisStructureLocator { placements.add(placement); continue; } - for (String structureKey : placement.getStructures()) { + for (String structureKey : placement.structures()) { if (structureKey == null || structureKey.isBlank()) { throw new IllegalStateException(replacesNative ? "REPLACE_SOURCE contains a blank Iris structure reference" @@ -1254,7 +1242,7 @@ public final class IrisStructureLocator { } } - public record ResolvedPlacement(IrisStructurePlacement placement, String structureKey, IrisStructure structure, + public record ResolvedPlacement(StructurePlacement placement, String structureKey, IrisStructure structure, KList pieces, RNG rng, int originX, int baseY, int originZ, boolean exactY) { } @@ -1286,7 +1274,7 @@ public final class IrisStructureLocator { } private record PlacementCatalog(List randomSpread, - List concentricRings, boolean hasDensity) { + List concentricRings, boolean hasDensity) { } private record LocatableIndex(Set keys, Set normalizedKeys, @@ -1317,12 +1305,12 @@ public final class IrisStructureLocator { private final Set vanillaAliases; private final Set suppressedVanillaSources; private final Set nativeKeys; - private final List placements; + private final List placements; private PlacementIndex(Set loadKeys, Set normalizedLoadKeys, Set vanillaAliases, Set suppressedVanillaSources, Set nativeKeys, - List placements) { + List placements) { this.loadKeys = loadKeys; this.normalizedLoadKeys = normalizedLoadKeys; this.vanillaAliases = vanillaAliases; diff --git a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java index 599b4bd88..163d6618d 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +++ b/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java @@ -1,8 +1,8 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +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; @@ -23,26 +23,26 @@ public final class StructureCaveAnchorResolver { private StructureCaveAnchorResolver() { } - public static Anchor resolve(Engine engine, IrisStructurePlacement placement, int chunkX, int chunkZ, RNG rng) { + 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"); - IrisStructureAnchorMode mode = placement.resolvedAnchor(); + 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.getMinHeight(), placement.getMaxHeight())); - int maximumY = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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.getCaveAnchorAttempts())); - int scanStep = Math.min(MAX_SCAN_STEP, Math.max(1, placement.getCaveAnchorScanStep())); - int clearance = Math.min(MAX_CLEARANCE, Math.max(1, placement.getCaveMinimumClearance())); + 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); @@ -73,8 +73,8 @@ public final class StructureCaveAnchorResolver { static List anchorsInColumn( Engine engine, - IrisStructurePlacement placement, - IrisStructureAnchorMode mode, + StructurePlacement placement, + StructureAnchorMode mode, int blockX, int blockZ, int minimumY, @@ -82,7 +82,7 @@ public final class StructureCaveAnchorResolver { int scanStep, int clearance ) { - if (mode == IrisStructureAnchorMode.CAVE_CENTER) { + if (mode == StructureAnchorMode.CAVE_CENTER) { return centerAnchorsInColumn( engine, placement, blockX, blockZ, minimumY, maximumY, scanStep, clearance); @@ -107,7 +107,7 @@ public final class StructureCaveAnchorResolver { private static List centerAnchorsInColumn( Engine engine, - IrisStructurePlacement placement, + StructurePlacement placement, int blockX, int blockZ, int minimumY, @@ -153,7 +153,7 @@ public final class StructureCaveAnchorResolver { private static void addCenterAnchor( List anchors, Engine engine, - IrisStructurePlacement placement, + StructurePlacement placement, int blockX, int blockZ, int worldY, @@ -172,14 +172,14 @@ public final class StructureCaveAnchorResolver { static boolean matchesGeometry( Engine engine, - IrisStructureAnchorMode mode, + StructureAnchorMode mode, int blockX, int mantleY, int blockZ, int clearance ) { IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); - if (mode == IrisStructureAnchorMode.CAVE_CENTER) { + if (mode == StructureAnchorMode.CAVE_CENTER) { return matchesCenterGeometry( carved, mantleY, Math.max(1, clearance), 0, engine.getHeight() - 1); } @@ -188,7 +188,7 @@ public final class StructureCaveAnchorResolver { static boolean matchesGeometry( IntPredicate carved, - IrisStructureAnchorMode mode, + StructureAnchorMode mode, int mantleY, int clearance ) { @@ -281,14 +281,14 @@ public final class StructureCaveAnchorResolver { private static boolean matchesAnchorFluid( Engine engine, - IrisStructurePlacement placement, + StructurePlacement placement, int blockX, int mantleY, int blockZ ) { MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); return acceptsAnchorFluid( - placement.isUnderwater(), + placement.underwater(), cavern, mantleY, engine.getDimension().getCaveLavaHeight()); @@ -322,12 +322,12 @@ public final class StructureCaveAnchorResolver { private static boolean matchesBiome( Engine engine, - IrisStructurePlacement placement, + StructurePlacement placement, int blockX, int mantleY, int blockZ ) { - if (placement.getCaveBiomes() == null || placement.getCaveBiomes().isEmpty()) { + if (placement.caveBiomes().isEmpty()) { return true; } IrisBiome biome = engine.getCaveOrMantleBiome(blockX, mantleY, blockZ); @@ -335,7 +335,7 @@ public final class StructureCaveAnchorResolver { return false; } String actual = biome.getLoadKey().toLowerCase(Locale.ROOT); - for (String allowed : placement.getCaveBiomes()) { + for (String allowed : placement.caveBiomes()) { if (matchesBiomeKey(actual, allowed)) { return true; } diff --git a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java index e02ad2288..bc477f26b 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java +++ b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementGrid.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; -import art.arcane.iris.engine.object.structure.IrisStructureAnchorMode; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.builtin.structure.NativeStructureSource; +import art.arcane.iris.builtin.structure.StructureAnchorMode; +import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.volmlib.util.math.RNG; import java.util.Locale; @@ -33,16 +33,16 @@ public final class StructurePlacementGrid { private StructurePlacementGrid() { } - public static boolean startsInChunk(IrisStructurePlacement placement, int cx, int cz, long seed) { - return switch (placement.getDistribution()) { - case RANDOM_SPREAD -> randomSpreadStart(cx, cz, placement.getSpacing(), placement.getSeparation(), + public static boolean startsInChunk(StructurePlacement placement, int cx, int cz, long seed) { + return switch (placement.distribution()) { + case RANDOM_SPREAD -> randomSpreadStart(cx, cz, placement.spacing(), placement.separation(), placementSalt(placement), seed); case DENSITY -> densityStart(placement, cx, cz, seed); case CONCENTRIC_RINGS -> concentricRingsStart(cx, cz, placement, seed); }; } - public static RNG placementRng(IrisStructurePlacement placement, int cx, int cz, long seed) { + public static RNG placementRng(StructurePlacement placement, int cx, int cz, long seed) { return new RNG(placementSeed(placement, cx, cz, seed)); } @@ -69,13 +69,13 @@ public final class StructurePlacementGrid { return new int[]{startCx, startCz}; } - public static int[] concentricRingChunk(IrisStructurePlacement placement, int placementIndex, long seed) { - int count = Math.max(1, placement.getRingCount()); + public static int[] concentricRingChunk(StructurePlacement placement, int placementIndex, long seed) { + int count = Math.max(1, placement.ringCount()); if (placementIndex < 0 || placementIndex >= count) { return null; } - int distance = Math.max(1, placement.getRingDistance()); - int spread = Math.max(1, placement.getRingSpread()); + int distance = Math.max(1, placement.ringDistance()); + int spread = Math.max(1, placement.ringSpread()); int ring = Math.floorDiv(placementIndex, spread) + 1; int firstIndex = (ring - 1) * spread; int slots = Math.min(spread, count - firstIndex); @@ -94,13 +94,13 @@ public final class StructurePlacementGrid { }; } - private static boolean concentricRingsStart(int cx, int cz, IrisStructurePlacement placement, long seed) { + private static boolean concentricRingsStart(int cx, int cz, StructurePlacement placement, long seed) { if (cx == 0 && cz == 0) { return false; } - int distance = Math.max(1, placement.getRingDistance()); - int count = Math.max(1, placement.getRingCount()); - int spread = Math.max(1, placement.getRingSpread()); + int distance = Math.max(1, placement.ringDistance()); + int count = Math.max(1, placement.ringCount()); + int spread = Math.max(1, placement.ringSpread()); double dist = Math.sqrt((double) cx * cx + (double) cz * cz); int estimatedRing = (int) Math.round(dist / distance); int ringCount = Math.ceilDiv(count, spread); @@ -127,8 +127,8 @@ public final class StructurePlacementGrid { return false; } - private static boolean densityStart(IrisStructurePlacement placement, int cx, int cz, long seed) { - double density = placement.getDensity(); + private static boolean densityStart(StructurePlacement placement, int cx, int cz, long seed) { + double density = placement.density(); if (density <= 0.0) { return false; } @@ -139,33 +139,33 @@ public final class StructurePlacementGrid { return rng.chance(density); } - public static long placementIdentity(IrisStructurePlacement placement) { + public static long placementIdentity(StructurePlacement placement) { long signature = 1469598103934665603L; - signature = appendLong(signature, placement.getDistribution().ordinal()); - signature = appendLong(signature, placement.getSalt()); - String placementId = placement.getPlacementId(); + signature = appendLong(signature, placement.distribution().ordinal()); + signature = appendLong(signature, placement.salt()); + String placementId = placement.placementId(); if (placementId != null && !placementId.isBlank()) { signature = appendLong(signature, 1L); signature = appendSignature(signature, placementId.trim()); } else { signature = appendLong(signature, 0L); - signature = appendLong(signature, placement.getSpacing()); - signature = appendLong(signature, placement.getSeparation()); - signature = appendLong(signature, Double.doubleToLongBits(placement.getDensity())); - signature = appendLong(signature, placement.getRingCount()); - signature = appendLong(signature, placement.getRingDistance()); - signature = appendLong(signature, placement.getRingSpread()); - signature = appendLong(signature, placement.getMinHeight()); - signature = appendLong(signature, placement.getMaxHeight()); - signature = appendLong(signature, placement.isUnderground() ? 1L : 0L); - signature = appendLong(signature, placement.isUnderwater() ? 1L : 0L); + signature = appendLong(signature, placement.spacing()); + signature = appendLong(signature, placement.separation()); + signature = appendLong(signature, Double.doubleToLongBits(placement.density())); + signature = appendLong(signature, placement.ringCount()); + signature = appendLong(signature, placement.ringDistance()); + signature = appendLong(signature, placement.ringSpread()); + signature = appendLong(signature, placement.minHeight()); + signature = appendLong(signature, placement.maxHeight()); + signature = appendLong(signature, placement.underground() ? 1L : 0L); + signature = appendLong(signature, placement.underwater() ? 1L : 0L); signature = appendSources(signature, placement); signature = appendAnchor(signature, placement); } return signature; } - private static long placementSeed(IrisStructurePlacement placement, int cx, int cz, long seed) { + private static long placementSeed(StructurePlacement placement, int cx, int cz, long seed) { long signature = placementIdentity(placement); int identitySalt = (int) (signature ^ (signature >>> 32)); return mix(seed ^ signature, cx, cz, placementSalt(placement) ^ identitySalt); @@ -189,37 +189,34 @@ public final class StructurePlacementGrid { return result; } - private static long appendSources(long signature, IrisStructurePlacement placement) { + private static long appendSources(long signature, StructurePlacement placement) { long result = signature; if (placement.hasIrisStructures()) { result = appendLong(result, 1L); - result = appendLong(result, placement.getStructures().size()); - for (String key : placement.getStructures()) { + result = appendLong(result, placement.structures().size()); + for (String key : placement.structures()) { result = appendSignature(result, key == null ? "" : key); } return result; } result = appendLong(result, 2L); - if (placement.getNativeStructures() == null) { - return appendLong(result, 0L); - } - result = appendLong(result, placement.getNativeStructures().size()); - for (IrisNativeStructure source : placement.getNativeStructures()) { + result = appendLong(result, placement.nativeStructures().size()); + for (NativeStructureSource source : placement.nativeStructures()) { if (source == null) { result = appendSignature(result, ""); result = appendLong(result, 0L); continue; } result = appendSignature(result, - source.getStructure() == null ? "" : source.getStructure()); - result = appendLong(result, source.getWeight()); + source.structure() == null ? "" : source.structure()); + result = appendLong(result, source.weight()); } return result; } - private static long appendAnchor(long signature, IrisStructurePlacement placement) { - IrisStructureAnchorMode anchor = placement.getAnchor(); - if (anchor == null || anchor == IrisStructureAnchorMode.LEGACY) { + private static long appendAnchor(long signature, StructurePlacement placement) { + StructureAnchorMode anchor = placement.anchor(); + if (anchor == StructureAnchorMode.LEGACY) { return signature; } long result = appendLong(signature, 0x4A49475341574C41L); @@ -227,14 +224,11 @@ public final class StructurePlacementGrid { if (!anchor.isCave()) { return result; } - result = appendLong(result, placement.getCaveAnchorAttempts()); - result = appendLong(result, placement.getCaveAnchorScanStep()); - result = appendLong(result, placement.getCaveMinimumClearance()); - if (placement.getCaveBiomes() == null) { - return appendLong(result, 0L); - } + result = appendLong(result, placement.caveAnchorAttempts()); + result = appendLong(result, placement.caveAnchorScanStep()); + result = appendLong(result, placement.caveMinimumClearance()); Set biomes = new TreeSet<>(); - for (String biome : placement.getCaveBiomes()) { + for (String biome : placement.caveBiomes()) { if (biome != null && !biome.isBlank()) { biomes.add(biome.trim().toLowerCase(Locale.ROOT)); } @@ -246,28 +240,28 @@ public final class StructurePlacementGrid { return result; } - static int placementSalt(IrisStructurePlacement placement) { - String placementId = placement.getPlacementId(); + static int placementSalt(StructurePlacement placement) { + String placementId = placement.placementId(); long identity; if (placementId != null && !placementId.isBlank()) { identity = appendSignature(1469598103934665603L, placementId.trim()); } else { identity = 1469598103934665603L; - identity = appendLong(identity, placement.getDistribution().ordinal()); - identity = appendLong(identity, placement.getSpacing()); - identity = appendLong(identity, placement.getSeparation()); - identity = appendLong(identity, Double.doubleToLongBits(placement.getDensity())); - identity = appendLong(identity, placement.getRingCount()); - identity = appendLong(identity, placement.getRingDistance()); - identity = appendLong(identity, placement.getRingSpread()); - identity = appendLong(identity, placement.getMinHeight()); - identity = appendLong(identity, placement.getMaxHeight()); - identity = appendLong(identity, placement.isUnderground() ? 1L : 0L); - identity = appendLong(identity, placement.isUnderwater() ? 1L : 0L); + identity = appendLong(identity, placement.distribution().ordinal()); + identity = appendLong(identity, placement.spacing()); + identity = appendLong(identity, placement.separation()); + identity = appendLong(identity, Double.doubleToLongBits(placement.density())); + identity = appendLong(identity, placement.ringCount()); + identity = appendLong(identity, placement.ringDistance()); + identity = appendLong(identity, placement.ringSpread()); + identity = appendLong(identity, placement.minHeight()); + identity = appendLong(identity, placement.maxHeight()); + identity = appendLong(identity, placement.underground() ? 1L : 0L); + identity = appendLong(identity, placement.underwater() ? 1L : 0L); identity = appendSources(identity, placement); identity = appendAnchor(identity, placement); } - return placement.getSalt() ^ (int) (identity ^ (identity >>> 32)); + return placement.salt() ^ (int) (identity ^ (identity >>> 32)); } private static double unitDouble(long value) { diff --git a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java index 9e35719af..bc99627de 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java +++ b/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java @@ -1,75 +1,68 @@ 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.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.volmlib.util.collection.KList; -import java.lang.ref.WeakReference; -import java.util.ArrayList; 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 static final List SCOPE_INDEXES = new ArrayList<>(); - private StructurePlacementScope() { } - public static KList placementsAt(Engine engine, int chunkX, int chunkZ) { + /** 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<>()); + 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, biome == null ? null : biome.getStructures()); + addUnique(placements, seen, placementsOf(biome)); } if (index.caveBiome()) { IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ); - addCaveUnique(placements, seen, caveBiome == null ? null : caveBiome.getStructures()); + addCaveUnique(placements, seen, placementsOf(caveBiome)); } if (index.region()) { IrisRegion region = complex.getRegionStream().get(blockX, blockZ); - addUnique(placements, seen, region == null ? null : region.getStructures()); + addUnique(placements, seen, placementsOf(region)); } } if (index.dimension()) { - addUnique(placements, seen, activeEngine.getDimension().getStructures()); + addUnique(placements, seen, placementsOf(activeEngine.getDimension())); } return placements; } private static ScopeIndex scopeIndex(Engine engine) { - int revision = engine.getCacheID(); - synchronized (SCOPE_INDEXES) { - for (int i = SCOPE_INDEXES.size() - 1; i >= 0; i--) { - CachedScopeIndex cached = SCOPE_INDEXES.get(i); - Engine indexedEngine = cached.engine().get(); - if (indexedEngine == null) { - SCOPE_INDEXES.remove(i); - continue; - } - if (indexedEngine == engine) { - if (cached.revision() == revision) { - return cached.index(); - } - SCOPE_INDEXES.remove(i); - break; - } - } - ScopeIndex index = buildScopeIndex(engine); - SCOPE_INDEXES.add(new CachedScopeIndex(new WeakReference<>(engine), revision, index)); - return index; - } + return engine.getGeneration().state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex); } private static ScopeIndex buildScopeIndex(Engine engine) { @@ -81,68 +74,42 @@ public final class StructurePlacementScope { caveBiome = true; } else { for (IrisBiome candidate : allBiomes) { - KList structures = candidate.getStructures(); - if (structures == null || structures.isEmpty()) { + List structures = placementsOf(candidate); + if (structures.isEmpty()) { continue; } biome = true; - for (IrisStructurePlacement placement : structures) { - if (placement != null && placement.resolvedAnchor().isCave()) { - caveBiome = true; - break; - } - } + caveBiome |= structures.stream().anyMatch(placement -> placement.resolvedAnchor().isCave()); } } boolean region = false; if (engine.getDimension() != null) { KList allRegions = engine.getDimension().getAllRegions(engine); - if (allRegions == null) { - region = true; - } else { - for (IrisRegion candidate : allRegions) { - if (candidate.getStructures() != null && !candidate.getStructures().isEmpty()) { - region = true; - break; - } - } - } + region = allRegions == null + || allRegions.stream().anyMatch(candidate -> !placementsOf(candidate).isEmpty()); } - boolean dimension = engine.getDimension() != null - && engine.getDimension().getStructures() != null - && !engine.getDimension().getStructures().isEmpty(); + boolean dimension = !placementsOf(engine.getDimension()).isEmpty(); return new ScopeIndex(biome, caveBiome, region, dimension); } - private static void addUnique(KList destination, - Set seen, - KList source) { - if (source == null) { - return; - } - for (IrisStructurePlacement placement : source) { + 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, - KList source) { - if (source == null) { - return; - } - for (IrisStructurePlacement placement : source) { + 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 CachedScopeIndex(WeakReference engine, int revision, ScopeIndex index) { - } - private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) { } } 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 index bc21cf3d7..c5f273b39 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java @@ -21,10 +21,9 @@ 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.engine.object.structure.IrisStructureAnchorMode; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.vanilla.IrisNativeStructure; -import art.arcane.volmlib.util.collection.KList; +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; @@ -46,17 +45,17 @@ public final class NativeStartPlanner { } /** One start a {@code nativeStructures} placement makes: the placement, its chosen source and world base Y. */ - public record Plan(IrisStructurePlacement placement, IrisNativeStructure source, int chunkX, int chunkZ, int baseY) { + 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 (IrisStructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { + for (StructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { Plan plan = planAt(engine, placement, chunkX, chunkZ); if (plan == null) { continue; } - String structureKey = normalize(plan.source().getStructure()); + String structureKey = normalize(plan.source().structure()); Plan current = plansByStructure.get(structureKey); if (current == null || comparePlacementPriority(plan.placement(), current.placement()) < 0) { plansByStructure.put(structureKey, plan); @@ -65,7 +64,7 @@ public final class NativeStartPlanner { return List.copyOf(plansByStructure.values()); } - public static Plan planAt(Engine engine, IrisStructurePlacement placement, int chunkX, int chunkZ) { + public static Plan planAt(Engine engine, StructurePlacement placement, int chunkX, int chunkZ) { validateBackend(placement); if (!placement.hasNativeStructures()) { return null; @@ -80,7 +79,7 @@ public final class NativeStartPlanner { } RNG placementRng = StructurePlacementGrid.placementRng( placement, chunkX, chunkZ, mantleSeed).nextParallelRNG(NATIVE_SELECTION_DOMAIN); - IrisNativeStructure source = selectSource(placement.getNativeStructures(), placementRng); + NativeStructureSource source = selectSource(placement.nativeStructures(), placementRng); Integer baseY = resolveBaseY(activeEngine, placement, chunkX, chunkZ, placementRng); if (baseY == null) { return null; @@ -88,7 +87,7 @@ public final class NativeStartPlanner { return new Plan(placement, source, chunkX, chunkZ, baseY); } - public static void validateBackend(IrisStructurePlacement placement) { + public static void validateBackend(StructurePlacement placement) { if (placement == null) { throw new IllegalStateException("Structure placement must not be null"); } @@ -98,8 +97,7 @@ public final class NativeStartPlanner { throw new IllegalStateException("Structure placement must declare exactly one backend: " + "structures or nativeStructures"); } - if (nativeStructure && placement.getAnchor() != null - && placement.getAnchor() != IrisStructureAnchorMode.LEGACY) { + if (nativeStructure && placement.anchor() != StructureAnchorMode.LEGACY) { throw new IllegalStateException("Native structure placements do not support the Iris anchor field"); } } @@ -108,26 +106,26 @@ public final class NativeStartPlanner { return engine.getHeight(blockX, blockZ, true) < engine.getDimension().getFluidHeight(); } - static IrisNativeStructure selectSource(KList sources, RNG rng) { + 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 (IrisNativeStructure source : sources) { - if (source == null || source.getStructure() == null || source.getStructure().isBlank()) { + 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.getWeight() < 1) { - throw new IllegalStateException("Native structure source '" + source.getStructure() - + "' has invalid weight " + source.getWeight()); + if (source.weight() < 1) { + throw new IllegalStateException("Native structure source '" + source.structure() + + "' has invalid weight " + source.weight()); } - totalWeight = Math.addExact(totalWeight, source.getWeight()); + 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 (IrisNativeStructure source : sources) { - roll -= source.getWeight(); + for (NativeStructureSource source : sources) { + roll -= source.weight(); if (roll < 0) { return source; } @@ -135,7 +133,7 @@ public final class NativeStartPlanner { throw new IllegalStateException("Native structure source selection produced no result"); } - private static Integer resolveBaseY(Engine engine, IrisStructurePlacement placement, + 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; @@ -144,25 +142,25 @@ public final class NativeStartPlanner { } int blockX = (chunkX << 4) + 8; int blockZ = (chunkZ << 4) + 8; - if (!placement.isUnderwater() && isSubmerged(engine, blockX, blockZ)) { + if (!placement.underwater() && isSubmerged(engine, blockX, blockZ)) { return null; } - if (!placement.isUnderground()) { + if (!placement.underground()) { int surfaceY = engine.getHeight(blockX, blockZ, true) + engine.getMinHeight(); - if (surfaceY < placement.getMinHeight() || surfaceY > placement.getMaxHeight()) { + if (surfaceY < placement.minHeight() || surfaceY > placement.maxHeight()) { return null; } return surfaceY; } - int bandMin = Math.max(worldMin, Math.min(placement.getMinHeight(), placement.getMaxHeight())); - int bandMax = Math.min(worldMax, Math.max(placement.getMinHeight(), placement.getMaxHeight())); + 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(IrisStructurePlacement left, IrisStructurePlacement right) { + private static int comparePlacementPriority(StructurePlacement left, StructurePlacement right) { long leftIdentity = StructurePlacementGrid.placementIdentity(left); long rightIdentity = StructurePlacementGrid.placementIdentity(right); return Long.compareUnsigned(leftIdentity, rightIdentity); 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 index c34c209ad..b19815e41 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java @@ -25,8 +25,8 @@ 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.engine.object.structure.IrisStructurePlacement; -import art.arcane.iris.engine.object.structure.vanilla.NativeStructureSuppression; +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; @@ -148,21 +148,18 @@ public final class StructureVanillaStructures implements VanillaStructures { /** {@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) { - IrisStructurePlacement placement = plan.placement(); - NativeStructureFit fit = new NativeStructureFit(0, null, false, placement.getStilt(), placement.resolvedTerrain()); - VanillaStructureStart start = VanillaStructureStart.at(ResourceId.parse(plan.source().getStructure()), + 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.isUnderground()) { + if (placement.underground()) { start = start.underground(); } - if (placement.getNativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE) { + if (placement.nativeSuppression() == NativeStructureSuppression.REPLACE_SOURCE) { start = start.replacingPlatformStart(); } - if (plan.source().getJigsaw() != null) { - start = start.withJigsaw(plan.source().getJigsaw()); - } - return start; + return plan.source().jigsaw().map(start::withJigsaw).orElse(start); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 4d3c5bcdb..f614d0ef0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -19,9 +19,8 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureSettings; -import art.arcane.iris.builtin.structure.StructureStilts; -import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; @@ -38,7 +37,6 @@ import com.volmit.service.StructureLocator; import com.volmit.service.VanillaStructures; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; -import com.volmit.vanilla.JigsawOverrides; /** * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear @@ -54,8 +52,8 @@ import com.volmit.vanilla.JigsawOverrides; * It decides over the platform's own structures through its {@link VanillaStructures} provider * ({@link StructureVanillaStructures}): the dimension's {@code importedStructures} settings disable, move, fit and set * them up, and the pack's structure placements replace them, place them alongside, start them where their - * {@code nativeStructures} grids say and fit them into the terrain. It describes the fit settings Iris's structure - * placements hold. + * {@code nativeStructures} grids say and fit them into the terrain. The pack's structure placements are its + * {@code "structures"} settings ({@link StructurePlacementSettings}) of the dimension, its regions and biomes. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; @@ -77,13 +75,11 @@ public final class StructureModule implements IrisModule { public void register(FeatureRegistry registry) { log = registry.log(); registry.registerSettings(StructureSettings.class); + registry.registerSettings(StructurePlacementSettings.class); StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new StructureValidator()); registry.registerService(StructureLocator.class, new StructureLocating()); registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); - registry.registerHeldType(StructureTerrain.class); - registry.registerHeldType(StructureStilts.class); - registry.registerHeldType(JigsawOverrides.class); } private static void place(MantleStageContext context) { 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 index f461f23f8..c0acf37e2 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -37,7 +37,7 @@ 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.engine.object.structure.IrisStructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.StructureStilts; import com.volmit.ModuleLog; import com.volmit.block.PaletteSampler; @@ -61,6 +61,7 @@ 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; /** @@ -82,7 +83,7 @@ public class StructurePlacing { /** 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 (IrisStructurePlacement placement : StructurePlacementScope.placementsAt( + for (StructurePlacement placement : StructurePlacementScope.placementsAt( engine, x, z)) { if (!placement.hasIrisStructures()) { continue; @@ -92,7 +93,7 @@ public class StructurePlacing { } @ChunkCoordinates - private void placeFromPlacement(MantleWriter writer, IrisStructurePlacement placement, int cx, int cz) { + private void placeFromPlacement(MantleWriter writer, StructurePlacement placement, int cx, int cz) { IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement( engine, placement, cx, cz); if (resolved == null) { @@ -101,8 +102,8 @@ public class StructurePlacing { boolean trace = IrisSettings.get().getGeneral().isDebug(); if (trace) { - log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.getStructures() - + " anchor=" + placement.resolvedAnchor() + " band=" + placement.getMinHeight() + ".." + placement.getMaxHeight()); + log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.structures() + + " anchor=" + placement.resolvedAnchor() + " band=" + placement.minHeight() + ".." + placement.maxHeight()); } String key = resolved.structureKey(); @@ -135,7 +136,7 @@ public class StructurePlacing { ObjectPlaceMode mode = structure.getPlaceMode(); int failedPieces = 0; - StructureStilts stilt = placement.getStilt(); + StructureStilts stilt = placement.stilt().orElse(null); Long2IntOpenHashMap foundationColumns = stilt == null ? null : new Long2IntOpenHashMap(); boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding(); @@ -590,19 +591,19 @@ public class StructurePlacing { int maxBlocks = 0; for (IrisRegion region : dimension.getAllRegions(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(region.getStructures())); + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(region))); } for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(biome.getStructures())); + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(biome))); } - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(dimension.getStructures())); + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(dimension))); return maxBlocks; } - private int maxBlocksFrom(KList placements) { + private int maxBlocksFrom(List placements) { int max = 0; - for (IrisStructurePlacement placement : placements) { + for (StructurePlacement placement : placements) { if (!placement.hasIrisStructures()) { continue; } @@ -610,7 +611,7 @@ public class StructurePlacing { int carvePadding = terrain.resolvedMode() == StructureTerrainMode.FORCE_CARVE || terrain.resolvedMode() == StructureTerrainMode.BORE ? Math.max(0, terrain.horizontalPadding()) : 0; - for (String key : placement.getStructures()) { + 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); diff --git a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java deleted file mode 100644 index b7d17991a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/IrisStructureAnchorMode.java +++ /dev/null @@ -1,34 +0,0 @@ -package art.arcane.iris.engine.object.structure; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Selects the vertical environment used to anchor an Iris structure placement.") -public enum IrisStructureAnchorMode { - @Desc("Preserve the historical underground boolean behavior.") - LEGACY, - - @Desc("Anchor to the terrain surface and use minHeight/maxHeight as a surface gate.") - SURFACE, - - @Desc("Choose a deterministic Y inside the minHeight/maxHeight band.") - HEIGHT_BAND, - - @Desc("Anchor in carved space with solid support below.") - CAVE_FLOOR, - - @Desc("Anchor in carved space with solid support above.") - CAVE_CEILING, - - @Desc("Anchor in carved space without nearby floor or ceiling support.") - CAVE_CENTER, - - @Desc("Anchor at any carved-space position.") - CAVE_ANY; - - public boolean isCave() { - return switch (this) { - case CAVE_FLOOR, CAVE_CEILING, CAVE_CENTER, CAVE_ANY -> true; - default -> false; - }; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java deleted file mode 100644 index 357b0002d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/IrisNativeStructure.java +++ /dev/null @@ -1,30 +0,0 @@ -package art.arcane.iris.engine.object.structure.vanilla; - -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; -import art.arcane.iris.engine.object.annotations.Required; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; -import com.volmit.vanilla.JigsawOverrides; - -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Data -@Desc("A live vanilla, datapack, or modded structure generated by Minecraft at an Iris-controlled placement.") -public class IrisNativeStructure { - @Required - @RegistryListVanillaStructure - @Desc("Registered structure key. The source retains its native generator, pieces, templates, processors, entities, markers, and data.") - private String structure = ""; - - @MinNumber(1) - @Desc("Relative selection weight when a placement offers multiple native structure sources.") - private int weight = 1; - - @Desc("Optional jigsaw-only assembly overrides. Null preserves the complete registered structure definition.") - private JigsawOverrides jigsaw = null; -} diff --git a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java b/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java deleted file mode 100644 index 35051cc68..000000000 --- a/src/main/java/art/arcane/iris/engine/object/structure/vanilla/NativeStructureSuppression.java +++ /dev/null @@ -1,12 +0,0 @@ -package art.arcane.iris.engine.object.structure.vanilla; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Controls whether an Iris structure placement suppresses its imported native source.") -public enum NativeStructureSuppression { - @Desc("Leaves native generation enabled alongside this Iris structure placement.") - NONE, - - @Desc("Suppresses the structure's vanillaSource when used by a validated dimension-level replacement placement.") - REPLACE_SOURCE -} 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 index 659bec501..3a1a3d934 100644 --- 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 @@ -22,7 +22,6 @@ import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; 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; @@ -146,9 +145,6 @@ public class IrisBiome extends IrisRegistrant implements IRare { private KList objects = new KList<>(); @Desc("Procedural objects (such as trees) iris generates from scratch and places in this biome, instead of loading them from iob files") private IrisProceduralObjects proceduralObjects = new IrisProceduralObjects(); - @ArrayType(min = 1, type = IrisStructurePlacement.class) - @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this biome") - private KList structures = 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()); 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 index 05269765d..cb4d0c812 100644 --- 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 @@ -26,7 +26,6 @@ import art.arcane.iris.engine.object.noise.IrisShapedGeneratorStyle; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.procedural.tree.IrisTreeSettings; import art.arcane.iris.engine.object.runtime.StudioMode; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; import art.arcane.iris.engine.object.value.IrisRange; import art.arcane.iris.engine.object.world.IrisEnvironment; import art.arcane.iris.engine.object.world.IrisWorldBoundary; @@ -236,9 +235,6 @@ public class IrisDimension extends IrisRegistrant { @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) @Desc("Overlay additional noise on top of the interoplated terrain.") private KList overlayNoise = new KList<>(); - @Desc("Dimension-wide Iris structure placements, independent of biome/region placements") - @ArrayType(type = IrisStructurePlacement.class, min = 1) - private KList structures = 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<>(); 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 index e57c3b9f9..4b70f84e7 100644 --- 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 @@ -20,7 +20,6 @@ package art.arcane.iris.engine.object.world.region; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.procedural.IrisProceduralObjects; -import art.arcane.iris.engine.object.structure.IrisStructurePlacement; 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; @@ -81,9 +80,6 @@ public class IrisRegion extends IrisRegistrant implements IRare { private KList objects = new KList<>(); @Desc("Procedural objects (trees, ruins, formations, coral, fungi, crystals) iris generates from scratch and places across this region") private IrisProceduralObjects proceduralObjects = new IrisProceduralObjects(); - @ArrayType(min = 1, type = IrisStructurePlacement.class) - @Desc("Structures define jigsaw or vanilla/datapack structures iris will place in this region") - private KList structures = new KList<>(); @MinNumber(0) @Desc("The min shore height") private double shoreHeightMin = 1.2; From 2d63a9aaa438f0e8e3bc5be7fe3c74e872b6fb49 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:36:42 +0200 Subject: [PATCH 080/139] iris:objects is written against IrisApi and the objects facade: ObjectModule, ObjectPlacing, ObjectWarmUp, ObjectLocating and TreeGrowing move into iris-builtins.jar; ObjectHost and ObjectChunk are what Iris answers --- builtin-modules.txt | 11 + .../iris/builtin/objects/CarvedSpace.java | 33 + .../iris/builtin/objects/CavePlacement.java | 40 + .../arcane/iris/builtin/objects/Cavern.java | 29 + .../iris/builtin/objects/ObjectChunk.java | 56 + .../iris/builtin/objects/ObjectHost.java | 125 ++ .../iris/builtin/objects/ObjectPlacement.java | 10 +- .../iris/builtin/objects/ObjectSink.java | 34 + .../iris/builtin/objects/ObjectSize.java | 23 + .../iris/builtin/objects/PlaceableObject.java | 34 + .../builtin/objects/PlacementChanges.java | 69 + .../iris/builtin/objects/PlacementSource.java | 42 + .../iris/builtin/objects/PlacementTags.java | 29 + .../builtin/objects/ProceduralPlacement.java | 88 + .../iris/builtin/objects/tree/Tree.java | 8 + .../engine/mantle/components/CaveAnchors.java | 228 +++ .../CaveObjectPlacementTransaction.java | 12 +- .../engine/mantle/components/CaveRejects.java | 69 + .../mantle/components/CaveSettings.java | 88 + .../mantle/components/ChunkObjectPlacing.java | 680 +++++++ .../components/EffectivePlacements.java | 90 + .../components/FloatingObjectPlacing.java | 52 +- .../components/GoldenDebugObjectPlacer.java | 6 +- .../mantle/components/ObjectLocating.java | 38 +- .../mantle/components/ObjectModule.java | 17 +- .../mantle/components/ObjectPlacing.java | 1654 +---------------- .../mantle/components/ObjectWarmUp.java | 83 +- .../mantle/components/PlacementReach.java | 170 ++ .../mantle/components/StructureModule.java | 2 +- .../engine/mantle/components/TreeGrowing.java | 215 +-- .../object/placement/ObjectPlacements.java | 7 +- .../iris/engine/object/prefab/IrisObject.java | 23 +- .../ResolvedProceduralPlacement.java | 5 + .../object/procedural/tree/ResolvedTree.java | 10 +- 34 files changed, 2238 insertions(+), 1842 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/Cavern.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 824782905..41cb85591 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -18,3 +18,14 @@ module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule module art.arcane.iris.engine.modifier.MatterModule +module art.arcane.iris.engine.mantle.components.ObjectModule +include art/arcane/iris/engine/mantle/components/ObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/ChunkObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/CaveAnchors*.class +include art/arcane/iris/engine/mantle/components/CaveSettings*.class +include art/arcane/iris/engine/mantle/components/CaveRejects*.class +include art/arcane/iris/engine/mantle/components/EffectivePlacements*.class +include art/arcane/iris/engine/mantle/components/PlacementReach*.class +include art/arcane/iris/engine/mantle/components/ObjectWarmUp*.class +include art/arcane/iris/engine/mantle/components/ObjectLocating*.class +include art/arcane/iris/engine/mantle/components/TreeGrowing*.class diff --git a/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java b/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java new file mode 100644 index 000000000..6ee201b23 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java @@ -0,0 +1,33 @@ +/* + * 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.builtin.objects; + +import java.util.Optional; + +/** The voids the cave carver planned in the mantle around the chunk being placed, which cave objects anchor in. */ +public interface CarvedSpace { + /** Whether the position is carved. */ + boolean isCarved(int x, int y, int z); + + /** Whether each height from 0 up to {@code height} is carved at the column, 1 for carved and 0 for not. */ + byte[] column(int x, int z, int height); + + /** The void at the position; empty where nothing was carved. */ + Optional cavernAt(int x, int y, int z); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java b/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java new file mode 100644 index 000000000..221ba5b30 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java @@ -0,0 +1,40 @@ +/* + * 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.builtin.objects; + +/** + * The outcome of placing an object in a cave. + * + * @param resultY the height the object was placed at, negative when the placement rejected it + * @param commit what became of the blocks the object wrote + */ +public record CavePlacement(int resultY, Commit commit) { + public enum Commit { + /** The blocks were written. */ + COMMITTED, + /** The object wrote no blocks, or the placement was rejected. */ + EMPTY, + /** Some block lay outside the cave, so nothing was written. */ + REJECTED_BOUNDS + } + + public boolean wroteBlocks() { + return commit == Commit.COMMITTED; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/Cavern.java b/src/main/java/art/arcane/iris/builtin/objects/Cavern.java new file mode 100644 index 000000000..8a524fea3 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/Cavern.java @@ -0,0 +1,29 @@ +/* + * 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.builtin.objects; + +/** + * A carved void of the mantle, as the cave carver left it. + * + * @param air whether the void holds air + * @param liquid the carver's liquid code for the void; {@link #FORCED_AIR_LIQUID} means air that stays air + */ +public record Cavern(boolean air, byte liquid) { + public static final byte FORCED_AIR_LIQUID = 3; +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java new file mode 100644 index 000000000..822163a0f --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java @@ -0,0 +1,56 @@ +/* + * 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.builtin.objects; + +import art.arcane.volmlib.util.math.RNG; + +/** + * The chunk whose mantle {@code iris:objects} is placing into: the one place objects are written. Every placement here + * runs Iris's placement stages, so it is what a pack's {@code objects} get when they are placed anywhere. Reached through + * {@link ObjectHost#chunk()} from a mantle stage. + */ +public interface ObjectChunk { + /** The voids the cave carver planned around the chunk. */ + CarvedSpace carved(); + + /** Whether the golden-debug switch is on for the chunk, which logs every decision of its placements. */ + boolean goldenDebug(int chunkX, int chunkZ); + + /** + * Places an object on the terrain, where it sits at the height its place mode finds. + * + * @param goldenTag logs the placer's questions under this tag, or null to leave them + * @return the height the object was placed at, negative when the placement rejected it + */ + int placeOnSurface(PlaceableObject object, int x, int z, PlacementSource placement, PlacementChanges changes, + PlacementTags tags, RNG rng, String goldenTag); + + /** + * Places an object in a cave, anchored at {@code anchorY}, and writes it only when all of it lies inside the cave and + * no deeper than {@code minDepthBelowSurface} under the surface. + * + * @param goldenTag logs the placer's questions under this tag, or null to leave them + */ + CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, PlacementSource placement, PlacementChanges changes, + int minDepthBelowSurface, PlacementTags tags, RNG rng, String goldenTag); + + /** Places an object at a given height, which the terrain stacked above uses for the objects hung from it. */ + int placeUpper(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, + PlacementTags tags, RNG rng); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java new file mode 100644 index 000000000..ef42019eb --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java @@ -0,0 +1,125 @@ +/* + * 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.builtin.objects; + +import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings; +import com.volmit.config.PackSettings; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * What {@code iris:objects} asks of Iris: the objects of the pack, how Iris scales and places them, and the layout around + * a world position. Iris's worlds implement it; a module reaches it with {@link #of}. Nothing here hands out the engine. + */ +public interface ObjectHost { + /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ + static ObjectHost of(PackSettings settings) { + if (settings instanceof Source source) { + return source.objects(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); + } + + /** The host of {@code world}, which must be a world Iris generates. */ + static ObjectHost of(PackWorld world) { + if (world instanceof Source source) { + return source.objects(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** Whether Iris's debug setting is on. */ + boolean debugging(); + + /** The height, above the dimension's bottom, up to which caves are filled with lava. */ + int caveLavaHeight(); + + /** The height of the dimension's fluid. */ + int fluidHeight(); + + /** The settings that apply at a world column, for work outside a chunk's generation. */ + FeatureSettings columnSettings(); + + /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ + RNG chunkRandom(int chunkX, int chunkZ); + + /** The chunk whose objects are being placed on this thread. */ + ObjectChunk chunk(); + + /** The object of the pack that {@code key} names. */ + Optional object(String key); + + /** An object of the placement, picked with {@code rng} and scaled the way the placement scales it; empty when it has none. */ + Optional pickScaled(ObjectPlacement placement, RNG rng); + + /** How many objects the placement places at the column, when its chance check passes. */ + int density(ObjectPlacement placement, RNG rng, double x, double z); + + /** The size of the pack's object, read without loading its blocks; empty when the pack has no such object. */ + Optional sizeOf(String objectKey); + + /** Builds what placing the placement would build on first use, so the first chunk to place it does not wait. */ + void warm(ObjectPlacement placement, RNG rng); + + /** The procedural objects {@code settings} declare, made placeable once. */ + List procedural(ProceduralObjectSettings settings); + + /** The object settings of the biome and the region of the dimension stacked above, at the column; none where nothing sits above. */ + Optional upperObjects(int worldX, int worldZ); + + /** Places the object into {@code sink}, which is outside any chunk's generation, such as a growing sapling's tree. */ + int placeInto(PlaceableObject object, int x, int y, int z, ObjectPlacement placement, ObjectSink sink, RNG rng); + + /** The region at the column. */ + ResourceId regionAt(int worldX, int worldZ); + + /** The surface biome at the column. */ + ResourceId surfaceBiomeAt(int worldX, int worldZ); + + /** The biome at the position, which is the cave biome underground. */ + ResourceId biomeAt(int worldX, int y, int worldZ); + + /** The settings the biome declares itself, whichever column it is found at; empty when it declares none. */ + Optional biomeDeclaration(ResourceId biome, Class type); + + /** The settings the region declares itself; empty when it declares none. */ + Optional regionDeclaration(ResourceId region, Class type); + + /** Every region and every reachable biome that declares the settings, by the key the pack knows it by, regions first. */ + List> declarations(Class type); + + /** What the dimension stacked above declares to place at a column, where each is null when its level declares none. */ + record UpperObjects(ObjectSettings biome, ObjectSettings region, String biomeKey, String regionKey) { + } + + /** Iris's worlds answer for their objects. */ + interface Source { + ObjectHost objects(); + } + + /** One region's or biome's declaration of settings. */ + record Declaration(Target level, String key, F settings) { + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index d0fc5c6e4..04479458a 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -65,7 +65,7 @@ import java.util.Optional; @Snippet("object-placer") @Desc("Represents an iris object placer. It places objects.") @JsonAdapter(ObjectPlacement.KeepingItsJson.class) -public final class ObjectPlacement { +public final class ObjectPlacement implements PlacementSource { private static final int DEFAULT_SURFACE_SUPPORT_BUFFER = 2; private static final int DEFAULT_SURFACE_SUPPORT_DEPTH = 2; @@ -190,6 +190,7 @@ public final class ObjectPlacement { return place == null ? List.of() : Collections.unmodifiableList(place); } + @Override public double chance() { return chance; } @@ -227,6 +228,7 @@ public final class ObjectPlacement { return warp; } + @Override public ObjectPlaceMode mode() { return mode; } @@ -235,18 +237,22 @@ public final class ObjectPlacement { return Optional.ofNullable(vacuumSettings); } + @Override public CarvingMode carvingSupport() { return carvingSupport; } + @Override public CaveAnchorMode caveAnchorMode() { return caveAnchorMode; } + @Override public boolean underwater() { return underwater; } + @Override public boolean isDolphinTarget() { return isDolphinTarget; } @@ -255,10 +261,12 @@ public final class ObjectPlacement { return forcePlace; } + @Override public boolean requireSurfaceSupport() { return requireSurfaceSupport; } + @Override public int surfaceSupportBuffer() { return surfaceSupportBuffer; } diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java new file mode 100644 index 000000000..777ef63e4 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java @@ -0,0 +1,34 @@ +/* + * 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.builtin.objects; + +import com.volmit.block.BlockState; + +/** Where an object placed through {@link ObjectHost#placeInto} reads the world around it and writes its blocks. */ +public interface ObjectSink { + /** The height of the highest block at the column; {@code ignoreFluid} leaves out the fluid above the ground. */ + int highest(int x, int z, boolean ignoreFluid); + + BlockState get(int x, int y, int z); + + void set(int x, int y, int z, BlockState state); + + /** The height of the dimension's fluid. */ + int fluidHeight(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java new file mode 100644 index 000000000..62a0119dc --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java @@ -0,0 +1,23 @@ +/* + * 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.builtin.objects; + +/** The size of an object, in blocks. */ +public record ObjectSize(int width, int height, int depth) { +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java b/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java new file mode 100644 index 000000000..8aafb4eab --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java @@ -0,0 +1,34 @@ +/* + * 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.builtin.objects; + +/** An object of the pack, or one made for a placement, that {@link ObjectHost} can place; Iris's own object class is one. */ +public interface PlaceableObject { + /** The key the pack loads the object by, or the key a procedural object is given; null for an object made in code. */ + String key(); + + /** How wide the object is, in blocks. */ + int width(); + + /** How tall the object is, in blocks. */ + int height(); + + /** How deep the object is, in blocks. */ + int depth(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java new file mode 100644 index 000000000..38348fa33 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java @@ -0,0 +1,69 @@ +/* + * 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.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; + +import java.util.List; + +/** + * How a placement differs from the settings it was read from, when {@code iris:objects} places it: a field that is + * null is left as the settings have it. + * + * @param place the objects the placement names, replacing the settings' + * @param mode the place mode + * @param upsideDown whether the object is turned over, for the objects hung from the terrain stacked above + * @param carvingSupport where the placement may place + * @param requireSurfaceSupport whether a surface placement needs solid ground under it + * @param surfaceSupportBuffer the buffer of solid ground around the object's base + * @param forcePlace whether the placement ignores the placement restrictions + */ +public record PlacementChanges(List place, ObjectPlaceMode mode, Boolean upsideDown, CarvingMode carvingSupport, + Boolean requireSurfaceSupport, Integer surfaceSupportBuffer, Boolean forcePlace) { + public static final PlacementChanges NONE = new PlacementChanges(null, null, null, null, null, null, null); + + public boolean isNone() { + return this.equals(NONE); + } + + public PlacementChanges withPlace(List place) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withMode(ObjectPlaceMode mode) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withUpsideDown(boolean upsideDown) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withCarvingSupport(CarvingMode carvingSupport) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } + + public PlacementChanges withSurfaceSupport(boolean required, int buffer) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, required, buffer, forcePlace); + } + + public PlacementChanges withForcePlace(boolean forcePlace) { + return new PlacementChanges(place, mode, upsideDown, carvingSupport, requireSurfaceSupport, surfaceSupportBuffer, forcePlace); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java new file mode 100644 index 000000000..96a33efd0 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java @@ -0,0 +1,42 @@ +/* + * 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.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; + +/** What a placement is read from: an object placement of a biome or region, or a procedural object. */ +public interface PlacementSource { + double chance(); + + ObjectPlaceMode mode(); + + CarvingMode carvingSupport(); + + CaveAnchorMode caveAnchorMode(); + + boolean underwater(); + + boolean requireSurfaceSupport(); + + int surfaceSupportBuffer(); + + boolean isDolphinTarget(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java new file mode 100644 index 000000000..cefef139c --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java @@ -0,0 +1,29 @@ +/* + * 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.builtin.objects; + +/** + * What a placement writes into the mantle besides the blocks, beside each block of the object. + * + * @param marker the placement marker to write beside every block the object places, or null for none + * @param treeMaterial whether the block is also written as the tree material the mantle keeps for felling and growth + * @param buriedTreasure whether storage chests among the blocks are marked as buried treasure + */ +public record PlacementTags(String marker, boolean treeMaterial, boolean buriedTreasure) { +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java new file mode 100644 index 000000000..ee0e55fab --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java @@ -0,0 +1,88 @@ +/* + * 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.builtin.objects; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.volmlib.util.math.RNG; + +import java.util.List; +import java.util.Optional; + +/** + * A procedural object of a region or biome made placeable: a pool of variants Iris bakes once from its settings, and + * the options it is scattered with, like an object placement. + */ +public interface ProceduralPlacement extends PlacementSource { + String name(); + + @Override + double chance(); + + int density(); + + /** Whether the variants are meant to look like the real thing, so leaves decay. */ + boolean plausible(); + + /** Whether the variants are trees. */ + boolean tree(); + + @Override + ObjectPlaceMode mode(); + + @Override + CarvingMode carvingSupport(); + + @Override + CaveAnchorMode caveAnchorMode(); + + @Override + boolean underwater(); + + @Override + default boolean requireSurfaceSupport() { + return true; + } + + @Override + default int surfaceSupportBuffer() { + return 2; + } + + @Override + default boolean isDolphinTarget() { + return false; + } + + ObjectRotation rotation(); + + ObjectTranslate translate(); + + Optional vacuumSettings(); + + /** One of the variants, picked with {@code rng}; empty when none baked. */ + Optional variant(RNG rng); + + /** Every variant, baked on first use. */ + List variants(); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java b/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java index bc3fdbdab..49ff9b31b 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java +++ b/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java @@ -257,6 +257,14 @@ public final class Tree { public Tree() { } + /** The key the variant {@code index} of the tree named {@code name} is loaded under, which placement markers and the sapling tree list name. */ + public static String variantLoadKey(String name, int index) { + if (index < 0) { + throw new IllegalArgumentException("index must not be negative"); + } + return "procedural/tree/" + name + "#" + index; + } + public String name() { return name; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java new file mode 100644 index 000000000..71cabe0de --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java @@ -0,0 +1,228 @@ +/* + * 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.carve.CaveAnchorMode; +import art.arcane.iris.builtin.objects.CarvedSpace; +import art.arcane.iris.builtin.objects.Cavern; +import art.arcane.volmlib.util.cache.CacheKey; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; +import com.volmit.world.TerrainSampler; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** Finds the places in the carved caves of a chunk where a cave object may be anchored, remembering what it scanned. */ +final class CaveAnchors { + private static final int BEDROCK_CLEARANCE = 6; + private static final int SOLID_NEIGHBOR_REACH_BLOCKS = 3; + private static final int MAX_PACKED_SETTING = 65535; + + private final CarvedSpace carved; + private final TerrainSampler terrain; + private final int worldHeight; + private final int caveLavaHeight; + private final Map>> anchorsBySetting = new HashMap<>(); + private final Map carvedColumns = new HashMap<>(); + private final Map surfaceHeights = new HashMap<>(); + + CaveAnchors(CarvedSpace carved, TerrainSampler terrain, int worldHeight, int caveLavaHeight) { + this.carved = carved; + this.terrain = terrain; + this.worldHeight = worldHeight; + this.caveLavaHeight = caveLavaHeight; + } + + /** A position to anchor a cave object at. */ + record Anchor(int x, int y, int z) { + } + + /** How a cave placement looks for its anchor. */ + record Search(CaveAnchorMode mode, int scanStep, int minDepthBelowSurface, int attempts) { + } + + /** + * Looks for an anchor in the chunk whose first block is {@code minX}, {@code minZ}: a column picked at random, a height in + * it picked among those the mode accepts, tried up to the search's attempts. + * + * @param expectedCaveBiome the cave biome the anchor has to be in, or null for any + * @return the anchor, or null when no attempt found one + */ + Anchor find(RNG rng, int minX, int minZ, Search search, ResourceId expectedCaveBiome, boolean underwater) { + for (int attempt = 0; attempt < search.attempts(); attempt++) { + int candidateX = rng.i(minX, minX + 16); + int candidateZ = rng.i(minZ, minZ + 16); + int candidateY = anchorY(rng, candidateX, candidateZ, search); + if (candidateY < 0 + || biomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiome) + || !acceptsFluid(underwater, carved.cavernAt(candidateX, candidateY, candidateZ), candidateY, caveLavaHeight)) { + continue; + } + return new Anchor(candidateX, candidateY, candidateZ); + } + return null; + } + + static boolean acceptsFluid(boolean underwater, Optional cavern, int y, int lavaHeight) { + if (cavern.isEmpty()) { + return false; + } + if (underwater || cavern.get().liquid() == Cavern.FORCED_AIR_LIQUID) { + return true; + } + return cavern.get().air() && y > lavaHeight; + } + + /** One above the highest height an anchor may sit at, or 0 when none may. */ + static int scanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) { + int maxAnchorY = maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface); + if (maxAnchorY <= 1) { + return 0; + } + return maxAnchorY + 1; + } + + /** The highest height a cave object may reach: no deeper than {@code minDepthBelowSurface} under the surface. */ + static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) { + return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface)); + } + + /** Whether the cave biome at the position is not the one expected, nor the surface biome the cave sits under. */ + private boolean biomeConflicts(int x, int y, int z, ResourceId expectedCaveBiome) { + if (expectedCaveBiome == null) { + return false; + } + BiomeSample sample = terrain.biome(x, y, z); + return biomeConflicts(sample.caveBiome().orElse(null), sample.surfaceBiome(), expectedCaveBiome); + } + + static boolean biomeConflicts(ResourceId at, ResourceId surface, ResourceId expectedCaveBiome) { + if (expectedCaveBiome == null || at == null) { + return false; + } + if (at.equals(expectedCaveBiome)) { + return false; + } + return surface == null || !at.equals(surface); + } + + private int anchorY(RNG rng, int x, int z, Search search) { + List anchors = anchorsAt(x, z, search); + if (anchors.isEmpty()) { + return -1; + } + if (anchors.size() == 1) { + return anchors.get(0); + } + return anchors.get(rng.i(anchors.size())); + } + + private List anchorsAt(int x, int z, Search search) { + if (search.scanStep() > MAX_PACKED_SETTING || search.minDepthBelowSurface() > MAX_PACKED_SETTING) { + return scanColumn(x, z, search); + } + long settingKey = ((long) search.mode().ordinal() << 32) | ((long) search.scanStep() << 16) | search.minDepthBelowSurface(); + Map> columns = anchorsBySetting.computeIfAbsent(settingKey, key -> new HashMap<>()); + long columnKey = CacheKey.key(x, z); + List anchors = columns.get(columnKey); + if (anchors != null) { + return anchors; + } + anchors = scanColumn(x, z, search); + columns.put(columnKey, anchors); + return anchors; + } + + private List scanColumn(int x, int z, Search search) { + int step = Math.max(1, search.scanStep()); + int surfaceY = surfaceHeight(x, z); + int maxAnchorExclusive = scanUpperBound(worldHeight, surfaceY, search.minDepthBelowSurface()); + if (maxAnchorExclusive == 0) { + return new ArrayList<>(); + } + int carvedHeight = Math.min(worldHeight, maxAnchorExclusive + 3); + byte[] carvedColumn = carvedColumn(x, z, carvedHeight); + return scanRange(search.mode(), step, carvedHeight, maxAnchorExclusive, carvedColumn); + } + + private List scanRange(CaveAnchorMode mode, int step, int height, int maxAnchorY, byte[] carvedColumn) { + List anchors = new ArrayList<>(); + for (int y = BEDROCK_CLEARANCE; y < maxAnchorY; y += step) { + if (!isCarved(carvedColumn, y)) { + continue; + } + boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1); + boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1); + if (matches(mode, solidBelow, solidAbove)) { + anchors.add(y); + } + } + return anchors; + } + + private static boolean isCarved(byte[] carvedColumn, int y) { + return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1; + } + + private static boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) { + for (int distance = 1; distance <= SOLID_NEIGHBOR_REACH_BLOCKS; distance++) { + int neighbor = y + (direction * distance); + if (neighbor < 0 || neighbor >= height || !isCarved(carvedColumn, neighbor)) { + return true; + } + } + return false; + } + + private static boolean matches(CaveAnchorMode mode, boolean solidBelow, boolean solidAbove) { + return switch (mode) { + case PROFILE_DEFAULT, FLOOR -> solidBelow; + case CEILING -> solidAbove; + case CENTER -> !solidBelow && !solidAbove; + case ANY -> true; + }; + } + + private byte[] carvedColumn(int x, int z, int height) { + long columnKey = CacheKey.key(x, z); + byte[] column = carvedColumns.get(columnKey); + if (column != null && column.length == height) { + return column; + } + column = carved.column(x, z, height); + carvedColumns.put(columnKey, column); + return column; + } + + private int surfaceHeight(int x, int z) { + long columnKey = CacheKey.key(x, z); + Integer known = surfaceHeights.get(columnKey); + if (known != null) { + return known; + } + int surfaceY = (int) Math.round(terrain.surfaceY(x, z)); + surfaceHeights.put(columnKey, surfaceY); + return surfaceY; + } +} 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 index c29157880..b8af13f46 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java @@ -32,7 +32,7 @@ import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; -final class CaveObjectPlacementTransaction implements IObjectPlacer { +public final class CaveObjectPlacementTransaction implements IObjectPlacer { private static final int CACHE_MISS = Integer.MIN_VALUE; private final IObjectPlacer delegate; @@ -46,7 +46,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { private final Long2IntOpenHashMap caveCeilings; private int blockWrites; - CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) { + public CaveObjectPlacementTransaction(IObjectPlacer delegate, int anchorY, int minDepthBelowSurface) { this.delegate = delegate; this.engine = delegate.getEngine(); this.anchorY = anchorY; @@ -60,7 +60,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { this.caveCeilings.defaultReturnValue(CACHE_MISS); } - CommitResult commit() { + public CommitResult commit() { if (blockWrites == 0) { discard(); return CommitResult.EMPTY; @@ -80,13 +80,13 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { return CommitResult.COMMITTED; } - void discard() { + public void discard() { mutations.clear(); bufferedBlocks.clear(); blockWrites = 0; } - int getCaveCeiling(int x, int z) { + public int getCaveCeiling(int x, int z) { long key = CacheKey.key(x, z); int cached = caveCeilings.get(key); if (cached != CACHE_MISS) { @@ -242,7 +242,7 @@ final class CaveObjectPlacementTransaction implements IObjectPlacer { return Math.min(worldHeight, scanLimit + 1); } - enum CommitResult { + public enum CommitResult { COMMITTED, EMPTY, REJECTED_BOUNDS diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java new file mode 100644 index 000000000..0dd2f8ff6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java @@ -0,0 +1,69 @@ +/* + * 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.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.PlaceableObject; +import com.volmit.ModuleLog; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +/** Debug lines for cave objects that were not placed, at most one per kind of rejection every few seconds. */ +final class CaveRejects { + private static final long THROTTLE_MILLIS = 5000L; + private static final Map STATES = new ConcurrentHashMap<>(); + + private CaveRejects() { + } + + static void log(ObjectHost host, ModuleLog log, String scope, String reason, int chunkX, int chunkZ, ObjectPlacement placement, + PlaceableObject object, int densityIndex, int density, CaveAnchors.Search search, Integer anchorY, Throwable error) { + if (!host.debugging()) { + return; + } + String placementKeys = placement == null ? "none" : String.join(",", placement.place()); + String objectKey = object == null ? "null" : object.key(); + String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; + State state = STATES.computeIfAbsent(throttleKey, key -> new State()); + long now = System.currentTimeMillis(); + long last = state.lastLogMillis.get(); + if ((now - last) < THROTTLE_MILLIS || !state.lastLogMillis.compareAndSet(last, now)) { + state.suppressed.incrementAndGet(); + return; + } + int suppressed = state.suppressed.getAndSet(0); + String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + error.getMessage(); + log.debug("Cave object reject: scope=" + scope + " reason=" + reason + " chunk=" + chunkX + "," + chunkZ + " object=" + objectKey + + " placements=" + placementKeys + " densityIndex=" + densityIndex + " density=" + density + + " anchorMode=" + search.mode() + " anchorSearchAttempts=" + search.attempts() + " anchorScanStep=" + search.scanStep() + + " minDepthBelowSurface=" + search.minDepthBelowSurface() + " anchorY=" + (anchorY == null ? "none" : anchorY) + + " forcePlace=" + (placement != null && placement.forcePlace()) + + " carvingSupport=" + (placement == null ? "none" : placement.carvingSupport()) + + " suppressed=" + suppressed + " error=" + errorText); + } + + private static final class State { + private final AtomicLong lastLogMillis = new AtomicLong(0L); + private final AtomicInteger suppressed = new AtomicInteger(0); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java new file mode 100644 index 000000000..cff789b80 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java @@ -0,0 +1,88 @@ +/* + * 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.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.objects.PlacementSource; + +/** What a cave object placement takes from the cave profile that applies to it. */ +final class CaveSettings { + private static final CaveProfile DEFAULT_PROFILE = new CaveProfile(); + private static final int DEFAULT_SCAN_STEP = 1; + private static final int DEFAULT_MIN_DEPTH_BELOW_SURFACE = 6; + private static final int DEFAULT_SEARCH_ATTEMPTS = 6; + + private final CaveProfile dimensionProfile; + + CaveSettings(CaveProfile dimensionProfile) { + this.dimensionProfile = dimensionProfile; + } + + /** The profile of the first of {@code preferred} and {@code secondary} that is enabled, else the dimension's, else the default one. */ + CaveProfile resolve(CaveProfile preferred, CaveProfile secondary) { + if (preferred != null && preferred.enabled()) { + return preferred; + } + if (secondary != null && secondary.enabled()) { + return secondary; + } + if (dimensionProfile != null) { + return dimensionProfile; + } + return DEFAULT_PROFILE; + } + + /** How the placement looks for its anchor in caves: its own mode, else the profile's, else the floor; turned upside down, the ceiling. */ + CaveAnchors.Search searchFor(PlacementSource placement, CaveProfile profile) { + CaveAnchorMode mode = anchorMode(placement, profile); + if (placement.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { + mode = CaveAnchorMode.CEILING; + } + return new CaveAnchors.Search(mode, scanStep(profile), minDepthBelowSurface(profile), searchAttempts(profile)); + } + + private static CaveAnchorMode anchorMode(PlacementSource placement, CaveProfile profile) { + CaveAnchorMode placementMode = placement.caveAnchorMode(); + if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return placementMode; + } + if (profile == null) { + return CaveAnchorMode.FLOOR; + } + CaveAnchorMode profileMode = profile.defaultObjectAnchor(); + if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { + return CaveAnchorMode.FLOOR; + } + return profileMode; + } + + private static int scanStep(CaveProfile profile) { + return profile == null ? DEFAULT_SCAN_STEP : Math.max(1, profile.anchorScanStep()); + } + + private static int minDepthBelowSurface(CaveProfile profile) { + return profile == null ? DEFAULT_MIN_DEPTH_BELOW_SURFACE : Math.max(0, profile.objectMinDepthBelowSurface()); + } + + private static int searchAttempts(CaveProfile profile) { + return profile == null ? DEFAULT_SEARCH_ATTEMPTS : Math.max(1, profile.anchorSearchAttempts()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java new file mode 100644 index 000000000..677f0aba4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -0,0 +1,680 @@ +/* + * 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.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.objects.CavePlacement; +import art.arcane.iris.builtin.objects.ObjectChunk; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.PlacementChanges; +import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.builtin.objects.PlacementTags; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralPlacement; +import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; +import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; +import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; +import art.arcane.iris.builtin.objects.UpperObjectsSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.TerrainSampler; + +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * Places what the objects of one chunk's region and biomes say: the objects of its surface, caves and the terrain stacked above, + * and its procedural objects, in that order, all drawing from the one random of the chunk. + */ +final class ChunkObjectPlacing { + private static final int CENTER_OFFSET_BLOCKS = 8; + private static final int CHUNK_SHIFT = 4; + private static final int CHUNK_WIDTH_BLOCKS = 16; + private static final double CHANCE_JITTER = 0.005; + private static final int[] CAVE_BIOME_SAMPLE_DEPTHS = {48, 80, 112}; + private static final int LEGACY_CAVE_SAMPLE_DEPTH = 48; + private static final int UPPER_SURFACE_MARGIN_BLOCKS = 2; + private static final int MINIMUM_UPPER_ANCHOR_Y = 1; + private static final int DIAGNOSTIC_CHUNK_MASK = 31; + private static final int DIAGNOSTIC_SURFACE_MARGIN = 14; + private static final String TREE_FOLDER = "trees/"; + private static final String REGEN_THREAD_PREFIX = "Iris-Regen-"; + + private final ObjectHost host; + private final ModuleLog log; + private final MantleStageContext context; + private final ObjectChunk chunk; + private final TerrainSampler terrain; + private final int chunkX; + private final int chunkZ; + private final int centerX; + private final int centerZ; + private final RNG rng; + private final boolean traceRegen; + private final boolean golden; + private final EffectivePlacements effective; + private final CaveSettings caves; + private final int worldHeight; + private final int caveLavaHeight; + + ChunkObjectPlacing(ObjectHost host, ModuleLog log, MantleStageContext context) { + this.host = host; + this.log = log; + this.context = context; + this.chunk = host.chunk(); + this.terrain = context.terrain(); + this.chunkX = context.originX() >> CHUNK_SHIFT; + this.chunkZ = context.originZ() >> CHUNK_SHIFT; + this.centerX = CENTER_OFFSET_BLOCKS + (chunkX << CHUNK_SHIFT); + this.centerZ = CENTER_OFFSET_BLOCKS + (chunkZ << CHUNK_SHIFT); + this.rng = host.chunkRandom(chunkX, chunkZ); + this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && host.debugging(); + this.golden = chunk.goldenDebug(chunkX, chunkZ); + this.worldHeight = context.mantle().bounds().maxY(); + this.caveLavaHeight = host.caveLavaHeight(); + this.effective = new EffectivePlacements(dimensionRequiresSurfaceSupport(), dimensionSurfaceSupportBuffer()); + this.caves = new CaveSettings(dimensionLevel(CaveProfile.class)); + } + + /** Places what originates in this chunk. */ + void place() { + Column column = readColumn(); + if (host.debugging() && (chunkX & DIAGNOSTIC_CHUNK_MASK) == 0 && (chunkZ & DIAGNOSTIC_CHUNK_MASK) == 0) { + logCaveDiagnostics(column); + } + if (traceRegen) { + logLayerStart(column); + } + Tally tally = placeObjects(column); + placeProceduralObjects(column); + if (upperObjectsEnabled()) { + placeUpperObjects(column); + } + if (traceRegen) { + logLayerDone(tally); + } + } + + /** The region and biomes at the chunk's centre and what each declares. */ + private Column readColumn() { + ResourceId region = host.regionAt(centerX, centerZ); + ResourceId surface = host.surfaceBiomeAt(centerX, centerZ); + int surfaceY = surfaceY(centerX, centerZ); + ResourceId cave = resolveCaveObjectBiome(surfaceY, surface); + return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), proceduralOf(cave, region, surface), + profilesOf(cave, region, surface)); + } + + private int surfaceY(int x, int z) { + return (int) Math.round(terrain.surfaceY(x, z)); + } + + private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) { + ResourceId legacy = caveBiomeAt(Math.max(1, surfaceY - LEGACY_CAVE_SAMPLE_DEPTH)).orElse(surfaceBiome); + ResourceId ladderChoice = null; + for (int depth : CAVE_BIOME_SAMPLE_DEPTHS) { + Optional sampled = caveBiomeAt(Math.max(1, surfaceY - depth)); + if (sampled.isEmpty() || sampled.get().equals(surfaceBiome)) { + continue; + } + if (hasCarvingObjects(host.biomeDeclaration(sampled.get(), ObjectSettings.class))) { + ladderChoice = sampled.get(); + } + } + return ladderChoice != null ? ladderChoice : legacy; + } + + private Optional caveBiomeAt(int y) { + return terrain.biome(centerX, y, centerZ).caveBiome(); + } + + private static boolean hasCarvingObjects(Optional settings) { + return settings.isPresent() && !carvingObjects(settings.get()).isEmpty(); + } + + private ColumnObjects objectsOf(ResourceId cave, ResourceId region, ResourceId surface) { + List> entries = context.settings().at(ObjectSettings.class, centerX, centerZ); + return new ColumnObjects(level(entries, Target.BIOME), caveSettings(cave, surface, entries, ObjectSettings.class), level(entries, Target.REGION)); + } + + private ColumnProcedural proceduralOf(ResourceId cave, ResourceId region, ResourceId surface) { + List> entries = context.settings().at(ProceduralObjectSettings.class, centerX, centerZ); + return new ColumnProcedural(level(entries, Target.BIOME), + caveSettings(cave, surface, entries, ProceduralObjectSettings.class), level(entries, Target.REGION)); + } + + private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) { + List> entries = context.settings().at(CaveProfile.class, centerX, centerZ); + return new ColumnProfiles(level(entries, Target.BIOME), caveSettings(cave, surface, entries, CaveProfile.class), level(entries, Target.REGION)); + } + + private F caveSettings(ResourceId cave, ResourceId surface, List> entries, Class type) { + if (cave.equals(surface)) { + return level(entries, Target.BIOME); + } + return host.biomeDeclaration(cave, type).orElse(null); + } + + private F dimensionLevel(Class type) { + return level(context.settings().at(type, centerX, centerZ), Target.DIMENSION); + } + + private static F level(List> entries, Target level) { + for (Entry entry : entries) { + if (entry.level() == level) { + return entry.value(); + } + } + return null; + } + + private boolean dimensionRequiresSurfaceSupport() { + RequireSurfaceSupportSettings settings = dimensionLevel(RequireSurfaceSupportSettings.class); + return settings == null ? new RequireSurfaceSupportSettings().require() : settings.require(); + } + + private int dimensionSurfaceSupportBuffer() { + SurfaceSupportBufferSettings settings = dimensionLevel(SurfaceSupportBufferSettings.class); + return settings == null ? new SurfaceSupportBufferSettings().buffer() : settings.buffer(); + } + + private boolean upperObjectsEnabled() { + UpperObjectsSettings settings = dimensionLevel(UpperObjectsSettings.class); + return settings != null && settings.enabled() && terrain.upperDimensionY(centerX, centerZ).isPresent(); + } + + private boolean upperObjectsForced() { + UpperObjectsForceSettings settings = dimensionLevel(UpperObjectsForceSettings.class); + return settings != null && settings.force(); + } + + private static List surfaceObjects(ObjectSettings settings) { + return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsSurface()).toList(); + } + + private static List carvingObjects(ObjectSettings settings) { + return settings == null ? List.of() : settings.objects().stream().filter(p -> p.carvingSupport().supportsCarving()).toList(); + } + + private CaveAnchors newAnchors() { + return new CaveAnchors(chunk.carved(), terrain, worldHeight, caveLavaHeight); + } + + private Tally placeObjects(Column column) { + Tally tally = new Tally(); + CaveProfile biomeCaveProfile = caves.resolve(column.profiles().cave(), column.profiles().region()); + CaveProfile regionCaveProfile = caves.resolve(column.profiles().region(), column.profiles().cave()); + CaveAnchors anchors = newAnchors(); + placeSurfaceScope(tally, "biome-surface", surfaceObjects(column.objects().surface()), column.surface().toString()); + placeCaveScope(tally, "biome-cave", carvingObjects(column.objects().cave()), biomeCaveProfile, column.cave(), column.cave().toString(), anchors); + placeSurfaceScope(tally, "region-surface", surfaceObjects(column.objects().region()), column.region().toString()); + placeCaveScope(tally, "region-cave", carvingObjects(column.objects().region()), regionCaveProfile, null, column.region().toString(), anchors); + return tally; + } + + private void placeSurfaceScope(Tally tally, String scope, List placements, String ownerName) { + for (ObjectPlacement placement : placements) { + tally.checked(scope); + boolean passes = rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER)); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); + try { + placeObject(tally, placement, scope); + } catch (Throwable failure) { + tally.errors++; + logPlacementFailure("Failed to place objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure); + } + } + } + + private void placeCaveScope(Tally tally, String scope, List placements, CaveProfile profile, + ResourceId expectedCaveBiome, String ownerName, CaveAnchors anchors) { + for (ObjectPlacement placement : placements) { + tally.checked(scope); + boolean passes = rng.chance(placement.chance()); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); + try { + placeCaveObject(tally, placement, profile, scope, expectedCaveBiome, anchors); + } catch (Throwable failure) { + tally.errors++; + logPlacementFailure("Failed to place cave objects in the following " + ownerKind(scope) + ": " + ownerName, placement, failure); + } + } + } + + private static String ownerKind(String scope) { + return scope.startsWith("biome") ? "biome" : "region"; + } + + private void logPlacementFailure(String message, ObjectPlacement placement, Throwable failure) { + log.error(message, failure); + log.error("Object(s) " + String.join(", ", placement.place()) + " (" + failure.getClass().getSimpleName() + ").", null); + log.error("Are these objects missing?", null); + } + + private void placeObject(Tally tally, ObjectPlacement placement, String scope) { + int blockX = chunkX << CHUNK_SHIFT; + int blockZ = chunkZ << CHUNK_SHIFT; + int density = host.density(placement, rng, blockX, blockZ); + for (int i = 0; i < density; i++) { + tally.attempts++; + Optional picked = host.pickScaled(placement, rng); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, i, density, placement); + continue; + } + PlaceableObject object = picked.get(); + int x = rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS); + int z = rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS); + PlacementChanges changes = effective.forSurface(placement, object); + boolean treePlacement = isTreePlacement(object, placement); + int id = rng.i(0, Integer.MAX_VALUE); + String goldenTag = golden ? scope + "/" + object.key() : null; + if (golden) { + log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " densityIndex=" + i + " xx=" + x + " zz=" + z + " mode=" + placement.mode()); + } + try { + PlacementTags tags = tags(object, id, "surface", treePlacement, placement); + int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, rng, goldenTag); + if (result >= 0) { + tally.placed++; + } else { + tally.rejected++; + } + traceObjectResult(scope, object, result, x, z, i, density); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + } + } + } + + private void placeCaveObject(Tally tally, ObjectPlacement placement, CaveProfile profile, String scope, + ResourceId expectedCaveBiome, CaveAnchors anchors) { + int minX = chunkX << CHUNK_SHIFT; + int minZ = chunkZ << CHUNK_SHIFT; + int density = host.density(placement, rng, minX, minZ); + CaveAnchors.Search search = caves.searchFor(placement, profile); + for (int i = 0; i < density; i++) { + tally.attempts++; + Optional picked = host.pickScaled(placement, rng); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, i, density, placement); + CaveRejects.log(host, log, scope, "NULL_OBJECT", chunkX, chunkZ, placement, null, i, density, search, null, null); + continue; + } + PlaceableObject object = picked.get(); + CaveAnchors.Anchor anchor = anchors.find(rng, minX, minZ, search, expectedCaveBiome, placement.underwater()); + if (anchor == null) { + tally.rejected++; + CaveRejects.log(host, log, scope, "NO_ANCHOR", chunkX, chunkZ, placement, object, i, density, search, null, null); + continue; + } + int id = rng.i(0, Integer.MAX_VALUE); + PlacementChanges changes = effective.forCave(placement, object, profile); + try { + PlacementTags tags = tags(object, id, "cave", isTreePlacement(object, placement), placement); + CavePlacement contained = chunk.placeInCave(object, anchor.x(), anchor.y(), anchor.z(), placement, changes, + search.minDepthBelowSurface(), tags, rng, null); + tallyCave(tally, contained, scope, object, placement, i, density, search, anchor); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen cave object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + CaveRejects.log(host, log, scope, "EXCEPTION", chunkX, chunkZ, placement, object, i, density, search, anchor.y(), failure); + } + } + } + + private void tallyCave(Tally tally, CavePlacement contained, String scope, PlaceableObject object, ObjectPlacement placement, + int index, int density, CaveAnchors.Search search, CaveAnchors.Anchor anchor) { + if (contained.wroteBlocks()) { + tally.placed++; + } else { + tally.rejected++; + CaveRejects.log(host, log, scope, rejectReason(contained), chunkX, chunkZ, placement, object, index, density, search, anchor.y(), null); + } + if (traceRegen) { + log.debug("Regen cave object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " resultY=" + contained.resultY() + " anchorY=" + anchor.y() + " px=" + anchor.x() + " pz=" + anchor.z() + + " wroteBlocks=" + contained.wroteBlocks() + " densityIndex=" + index + " density=" + density); + } + } + + private static String rejectReason(CavePlacement contained) { + if (contained.resultY() < 0) { + return "PLACE_NEGATIVE"; + } + return contained.commit() == CavePlacement.Commit.REJECTED_BOUNDS ? "CONTAINMENT" : "NO_WRITES"; + } + + private void placeProceduralObjects(Column column) { + List surface = proceduralPlacements(column.procedural().surface()); + List region = proceduralPlacements(column.procedural().region()); + CaveProfile surfaceProfile = caves.resolve(column.profiles().surface(), column.profiles().region()); + CaveProfile regionProfile = caves.resolve(column.profiles().region(), column.profiles().cave()); + placeProceduralFrom(surface, column.surface().toString(), surfaceProfile, column.surface()); + placeProceduralFrom(region, column.region().toString(), regionProfile, null); + if (!column.cave().equals(column.surface())) { + CaveProfile caveProfile = caves.resolve(column.profiles().cave(), column.profiles().region()); + placeProceduralFrom(proceduralPlacements(column.procedural().cave()), column.cave().toString(), caveProfile, column.cave()); + } + } + + private List proceduralPlacements(ProceduralObjectSettings settings) { + return settings == null ? List.of() : host.procedural(settings); + } + + private void placeProceduralFrom(List placements, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome) { + if (placements.isEmpty()) { + return; + } + int blockX = chunkX << CHUNK_SHIFT; + int blockZ = chunkZ << CHUNK_SHIFT; + CaveAnchors anchors = newAnchors(); + for (ProceduralPlacement placement : placements) { + boolean chancePassed = passesProceduralChance(rng, placement.chance()); + if (golden) { + log.debug("Goldendebug procedural chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " placement=" + placement.name() + " passed=" + chancePassed); + } + if (!chancePassed) { + continue; + } + placeProcedural(placement, scope, caveProfile, expectedCaveBiome, anchors, blockX, blockZ); + } + } + + private void placeProcedural(ProceduralPlacement placement, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome, + CaveAnchors anchors, int blockX, int blockZ) { + boolean carving = placement.carvingSupport() == CarvingMode.CARVING_ONLY; + CaveAnchors.Search search = caves.searchFor(placement, caveProfile); + int density = Math.max(1, placement.density()); + for (int i = 0; i < density; i++) { + Optional picked = placement.variant(rng); + if (picked.isEmpty()) { + if (golden) { + log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + i + " variant=null"); + } + continue; + } + PlaceableObject variant = picked.get(); + CaveAnchors.Anchor anchor = carving ? anchors.find(rng, blockX, blockZ, search, expectedCaveBiome, placement.underwater()) : null; + if (carving && anchor == null) { + if (golden) { + log.debug("Goldendebug procedural cave anchor rejected: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + + " minDepthBelowSurface=" + search.minDepthBelowSurface()); + } + continue; + } + int x = anchor == null ? rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS) : anchor.x(); + int z = anchor == null ? rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS) : anchor.z(); + int id = rng.i(0, Integer.MAX_VALUE); + if (golden) { + logProceduralPick(placement, variant, i, x, z, carving); + } + try { + placeProceduralVariant(placement, variant, scope, caveProfile, search, anchor, x, z, id); + } catch (Throwable failure) { + log.error("Failed to place procedural object '" + placement.name() + "' in " + scope, failure); + } + } + } + + private void placeProceduralVariant(ProceduralPlacement placement, PlaceableObject variant, String scope, CaveProfile caveProfile, + CaveAnchors.Search search, CaveAnchors.Anchor anchor, int x, int z, int id) { + String goldenTag = golden ? scope + "/" + placement.name() : null; + PlacementTags tags = tags(variant, id, "procedural", placement.tree(), placement, false); + int resultY; + String commit = "n/a"; + if (anchor != null) { + PlacementChanges changes = effective.forCave(placement, variant, caveProfile); + CavePlacement contained = chunk.placeInCave(variant, x, anchor.y(), z, placement, changes, search.minDepthBelowSurface(), tags, rng, goldenTag); + resultY = contained.resultY(); + commit = contained.commit().toString(); + } else { + resultY = chunk.placeOnSurface(variant, x, z, placement, PlacementChanges.NONE, tags, rng, goldenTag); + } + if (golden) { + log.debug("Goldendebug procedural result: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + + " variant=" + variant.key() + " xx=" + x + " zz=" + z + " resultY=" + resultY + " commit=" + commit); + } + } + + private void logProceduralPick(ProceduralPlacement placement, PlaceableObject variant, int index, int x, int z, boolean carving) { + List pool = placement.variants(); + log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + index + + " variant=" + variant.key() + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() + " xx=" + x + " zz=" + z + + " mode=" + placement.mode() + " carving=" + carving); + } + + static boolean passesProceduralChance(RNG rng, double chance) { + if (chance <= 0.0) { + return false; + } + if (chance >= 1.0) { + return true; + } + return rng.chance(Math.max(0.0, Math.min(1.0, chance + rng.d(-CHANCE_JITTER, CHANCE_JITTER)))); + } + + private void placeUpperObjects(Column column) { + Optional upper = host.upperObjects(centerX, centerZ); + if (upper.isEmpty() || (upper.get().biome() == null && upper.get().region() == null)) { + return; + } + boolean forcePlace = upperObjectsForced(); + placeUpperScope(upper.get().biome(), upper.get().biomeKey(), "upper-biome-surface", "biome", forcePlace); + placeUpperScope(upper.get().region(), upper.get().regionKey(), "upper-region-surface", "region", forcePlace); + } + + private void placeUpperScope(ObjectSettings settings, String ownerKey, String scope, String kind, boolean forcePlace) { + for (ObjectPlacement placement : surfaceObjects(settings)) { + if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + continue; + } + try { + placeUpperObject(placement, forcePlace, scope); + } catch (Throwable failure) { + log.error("Failed to place upper-dimension objects in " + kind + " " + ownerKey + ": " + String.join(", ", placement.place()) + + " (" + failure.getClass().getSimpleName() + ")", failure); + } + } + } + + private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) { + int minX = chunkX << CHUNK_SHIFT; + int minZ = chunkZ << CHUNK_SHIFT; + int density = host.density(placement, rng, minX, minZ); + for (int i = 0; i < density; i++) { + Optional picked = host.pickScaled(placement, rng); + if (picked.isEmpty()) { + continue; + } + PlaceableObject object = picked.get(); + int x = rng.i(minX, minX + CHUNK_WIDTH_BLOCKS); + int z = rng.i(minZ, minZ + CHUNK_WIDTH_BLOCKS); + OptionalInt upperSurface = terrain.upperDimensionY(x, z); + if (upperSurface.isEmpty() || upperSurface.getAsInt() >= worldHeight - UPPER_SURFACE_MARGIN_BLOCKS) { + continue; + } + int anchorY = upperSurface.getAsInt() - 1 - Math.floorDiv(object.height(), 2); + if (anchorY <= MINIMUM_UPPER_ANCHOR_Y) { + continue; + } + int id = rng.i(0, Integer.MAX_VALUE); + PlacementChanges changes = PlacementChanges.NONE.withPlace(List.of(String.valueOf(object.key()))) + .withMode(ObjectPlaceMode.CENTER_HEIGHT) + .withUpsideDown(true).withCarvingSupport(CarvingMode.ANYWHERE); + if (forcePlace) { + changes = changes.withForcePlace(true); + } + PlacementTags tags = tags(object, id, "upper", isTreePlacement(object, placement), placement); + int result = chunk.placeUpper(object, x, anchorY, z, placement, changes, tags, rng); + if (traceRegen) { + log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + " anchorY=" + + anchorY + " upperSurfaceY=" + upperSurface.getAsInt() + " resultY=" + result + " forcePlace=" + forcePlace); + } + } + } + + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement) { + return tags(object, id, context, treePlacement, placement, placement.isDolphinTarget() && placement.underwater()); + } + + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement, + boolean buriedTreasure) { + return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure); + } + + private String placementMarker(PlaceableObject object, int id, String context) { + String key = object == null ? null : object.key(); + if (key == null || key.isEmpty() || key.equals("null")) { + String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); + log.warnOnce(fingerprint, "Skipping placement marker write: the object has no loadKey (context=" + context + "). " + + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); + return null; + } + return key + "@" + id; + } + + private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) { + String key = object == null ? null : object.key(); + return (key != null && key.startsWith(TREE_FOLDER)) || (placement != null && !placement.trees().isEmpty()); + } + + private void traceChance(String scope, boolean passes, ObjectPlacement placement) { + if (!traceRegen) { + return; + } + log.debug("Regen object placer chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " chanceResult=" + passes + + " chanceBase=" + placement.chance() + " densityMid=" + placement.middleDensity() + " objects=" + placement.place().size()); + } + + private void traceNullObject(String scope, int index, int density, ObjectPlacement placement) { + if (!traceRegen) { + return; + } + log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " densityIndex=" + index + + " density=" + density + " placementKeys=" + String.join(",", placement.place())); + } + + private void traceObjectResult(String scope, PlaceableObject object, int result, int x, int z, int index, int density) { + if (golden) { + log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " resultY=" + result + " fallback=surface"); + } + if (traceRegen) { + log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + + " resultY=" + result + " px=" + x + " pz=" + z + " fallback=surface densityIndex=" + index + " density=" + density); + } + } + + private void logCaveDiagnostics(Column column) { + CarvedCount carved = new CarvedCount(); + int maxY = Math.min(worldHeight - 1, column.surfaceY() - DIAGNOSTIC_SURFACE_MARGIN); + for (int y = 1; y < maxY; y++) { + if (chunk.carved().isCarved(centerX, y, centerZ)) { + carved.blocks++; + } + } + log.debug("Cave object diag: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() + + " surfaceY=" + column.surfaceY() + " maxAnchorY=" + maxY + " carvedAtCenter=" + carved.blocks + + " biomeCarvingObjects=" + carvingObjects(column.objects().cave()).size() + + " regionCarvingObjects=" + carvingObjects(column.objects().region()).size() + + " sameBiome=" + column.cave().equals(column.surface())); + } + + private void logLayerStart(Column column) { + log.debug("Regen object layer start: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() + + " region=" + column.region() + " biomeSurfacePlacers=" + surfaceObjects(column.objects().surface()).size() + + " biomeCavePlacers=" + carvingObjects(column.objects().cave()).size() + + " regionSurfacePlacers=" + surfaceObjects(column.objects().region()).size() + + " regionCavePlacers=" + carvingObjects(column.objects().region()).size()); + } + + private void logLayerDone(Tally tally) { + log.debug("Regen object layer done: chunk=" + chunkX + "," + chunkZ + " " + tally.describe() + + " objectAttempts=" + tally.attempts + " objectPlaced=" + tally.placed + " objectRejected=" + tally.rejected + + " objectNull=" + tally.nullObjects + " objectErrors=" + tally.errors); + } + + private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects, + ColumnProcedural procedural, ColumnProfiles profiles) { + } + + private record ColumnObjects(ObjectSettings surface, ObjectSettings cave, ObjectSettings region) { + } + + private record ColumnProcedural(ProceduralObjectSettings surface, ProceduralObjectSettings cave, ProceduralObjectSettings region) { + } + + private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) { + } + + private static final class CarvedCount { + private int blocks; + } + + /** What placing the objects of a chunk came to. */ + private static final class Tally { + private final java.util.Map scopes = new java.util.LinkedHashMap<>(); + private int attempts; + private int placed; + private int rejected; + private int nullObjects; + private int errors; + + void checked(String scope) { + scopes.computeIfAbsent(scope, key -> new int[2])[0]++; + } + + void triggered(String scope) { + scopes.computeIfAbsent(scope, key -> new int[2])[1]++; + } + + String describe() { + StringBuilder text = new StringBuilder(); + scopes.forEach((scope, counts) -> text.append(scope).append("PlacersChecked=").append(counts[0]) + .append(' ').append(scope).append("PlacersTriggered=").append(counts[1]).append(' ')); + return text.toString(); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java new file mode 100644 index 000000000..22315d331 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -0,0 +1,90 @@ +/* + * 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.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.PlacementChanges; +import art.arcane.iris.builtin.objects.PlacementSource; + +import java.util.List; +import java.util.Locale; + +/** How a dimension and a cave profile change the placement an object is placed with. */ +final class EffectivePlacements { + private static final String IMPORTS_FOLDER = "imports/"; + + private final boolean dimensionRequiresSurfaceSupport; + private final int dimensionSurfaceSupportBuffer; + + EffectivePlacements(boolean dimensionRequiresSurfaceSupport, int dimensionSurfaceSupportBuffer) { + this.dimensionRequiresSurfaceSupport = dimensionRequiresSurfaceSupport; + this.dimensionSurfaceSupportBuffer = dimensionSurfaceSupportBuffer; + } + + /** The changes to make to {@code placement} to place {@code object} on the surface. */ + PlacementChanges forSurface(PlacementSource placement, PlaceableObject object) { + return withDimensionSurfaceSupport(placement, withImportedMode(placement, object, PlacementChanges.NONE)); + } + + /** The changes to make to {@code placement} to place {@code object} in a cave with the cave profile {@code caveProfile}. */ + PlacementChanges forCave(PlacementSource placement, PlaceableObject object, CaveProfile caveProfile) { + PlacementChanges changes = forSurface(placement, object); + ObjectPlaceMode mode = changes.mode() != null ? changes.mode() : placement.mode(); + if (mode != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { + return changes; + } + ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null); + if (profileMode == null) { + return changes; + } + String key = object.key(); + List place = key == null || key.isBlank() ? List.of() : List.of(key); + return changes.withPlace(place).withMode(profileMode); + } + + /** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */ + private static PlacementChanges withImportedMode(PlacementSource placement, PlaceableObject object, PlacementChanges changes) { + String key = object.key(); + if (key == null || key.isBlank() || !isImported(key)) { + return changes; + } + ObjectPlaceMode mode = placement.mode(); + if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT) || mode == ObjectPlaceMode.FAST_MIN_STILT) { + return changes; + } + return changes.withPlace(List.of(key)).withMode(ObjectPlaceMode.FAST_MIN_STILT); + } + + private static boolean isImported(String key) { + return key.toLowerCase(Locale.ROOT).contains(IMPORTS_FOLDER); + } + + /** The dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ + private PlacementChanges withDimensionSurfaceSupport(PlacementSource placement, PlacementChanges changes) { + boolean require = placement.requireSurfaceSupport() && dimensionRequiresSurfaceSupport; + int buffer = Math.max(placement.surfaceSupportBuffer(), dimensionSurfaceSupportBuffer); + if (require == placement.requireSurfaceSupport() && buffer == placement.surfaceSupportBuffer()) { + return changes; + } + return changes.withSurfaceSupport(require, buffer); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index b24ba27e0..4dbc0a9ad 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -29,6 +29,7 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; +import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.prefab.IrisObject; @@ -593,7 +594,7 @@ public class FloatingObjectPlacing { size = IrisObject.sampleSize(file); sizeCache.put(objectKey, size); } - int reach = ObjectPlacing.calculatePlacementReach(size, placement); + int reach = calculatePlacementReach(size, placement); if (reach > 128 && warnedLargeObjects.add(objectKey)) { log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); } @@ -605,4 +606,53 @@ public class FloatingObjectPlacing { } return radius; } + + static int calculatePlacementReach(IrisBlockVector size, IrisObjectPlacement placement) { + if (size == null) { + return 0; + } + if (placement == null) { + return Math.max(Math.abs(size.getBlockX()), Math.abs(size.getBlockZ())); + } + + double scale = placement.getScale() != null ? Math.max(1D, placement.getScale().getMaxScale()) : 1D; + int width = scaledDimension(size.getBlockX(), scale); + int height = scaledDimension(size.getBlockY(), scale); + int depth = scaledDimension(size.getBlockZ(), scale); + IrisObjectRotation rotation = placement.getRotation(); + boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().enabled(); + boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().enabled(); + int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); + int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); + int warp = placement.getWarp() != null && !placement.getWarp().isFlat() + ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) + : 0; + int vacuum = placement.getMode().placeMode().bendsTerrain() + ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode().placeMode().vacuum(), placement.getVacuumSettings()) + : 0; + long reach = (long) footprint + translation + warp + vacuum; + return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + } + + private static int scaledDimension(int dimension, double scale) { + int absoluteDimension = Math.abs(dimension); + if (scale <= 1D) { + return absoluteDimension; + } + return (int) Math.ceil((absoluteDimension * scale) + (scale * 2D)); + } + + private static int calculateTranslationReach(IrisObjectTranslate translate, IrisObjectRotation rotation, boolean rotateVertically) { + if (translate == null || !translate.canTranslate()) { + return 0; + } + double x = translate.getX(); + double y = translate.getY(); + double z = translate.getZ(); + if (rotateVertically) { + return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); + } + boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().enabled(); + return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(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 index 4dd1c86ba..d2a958e68 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java @@ -25,7 +25,7 @@ import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.spi.PlatformBlockState; import com.volmit.ModuleLog; -final class GoldenDebugObjectPlacer implements IObjectPlacer { +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; @@ -33,7 +33,7 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { private final String tag; private final ModuleLog log; - GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) { + public GoldenDebugObjectPlacer(IObjectPlacer delegate, String tag, ModuleLog log) { this.delegate = delegate; this.tag = tag; this.log = log; @@ -70,7 +70,7 @@ final class GoldenDebugObjectPlacer implements IObjectPlacer { } } - static boolean isGoldenDebugChunk(int x, int z) { + 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]; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index 98b448b57..144077e11 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -18,14 +18,14 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import com.volmit.FeatureAttachment.Target; import com.volmit.service.ObjectsAt; import com.volmit.world.PackWorld; + import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -37,38 +37,28 @@ import java.util.Set; public final class ObjectLocating implements ObjectsAt { @Override public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return ObjectModule.placing(engine(world), world.log()).guess(chunkX, chunkZ); + return ObjectPlacing.of(world).guess(chunkX, chunkZ); } @Override public PlacedBy placedBy(PackWorld world, String objectKey) { - Engine engine = engine(world); Set biomes = new LinkedHashSet<>(); - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - if (biome != null && placesObject(ObjectPlacements.surface(biome), objectKey)) { - biomes.add(biome.getLoadKey()); - } - } - Set regions = new LinkedHashSet<>(); - for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region != null && placesObject(ObjectPlacements.surface(region), objectKey)) { - regions.add(region.getLoadKey()); + for (Declaration declaration : ObjectHost.of(world).declarations(ObjectSettings.class)) { + if (!placesObject(declaration.settings().objects(), objectKey)) { + continue; } + (declaration.level() == Target.BIOME ? biomes : regions).add(declaration.key()); } return new PlacedBy(biomes, regions); } - private static boolean placesObject(List placements, String objectKey) { - for (IrisObjectPlacement placement : placements) { - if (placement != null && placement.getPlace().contains(objectKey)) { + private static boolean placesObject(List placements, String objectKey) { + for (ObjectPlacement placement : placements) { + if (placement != null && placement.carvingSupport().supportsSurface() && placement.place().contains(objectKey)) { return true; } } return false; } - - private static Engine engine(PackWorld world) { - return IrisPackWorld.of(world).engine(); - } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index de1aa17d6..3e90a8e2e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; @@ -26,10 +27,6 @@ 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.modules.IrisMantleChunk; -import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.framework.Engine; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -82,20 +79,14 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { @Override public void warmUp(PackWorld world) { - new ObjectWarmUp(IrisPackWorld.of(world).engine()).warm(); + new ObjectWarmUp(world).warm(); } private static void place(MantleStageContext context) { - IrisMantleChunk chunk = IrisMantleChunk.current(); - placing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + ObjectPlacing.of(context.world()).place(context); } private int reach(PackSettings settings) { - return placing(IrisPackSettings.of(settings).engine(), log).reach(); - } - - /** The engine runtime's object placing, which the module's {@link ObjectsAt} also asks; {@code log} is the module's. */ - public static ObjectPlacing placing(Engine engine, ModuleLog log) { - return engine.getGeneration().state(ObjectPlacing.class, generating -> new ObjectPlacing(generating, log)); + return new PlacementReach(ObjectHost.of(settings), log).ofPack(settings); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 92ae78dc8..e07447045 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -18,1633 +18,87 @@ package art.arcane.iris.engine.mantle.components; - -import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.prepare.AxisRotationClamp; -import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.placement.IrisObjectVacuum; -import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.object.placement.DecayControlPlacer; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -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.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; -import art.arcane.iris.engine.object.world.region.IrisRegion; -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.project.context.ChunkContext; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterStructurePOI; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.iris.util.project.noise.NoiseType; +import com.volmit.FeatureAttachment.Target; import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; -import java.io.IOException; -import java.util.Locale; -import java.util.Map; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; /** - * Places the objects of the dimension's regions and biomes into the mantle for - * {@link ObjectModule}: surface, cave and upper-dimension objects, and procedural objects, one chunk at a - * time after the caves they anchor in are planned. One per engine runtime. Its reach is the largest - * placement reach of any object the dimension can place. + * Places the objects the dimension's regions and biomes declare, one chunk at a time, into the mantle of a world: the worker + * of {@link ObjectModule}, one per world. It also works out which objects a chunk would get, without placing them, and how far + * the pack's objects reach. */ -public class ObjectPlacing { - private static final CaveProfile DEFAULT_CAVE_PROFILE = new CaveProfile(); - private static final long CAVE_REJECT_LOG_THROTTLE_MS = 5000L; - private static final int BEDROCK_CLEARANCE = 6; - private static final byte LIQUID_FORCED_AIR = 3; - private static final Map CAVE_REJECT_LOG_STATE = new ConcurrentHashMap<>(); - private static final Set MISSING_LOAD_KEY_WARNED = ConcurrentHashMap.newKeySet(); +public final class ObjectPlacing { + private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; + private static final int CHUNK_SHIFT = 4; + private static final double CHANCE_JITTER = 0.005; - private final Engine engine; + private final ObjectHost host; private final ModuleLog log; - public ObjectPlacing(Engine engine, ModuleLog log) { - this.engine = engine; + private ObjectPlacing(ObjectHost host, ModuleLog log) { + this.host = host; this.log = log; } - private String placementMarker(IrisObject object, int id, String context) { - String key = object == null ? null : object.getLoadKey(); - if (key == null || key.isEmpty() || key.equals("null")) { - String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); - if (MISSING_LOAD_KEY_WARNED.add(fingerprint)) { - java.io.File file = object == null ? null : object.getLoadFile(); - log.warn("Skipping placement marker write: IrisObject has no loadKey (context=" + context - + ", file=" + (file == null ? "" : file.getPath()) + "). " - + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); - } - return null; - } - return key + "@" + id; + /** The object placing of {@code world}. */ + public static ObjectPlacing of(PackWorld world) { + return world.state(ObjectPlacing.class, generating -> new ObjectPlacing(ObjectHost.of(generating), generating.log())); } - private static boolean isTreePlacement(IrisObject object, IrisObjectPlacement placement) { - String key = object == null ? null : object.getLoadKey(); - return (key != null && key.startsWith("trees/")) - || (placement != null && placement.getTrees() != null && placement.getTrees().isNotEmpty()); + /** Places what originates in the chunk {@code context} generates. */ + void place(MantleStageContext context) { + new ChunkObjectPlacing(host, log, context).place(); } - private static void writeTreeMaterial(IObjectPlacer placer, int x, int y, int z, PlatformBlockState data) { - placer.setData(x, y, z, TreeBlockMaterial.of(data)); - } - - /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ - public void place(MantleWriter writer, int x, int z, ChunkContext context) { - IrisComplex complex = context.getComplex(); - boolean traceRegen = isRegenTraceThread(); - RNG rng = applyNoise(x, z, CacheKey.key(x, z) + engine.getSeedManager().getMantle()); - int xxx = 8 + (x << 4); - int zzz = 8 + (z << 4); - IrisRegion region = complex.getRegionStream().get(xxx, zzz); - IrisBiome surfaceBiome = complex.getTrueBiomeStream().get(xxx, zzz); - int surfaceY = engine.getHeight(xxx, zzz, true); - IrisBiome caveBiome = resolveCaveObjectBiome(xxx, zzz, surfaceY, surfaceBiome); - if (IrisSettings.get().getGeneral().isDebug() && (x & 31) == 0 && (z & 31) == 0) { - int carvedBlocks = 0; - int minY = 1; - int maxY = Math.min(engine.getHeight() - 1, surfaceY - 14); - for (int sy = minY; sy < maxY; sy++) { - if (writer.isCarved(8 + (x << 4), sy, 8 + (z << 4))) { - carvedBlocks++; - } - } - log.debug("Cave object diag: chunk=" + x + "," + z - + " surfaceBiome=" + surfaceBiome.getLoadKey() - + " caveBiome=" + caveBiome.getLoadKey() - + " surfaceY=" + surfaceY - + " maxAnchorY=" + maxY - + " carvedAtCenter=" + carvedBlocks - + " biomeCarvingObjects=" + ObjectPlacements.carving(caveBiome).size() - + " regionCarvingObjects=" + ObjectPlacements.carving(region).size() - + " sameBiome=" + (caveBiome == surfaceBiome || java.util.Objects.equals(caveBiome.getLoadKey(), surfaceBiome.getLoadKey()))); - } - if (traceRegen) { - log.debug("Regen object layer start: chunk=" + x + "," + z - + " surfaceBiome=" + surfaceBiome.getLoadKey() - + " caveBiome=" + caveBiome.getLoadKey() - + " region=" + region.getLoadKey() - + " biomeSurfacePlacers=" + ObjectPlacements.surface(surfaceBiome).size() - + " biomeCavePlacers=" + ObjectPlacements.carving(caveBiome).size() - + " regionSurfacePlacers=" + ObjectPlacements.surface(region).size() - + " regionCavePlacers=" + ObjectPlacements.carving(region).size()); - } - ObjectPlacementSummary summary = placeObjects(writer, rng, x, z, surfaceBiome, caveBiome, region, complex, traceRegen); - placeProceduralObjects(writer, rng, x, z, surfaceBiome, caveBiome, region); - UpperDimensionContext upperCtx = engine.getUpperContext(); - IrisDimension dimension = engine.getDimension(); - if (upperCtx != null && ObjectPlacements.upperObjects(dimension)) { - placeUpperObjects(writer, rng, x, z, xxx, zzz, surfaceY, upperCtx, dimension, complex, traceRegen); - } - if (traceRegen) { - log.debug("Regen object layer done: chunk=" + x + "," + z - + " biomeSurfacePlacersChecked=" + summary.biomeSurfacePlacersChecked() - + " biomeSurfacePlacersTriggered=" + summary.biomeSurfacePlacersTriggered() - + " biomeCavePlacersChecked=" + summary.biomeCavePlacersChecked() - + " biomeCavePlacersTriggered=" + summary.biomeCavePlacersTriggered() - + " regionSurfacePlacersChecked=" + summary.regionSurfacePlacersChecked() - + " regionSurfacePlacersTriggered=" + summary.regionSurfacePlacersTriggered() - + " regionCavePlacersChecked=" + summary.regionCavePlacersChecked() - + " regionCavePlacersTriggered=" + summary.regionCavePlacersTriggered() - + " objectAttempts=" + summary.objectAttempts() - + " objectPlaced=" + summary.objectPlaced() - + " objectRejected=" + summary.objectRejected() - + " objectNull=" + summary.objectNull() - + " objectErrors=" + summary.objectErrors()); - } - } - - private RNG applyNoise(int x, int z, long seed) { - CNG noise = CNG.signatureFast(new RNG(seed), NoiseType.WHITE, NoiseType.GLOB); - return new RNG((long) (seed * noise.noise(x, z))); - } - - private IrisBiome resolveCaveObjectBiome(int x, int z, int surfaceY, IrisBiome surfaceBiome) { - int legacySampleY = Math.max(1, surfaceY - 48); - IrisBiome legacyCaveBiome = engine.getCaveBiome(x, legacySampleY, z); - if (legacyCaveBiome == null) { - legacyCaveBiome = surfaceBiome; - } - - int[] sampleDepths = new int[]{48, 80, 112}; - IrisBiome ladderChoice = null; - for (int sampleDepth : sampleDepths) { - int sampleY = Math.max(1, surfaceY - sampleDepth); - IrisBiome sampled = engine.getCaveBiome(x, sampleY, z); - boolean sameSurface = sampled == surfaceBiome; - if (!sameSurface && sampled != null && surfaceBiome != null) { - String sampledKey = sampled.getLoadKey(); - String surfaceKey = surfaceBiome.getLoadKey(); - sameSurface = sampledKey != null && sampledKey.equals(surfaceKey); - } - - if (sampled == null || sameSurface) { - continue; - } - - if (!ObjectPlacements.carving(sampled).isEmpty()) { - ladderChoice = sampled; - } - } - - if (ladderChoice != null) { - return ladderChoice; - } - - return legacyCaveBiome; - } - - @ChunkCoordinates - private ObjectPlacementSummary placeObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region, IrisComplex complex, boolean traceRegen) { - int biomeSurfaceChecked = 0; - int biomeSurfaceTriggered = 0; - int biomeCaveChecked = 0; - int biomeCaveTriggered = 0; - int regionSurfaceChecked = 0; - int regionSurfaceTriggered = 0; - int regionCaveChecked = 0; - int regionCaveTriggered = 0; - int attempts = 0; - int placed = 0; - int rejected = 0; - int nullObjects = 0; - int errors = 0; - CaveProfile biomeCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); - CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), CaveProfiles.declaredBy(caveBiome)); - CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); - - for (IrisObjectPlacement i : ObjectPlacements.surface(surfaceBiome)) { - biomeSurfaceChecked++; - boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=biome-surface" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - biomeSurfaceTriggered++; - try { - ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "biome-surface"); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place objects in the following biome: " + surfaceBiome.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); + /** The keys of the objects the chunk would get, as far as the chunk's surface objects go. */ + public Set guess(int chunkX, int chunkZ) { + RNG rng = host.chunkRandom(chunkX, chunkZ); + int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + List> entries = host.columnSettings().at(ObjectSettings.class, centerX, centerZ); + Set keys = new HashSet<>(); + for (Target level : new Target[]{Target.BIOME, Target.REGION}) { + for (Entry entry : entries) { + if (entry.level() == level) { + guessFrom(entry.value(), rng, chunkX, chunkZ, keys); } } } - - for (IrisObjectPlacement i : ObjectPlacements.carving(caveBiome)) { - if (!i.getCarvingSupport().supportsCarving()) { - continue; - } - biomeCaveChecked++; - boolean chance = rng.chance(i.getChance()); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=biome-cave" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - biomeCaveTriggered++; - try { - ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, biomeCaveProfile, complex, traceRegen, x, z, "biome-cave", caveBiome.getLoadKey(), caveAnchorCache); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place cave objects in the following biome: " + caveBiome.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); - } - } - } - - for (IrisObjectPlacement i : ObjectPlacements.surface(region)) { - regionSurfaceChecked++; - boolean chance = rng.chance(i.getChance() + rng.d(-0.005, 0.005)); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=region-surface" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - regionSurfaceTriggered++; - try { - ObjectPlacementResult result = placeObject(writer, rng, x << 4, z << 4, i, complex, traceRegen, x, z, "region-surface"); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place objects in the following region: " + region.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); - } - } - } - - for (IrisObjectPlacement i : ObjectPlacements.carving(region)) { - if (!i.getCarvingSupport().supportsCarving()) { - continue; - } - regionCaveChecked++; - boolean chance = rng.chance(i.getChance()); - if (traceRegen) { - log.debug("Regen object placer chance: chunk=" + x + "," + z - + " scope=region-cave" - + " chanceResult=" + chance - + " chanceBase=" + i.getChance() - + " densityMid=" + i.getDensity() - + " objects=" + i.getPlace().size()); - } - if (chance) { - regionCaveTriggered++; - try { - ObjectPlacementResult result = placeCaveObject(writer, rng, x, z, i, regionCaveProfile, complex, traceRegen, x, z, "region-cave", null, caveAnchorCache); - attempts += result.attempts(); - placed += result.placed(); - rejected += result.rejected(); - nullObjects += result.nullObjects(); - errors += result.errors(); - } catch (Throwable e) { - errors++; - log.error("Failed to place cave objects in the following region: " + region.getName(), e); - log.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ").", null); - log.error("Are these objects missing?", null); - } - } - } - - return new ObjectPlacementSummary( - biomeSurfaceChecked, - biomeSurfaceTriggered, - biomeCaveChecked, - biomeCaveTriggered, - regionSurfaceChecked, - regionSurfaceTriggered, - regionCaveChecked, - regionCaveTriggered, - attempts, - placed, - rejected, - nullObjects, - errors - ); + return keys; } - @ChunkCoordinates - private void placeProceduralObjects(MantleWriter writer, RNG rng, int x, int z, IrisBiome surfaceBiome, IrisBiome caveBiome, IrisRegion region) { - CaveProfile surfaceCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(surfaceBiome), CaveProfiles.declaredBy(region)); - CaveProfile regionCaveProfile = resolveCaveProfile(CaveProfiles.declaredBy(region), caveBiome == null ? null : CaveProfiles.declaredBy(caveBiome)); - placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(surfaceBiome), surfaceBiome.getName(), surfaceCaveProfile, surfaceBiome.getLoadKey()); - placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(region), region.getName(), regionCaveProfile, null); - if (caveBiome != null && caveBiome != surfaceBiome) { - CaveProfile caveProfile = resolveCaveProfile(CaveProfiles.declaredBy(caveBiome), CaveProfiles.declaredBy(region)); - placeProceduralFrom(writer, rng, x, z, ObjectPlacements.procedural(caveBiome), caveBiome.getName(), caveProfile, caveBiome.getLoadKey()); - } - } - - @ChunkCoordinates - private void placeProceduralFrom( - MantleWriter writer, - RNG rng, - int x, - int z, - ResolvedProceduralObjects proceduralObjects, - String scope, - CaveProfile caveProfile, - String expectedCaveBiomeKey - ) { - if (proceduralObjects == null || proceduralObjects.isEmpty()) { - return; - } - - int blockX = x << 4; - int blockZ = z << 4; - boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(x, z); - CaveAnchorCache caveAnchorCache = new CaveAnchorCache(); - for (IrisProceduralPlacement p : proceduralObjects.getAllPlacements()) { - boolean treePlacement = p instanceof ResolvedTree; - boolean chancePassed = passesProceduralChance(rng, p.getChance()); - if (golden) { - log.debug("Goldendebug procedural chance: chunk=" + x + "," + z - + " scope=" + scope - + " placement=" + p.getName() - + " passed=" + chancePassed); - } - if (!chancePassed) { - continue; - } - - IrisObjectPlacement placement = p.asPlacement(); - boolean carving = placement.getCarvingSupport() == CarvingMode.CARVING_ONLY; - CaveAnchorMode anchorMode = resolveAnchorMode(placement, caveProfile); - if (placement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { - anchorMode = CaveAnchorMode.CEILING; - } - int anchorScanStep = resolveAnchorScanStep(caveProfile); - int minDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); - int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); - IObjectPlacer basePlacer = p.isPlausible() ? new DecayControlPlacer(writer) : writer; - IObjectPlacer placer = golden ? new GoldenDebugObjectPlacer(basePlacer, scope + "/" + p.getName(), log) : basePlacer; - int density = Math.max(1, p.getDensity()); - for (int i = 0; i < density; i++) { - IrisObject variant = p.getVariantObject(engine.getData(), rng); - if (variant == null) { - if (golden) { - log.debug("Goldendebug procedural pick: chunk=" + x + "," + z - + " placement=" + p.getName() - + " densityIndex=" + i - + " variant=null"); - } - continue; - } - CavePlacementAnchor caveAnchor = null; - if (carving) { - caveAnchor = findCavePlacementAnchor( - writer, - rng, - blockX, - blockZ, - anchorMode, - anchorScanStep, - minDepthBelowSurface, - anchorSearchAttempts, - expectedCaveBiomeKey, - placement.isUnderwater(), - caveAnchorCache - ); - } - if (carving && caveAnchor == null) { - if (golden) { - log.debug("Goldendebug procedural cave anchor rejected: chunk=" + x + "," + z - + " placement=" + p.getName() - + " minDepthBelowSurface=" + minDepthBelowSurface); - } - continue; - } - int xx = caveAnchor == null ? rng.i(blockX, blockX + 16) : caveAnchor.x(); - int zz = caveAnchor == null ? rng.i(blockZ, blockZ + 16) : caveAnchor.z(); - int id = rng.i(0, Integer.MAX_VALUE); - if (golden) { - KList pool = p.getVariantObjects(engine.getData()); - log.debug("Goldendebug procedural pick: chunk=" + x + "," + z - + " placement=" + p.getName() - + " densityIndex=" + i - + " variant=" + variant.getLoadKey() - + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() - + " xx=" + xx - + " zz=" + zz - + " mode=" + placement.getMode() - + " carving=" + carving); - } - try { - int placeResult = -1; - CaveObjectPlacementTransaction.CommitResult commitResult = CaveObjectPlacementTransaction.CommitResult.EMPTY; - if (carving) { - int caveFloorY = caveAnchor.y(); - if (golden) { - log.debug("Goldendebug procedural caveFloor: chunk=" + x + "," + z - + " placement=" + p.getName() - + " xx=" + xx - + " zz=" + zz - + " caveFloorY=" + caveFloorY); - } - IrisObjectPlacement effectivePlacement = resolveCavePlacement(placement, variant, caveProfile); - ContainedPlacementResult contained = placeContainedCaveObject( - placer, - variant, - xx, - caveFloorY, - zz, - effectivePlacement, - minDepthBelowSurface, - id, - "procedural", - treePlacement, - rng - ); - placeResult = contained.resultY(); - commitResult = contained.commitResult(); - } else { - String marker = placementMarker(variant, id, "procedural"); - placeResult = variant.place(xx, -1, zz, placer, placement, rng, (b, data) -> { - if (marker != null) { - placer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(placer, b.getX(), b.getY(), b.getZ(), data); - } - }, null, engine.getData()); - } - if (golden) { - log.debug("Goldendebug procedural result: chunk=" + x + "," + z - + " placement=" + p.getName() - + " variant=" + variant.getLoadKey() - + " xx=" + xx - + " zz=" + zz - + " resultY=" + placeResult - + " commit=" + commitResult); - } - } catch (Throwable e) { - log.error("Failed to place procedural object '" + p.getName() + "' in " + scope, e); - } + private void guessFrom(ObjectSettings settings, RNG rng, int chunkX, int chunkZ, Set keys) { + for (ObjectPlacement placement : settings.objects()) { + if (placement.carvingSupport().supportsSurface() && rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + keys.addAll(guessPlacedKeys(rng, chunkX, chunkZ, placement)); } } } - static boolean passesProceduralChance(RNG rng, double chance) { - if (chance <= 0.0) { - return false; + private Set guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) { + Set keys = new HashSet<>(); + for (int i = 0; i < host.density(placement, rng, x, z); i++) { + Optional picked = host.pickScaled(placement, rng); + picked.ifPresent(object -> keys.add(object.key())); } - if (chance >= 1.0) { - return true; - } - return rng.chance(Math.max(0.0, Math.min(1.0, chance + rng.d(-0.005, 0.005)))); - } - - private CavePlacementAnchor findCavePlacementAnchor( - MantleWriter writer, - RNG rng, - int minX, - int minZ, - CaveAnchorMode anchorMode, - int anchorScanStep, - int minDepthBelowSurface, - int searchAttempts, - String expectedCaveBiomeKey, - boolean underwater, - CaveAnchorCache anchorCache - ) { - for (int search = 0; search < searchAttempts; search++) { - int candidateX = rng.i(minX, minX + 16); - int candidateZ = rng.i(minZ, minZ + 16); - int candidateY = findCaveAnchorY( - writer, - rng, - candidateX, - candidateZ, - anchorMode, - anchorScanStep, - minDepthBelowSurface, - anchorCache - ); - if (candidateY < 0 - || caveAnchorBiomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiomeKey) - || !acceptsCaveAnchorFluid( - underwater, - writer.getDataIfPresent(candidateX, candidateY, candidateZ, MatterCavern.class), - candidateY, - engine.getDimension().getCaveLavaHeight())) { - continue; - } - return new CavePlacementAnchor(candidateX, candidateY, candidateZ); - } - return null; - } - - static boolean acceptsCaveAnchorFluid(boolean underwater, MatterCavern cavern, int y, int lavaHeight) { - if (cavern == null || !cavern.isCavern()) { - return false; - } - if (underwater || cavern.getLiquid() == LIQUID_FORCED_AIR) { - return true; - } - return cavern.isAir() && y > lavaHeight; - } - - private ContainedPlacementResult placeContainedCaveObject( - IObjectPlacer placer, - IrisObject object, - int x, - int anchorY, - int z, - IrisObjectPlacement placement, - int minDepthBelowSurface, - int id, - String markerContext, - boolean treePlacement, - RNG rng - ) { - CaveObjectPlacementTransaction transaction = new CaveObjectPlacementTransaction(placer, anchorY, minDepthBelowSurface); - int placeY = anchorY; - if (placement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { - placeY = Math.max(1, transaction.getCaveCeiling(x, z) - 1 - Math.floorDiv(object.getH(), 2)); - } - String marker = placementMarker(object, id, markerContext); - int result = object.place(x, placeY, z, transaction, placement, rng, (block, data) -> { - if (marker != null) { - transaction.setData(block.getX(), block.getY(), block.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(transaction, block.getX(), block.getY(), block.getZ(), data); - } - if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { - transaction.setData(block.getX(), block.getY(), block.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, engine.getData()); - if (result < 0) { - transaction.discard(); - return new ContainedPlacementResult(result, CaveObjectPlacementTransaction.CommitResult.EMPTY); - } - return new ContainedPlacementResult(result, transaction.commit()); - } - - @BlockCoordinates - private ObjectPlacementResult placeObject( - MantleWriter writer, - RNG rng, - int x, - int z, - IrisObjectPlacement objectPlacement, - IrisComplex complex, - boolean traceRegen, - int chunkX, - int chunkZ, - String scope - ) { - int attempts = 0; - int placed = 0; - int rejected = 0; - int nullObjects = 0; - int errors = 0; - int density = objectPlacement.getDensity(rng, x, z, engine.getData()); - boolean golden = GoldenDebugObjectPlacer.isGoldenDebugChunk(chunkX, chunkZ); - - for (int i = 0; i < density; i++) { - attempts++; - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); - if (v == null) { - nullObjects++; - if (traceRegen) { - log.debug("Regen object placement null object: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " densityIndex=" + i - + " density=" + density - + " placementKeys=" + objectPlacement.getPlace().toString(",")); - } - continue; - } - int xx = rng.i(x, x + 16); - int zz = rng.i(z, z + 16); - IrisObjectPlacement effectivePlacement = resolveEffectivePlacement(objectPlacement, v); - boolean treePlacement = isTreePlacement(v, effectivePlacement); - int id = rng.i(0, Integer.MAX_VALUE); - IObjectPlacer placePlacer = golden ? new GoldenDebugObjectPlacer(writer, scope + "/" + v.getLoadKey(), log) : writer; - if (golden) { - log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " densityIndex=" + i - + " xx=" + xx - + " zz=" + zz - + " mode=" + effectivePlacement.getMode()); - } - try { - String marker = placementMarker(v, id, "surface"); - int result = v.place(xx, -1, zz, placePlacer, effectivePlacement, rng, (b, data) -> { - if (marker != null) { - writer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); - } - if (effectivePlacement.isDolphinTarget() && effectivePlacement.isUnderwater() && B.isStorageChest(data)) { - writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, engine.getData()); - - if (result >= 0) { - placed++; - } else { - rejected++; - } - - if (golden) { - log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " resultY=" + result - + " fallback=surface"); - } - - if (traceRegen) { - log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " resultY=" + result - + " px=" + xx - + " pz=" + zz - + " fallback=surface" - + " densityIndex=" + i - + " density=" + density); - } - } catch (Throwable e) { - errors++; - log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " densityIndex=" + i - + " density=" + density - + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage(), e); - } - } - - return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors); - } - - @ChunkCoordinates - private boolean caveAnchorBiomeConflicts(int x, int y, int z, String expectedCaveBiomeKey) { - if (expectedCaveBiomeKey == null) { - return false; - } - IrisBiome at = engine.getCaveBiome(x, y, z); - IrisBiome surface = engine.getSurfaceBiome(x, z); - return caveAnchorBiomeConflicts(at, surface, expectedCaveBiomeKey); - } - - static boolean caveAnchorBiomeConflicts(IrisBiome at, IrisBiome surface, String expectedCaveBiomeKey) { - if (expectedCaveBiomeKey == null || at == null) { - return false; - } - String atKey = at.getLoadKey(); - if (atKey == null || atKey.equals(expectedCaveBiomeKey)) { - return false; - } - if (surface != null && atKey.equals(surface.getLoadKey())) { - return false; - } - return true; - } - - private ObjectPlacementResult placeCaveObject( - MantleWriter writer, - RNG rng, - int chunkX, - int chunkZ, - IrisObjectPlacement objectPlacement, - CaveProfile caveProfile, - IrisComplex complex, - boolean traceRegen, - int metricChunkX, - int metricChunkZ, - String scope, - String expectedCaveBiomeKey, - CaveAnchorCache anchorCache - ) { - int attempts = 0; - int placed = 0; - int rejected = 0; - int nullObjects = 0; - int errors = 0; - int minX = chunkX << 4; - int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); - CaveAnchorMode anchorMode = resolveAnchorMode(objectPlacement, caveProfile); - if (objectPlacement.getMode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { - anchorMode = CaveAnchorMode.CEILING; - } - int anchorScanStep = resolveAnchorScanStep(caveProfile); - int objectMinDepthBelowSurface = resolveObjectMinDepthBelowSurface(caveProfile); - int anchorSearchAttempts = resolveAnchorSearchAttempts(caveProfile); - - for (int i = 0; i < density; i++) { - attempts++; - IrisObject object = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); - if (object == null) { - nullObjects++; - if (traceRegen) { - log.debug("Regen cave object placement null object: chunk=" + metricChunkX + "," + metricChunkZ - + " scope=" + scope - + " densityIndex=" + i - + " density=" + density - + " placementKeys=" + objectPlacement.getPlace().toString(",")); - } - logCaveReject( - scope, - "NULL_OBJECT", - metricChunkX, - metricChunkZ, - objectPlacement, - null, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - null, - null - ); - continue; - } - - CavePlacementAnchor anchor = findCavePlacementAnchor( - writer, - rng, - minX, - minZ, - anchorMode, - anchorScanStep, - objectMinDepthBelowSurface, - anchorSearchAttempts, - expectedCaveBiomeKey, - objectPlacement.isUnderwater(), - anchorCache - ); - - if (anchor == null) { - rejected++; - logCaveReject( - scope, - "NO_ANCHOR", - metricChunkX, - metricChunkZ, - objectPlacement, - object, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - null, - null - ); - continue; - } - - int x = anchor.x(); - int y = anchor.y(); - int z = anchor.z(); - - int id = rng.i(0, Integer.MAX_VALUE); - IrisObjectPlacement effectivePlacement = resolveCavePlacement(objectPlacement, object, caveProfile); - - try { - ContainedPlacementResult contained = placeContainedCaveObject( - writer, - object, - x, - y, - z, - effectivePlacement, - objectMinDepthBelowSurface, - id, - "cave", - isTreePlacement(object, effectivePlacement), - rng - ); - int result = contained.resultY(); - boolean wroteBlocks = contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.COMMITTED; - if (wroteBlocks) { - placed++; - } else { - rejected++; - String rejectReason; - if (result < 0) { - rejectReason = "PLACE_NEGATIVE"; - } else if (contained.commitResult() == CaveObjectPlacementTransaction.CommitResult.REJECTED_BOUNDS) { - rejectReason = "CONTAINMENT"; - } else { - rejectReason = "NO_WRITES"; - } - logCaveReject( - scope, - rejectReason, - metricChunkX, - metricChunkZ, - objectPlacement, - object, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - y, - null - ); - } - - if (traceRegen) { - log.debug("Regen cave object placement result: chunk=" + metricChunkX + "," + metricChunkZ - + " scope=" + scope - + " object=" + object.getLoadKey() - + " resultY=" + result - + " anchorY=" + y - + " px=" + x - + " pz=" + z - + " wroteBlocks=" + wroteBlocks - + " densityIndex=" + i - + " density=" + density); - } - } catch (Throwable e) { - errors++; - log.error("Regen cave object placement exception: chunk=" + metricChunkX + "," + metricChunkZ - + " scope=" + scope - + " object=" + object.getLoadKey() - + " densityIndex=" + i - + " density=" + density - + " error=" + e.getClass().getSimpleName() + ":" + e.getMessage(), e); - logCaveReject( - scope, - "EXCEPTION", - metricChunkX, - metricChunkZ, - objectPlacement, - object, - i, - density, - anchorMode, - anchorSearchAttempts, - anchorScanStep, - objectMinDepthBelowSurface, - y, - e - ); - } - } - - return new ObjectPlacementResult(attempts, placed, rejected, nullObjects, errors); - } - - @ChunkCoordinates - private void placeUpperObjects( - MantleWriter writer, - RNG rng, - int chunkX, - int chunkZ, - int centerX, - int centerZ, - int lowerSurfaceCenterY, - UpperDimensionContext upperCtx, - IrisDimension dimension, - IrisComplex complex, - boolean traceRegen - ) { - IrisBiome upperBiome = upperCtx.getUpperBiome(centerX, centerZ); - IrisRegion upperRegion = upperCtx.getUpperRegion(centerX, centerZ); - if (upperBiome == null && upperRegion == null) { - return; - } - - boolean forcePlace = ObjectPlacements.upperObjectsForced(dimension); - if (upperBiome != null) { - for (IrisObjectPlacement i : ObjectPlacements.surface(upperBiome)) { - if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - continue; - } - try { - placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-biome-surface"); - } catch (Throwable e) { - log.error("Failed to place upper-dimension objects in biome " + upperBiome.getName() - + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")", e); - } - } - } - - if (upperRegion != null) { - for (IrisObjectPlacement i : ObjectPlacements.surface(upperRegion)) { - if (!rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - continue; - } - try { - placeUpperObject(writer, rng, chunkX, chunkZ, i, upperCtx, dimension, complex, forcePlace, traceRegen, "upper-region-surface"); - } catch (Throwable e) { - log.error("Failed to place upper-dimension objects in region " + upperRegion.getName() - + ": " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")", e); - } - } - } - } - - @ChunkCoordinates - private void placeUpperObject( - MantleWriter writer, - RNG rng, - int chunkX, - int chunkZ, - IrisObjectPlacement objectPlacement, - UpperDimensionContext upperCtx, - IrisDimension dimension, - IrisComplex complex, - boolean forcePlace, - boolean traceRegen, - String scope - ) { - int chunkHeight = engine.getHeight(); - int upperGap = dimension.getUpperDimensionGap(); - int minX = chunkX << 4; - int minZ = chunkZ << 4; - int density = objectPlacement.getDensity(rng, minX, minZ, engine.getData()); - - for (int i = 0; i < density; i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(complex, rng), engine); - if (v == null) { - continue; - } - - int xx = rng.i(minX, minX + 16); - int zz = rng.i(minZ, minZ + 16); - int columnLowerSurfaceY = engine.getHeight(xx, zz, true); - int rawUpperSurface = upperCtx.getUpperSurfaceY(xx, zz); - int upperSurfaceY = Math.max(rawUpperSurface, columnLowerSurfaceY + upperGap); - if (upperSurfaceY >= chunkHeight - 2) { - continue; - } - - int halfH = Math.floorDiv(v.getH(), 2); - int anchorY = upperSurfaceY - 1 - halfH; - if (anchorY <= 1) { - continue; - } - - int id = rng.i(0, Integer.MAX_VALUE); - IrisObjectPlacement placement = objectPlacement.toPlacement(v.getLoadKey()); - placement.setMode(ObjectPlaceMode.CENTER_HEIGHT); - placement.setRotation(buildUpsideDownRotation()); - placement.setCarvingSupport(CarvingMode.ANYWHERE); - if (forcePlace) { - placement.setForcePlace(true); - } - boolean treePlacement = isTreePlacement(v, objectPlacement); - String marker = placementMarker(v, id, "upper"); - - int result = v.place(xx, anchorY, zz, writer, placement, rng, (b, data) -> { - if (marker != null) { - writer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - if (treePlacement && marker != null) { - writeTreeMaterial(writer, b.getX(), b.getY(), b.getZ(), data); - } - if (placement.isDolphinTarget() && placement.isUnderwater() && B.isStorageChest(data)) { - writer.setData(b.getX(), b.getY(), b.getZ(), MatterStructurePOI.BURIED_TREASURE); - } - }, null, engine.getData()); - - if (traceRegen) { - log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ - + " scope=" + scope - + " object=" + v.getLoadKey() - + " anchorY=" + anchorY - + " upperSurfaceY=" + upperSurfaceY - + " resultY=" + result - + " forcePlace=" + forcePlace); - } - } - } - - private IrisObjectRotation buildUpsideDownRotation() { - IrisObjectRotation rt = new IrisObjectRotation(); - rt.setEnabled(true); - rt.setXAxis(AxisRotationClamp.of(true, true, 180D, 180D, 90D)); - rt.setYAxis(AxisRotationClamp.of(true, false, 0D, 0D, 90D)); - rt.setZAxis(new AxisRotationClamp()); - return rt; - } - - private void logCaveReject( - String scope, - String reason, - int chunkX, - int chunkZ, - IrisObjectPlacement objectPlacement, - IrisObject object, - int densityIndex, - int density, - CaveAnchorMode anchorMode, - int anchorSearchAttempts, - int anchorScanStep, - int objectMinDepthBelowSurface, - Integer anchorY, - Throwable error - ) { - if (!IrisSettings.get().getGeneral().isDebug()) { - return; - } - - String placementKeys = objectPlacement == null ? "none" : objectPlacement.getPlace().toString(","); - String objectKey = object == null ? "null" : object.getLoadKey(); - String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; - CaveRejectLogState state = CAVE_REJECT_LOG_STATE.computeIfAbsent(throttleKey, (k) -> new CaveRejectLogState()); - long now = System.currentTimeMillis(); - long last = state.lastLogMs.get(); - if ((now - last) < CAVE_REJECT_LOG_THROTTLE_MS) { - state.suppressed.incrementAndGet(); - return; - } - - if (!state.lastLogMs.compareAndSet(last, now)) { - state.suppressed.incrementAndGet(); - return; - } - - int suppressed = state.suppressed.getAndSet(0); - String anchorYText = anchorY == null ? "none" : String.valueOf(anchorY); - String errorText = error == null ? "none" : error.getClass().getSimpleName() + ":" + String.valueOf(error.getMessage()); - log.debug("Cave object reject: scope=" + scope - + " reason=" + reason - + " chunk=" + chunkX + "," + chunkZ - + " object=" + objectKey - + " placements=" + placementKeys - + " densityIndex=" + densityIndex - + " density=" + density - + " anchorMode=" + anchorMode - + " anchorSearchAttempts=" + anchorSearchAttempts - + " anchorScanStep=" + anchorScanStep - + " minDepthBelowSurface=" + objectMinDepthBelowSurface - + " anchorY=" + anchorYText - + " forcePlace=" + (objectPlacement != null && objectPlacement.isForcePlace()) - + " carvingSupport=" + (objectPlacement == null ? "none" : objectPlacement.getCarvingSupport()) - + " bottom=" + (objectPlacement != null && objectPlacement.isBottom()) - + " suppressed=" + suppressed - + " error=" + errorText); - } - - private IrisObjectPlacement resolveEffectivePlacement(IrisObjectPlacement objectPlacement, IrisObject object) { - if (objectPlacement == null || object == null) { - return objectPlacement; - } - - return applyDimensionSurfaceSupport(resolveImportedPlacement(objectPlacement, object)); - } - - /** Dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ - private IrisObjectPlacement applyDimensionSurfaceSupport(IrisObjectPlacement placement) { - IrisDimension dimension = engine.getDimension(); - boolean require = placement.isRequireSurfaceSupport() && ObjectPlacements.requiresSurfaceSupport(dimension); - int buffer = Math.max(placement.getSurfaceSupportBuffer(), ObjectPlacements.surfaceSupportBuffer(dimension)); - if (require == placement.isRequireSurfaceSupport() && buffer == placement.getSurfaceSupportBuffer()) { - return placement; - } - - IrisObjectPlacement resolved = placement.toPlacement(placement.getPlace().toArray(new String[0])); - resolved.setRequireSurfaceSupport(require); - resolved.setSurfaceSupportBuffer(buffer); - return resolved; - } - - private IrisObjectPlacement resolveImportedPlacement(IrisObjectPlacement objectPlacement, IrisObject object) { - String loadKey = object.getLoadKey(); - if (loadKey == null || loadKey.isBlank()) { - return objectPlacement; - } - - String normalized = loadKey.toLowerCase(Locale.ROOT); - boolean imported = normalized.startsWith("imports/") - || normalized.contains("/imports/") - || normalized.contains("imports/"); - - if (!imported) { - return objectPlacement; - } - - ObjectPlaceMode mode = objectPlacement.getMode(); - if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { - return objectPlacement; - } - boolean needsModeChange = mode != ObjectPlaceMode.FAST_MIN_STILT; - if (!needsModeChange) { - return objectPlacement; - } - - IrisObjectPlacement effectivePlacement = objectPlacement.toPlacement(loadKey); - effectivePlacement.setMode(ObjectPlaceMode.FAST_MIN_STILT); - return effectivePlacement; - } - - private IrisObjectPlacement resolveCavePlacement(IrisObjectPlacement objectPlacement, IrisObject object, CaveProfile caveProfile) { - IrisObjectPlacement resolvedPlacement = resolveEffectivePlacement(objectPlacement, object); - if (resolvedPlacement.getMode() != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { - return resolvedPlacement; - } - - ObjectPlaceMode profileMode = caveProfile.defaultObjectPlaceMode().orElse(null); - if (profileMode == null) { - return resolvedPlacement; - } - - String loadKey = object.getLoadKey(); - if (loadKey == null || loadKey.isBlank()) { - resolvedPlacement = resolvedPlacement.toPlacement(); - } else { - resolvedPlacement = resolvedPlacement.toPlacement(loadKey); - } - resolvedPlacement.setMode(profileMode); - return resolvedPlacement; - } - - static int caveAnchorScanUpperBound(int worldHeight, int surfaceY, int minDepthBelowSurface) { - int maxAnchorY = CaveObjectPlacementTransaction.maxBuriedY(worldHeight, surfaceY, minDepthBelowSurface); - if (maxAnchorY <= 1) { - return 0; - } - return maxAnchorY + 1; - } - - private int findCaveAnchorY(MantleWriter writer, RNG rng, int x, int z, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, CaveAnchorCache anchorCache) { - KList anchors = anchorCache.get(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z); - if (anchors.isEmpty()) { - return -1; - } - - if (anchors.size() == 1) { - return anchors.get(0); - } - - return anchors.get(rng.i(anchors.size())); - } - - private KList scanCaveAnchorColumn(MantleWriter writer, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z, CaveAnchorCache anchorCache) { - int height = engine.getHeight(); - int step = Math.max(1, anchorScanStep); - int surfaceY = anchorCache.getSurfaceHeight(x, z); - int maxAnchorExclusive = caveAnchorScanUpperBound(height, surfaceY, objectMinDepthBelowSurface); - if (maxAnchorExclusive == 0) { - return new KList<>(); - } - - int carvedHeight = Math.min(height, maxAnchorExclusive + 3); - byte[] carvedColumn = anchorCache.getCarvedColumn(writer, x, z, carvedHeight); - return scanCaveAnchorRange(anchorMode, step, carvedHeight, BEDROCK_CLEARANCE, maxAnchorExclusive, carvedColumn); - } - - private KList scanCaveAnchorRange(CaveAnchorMode anchorMode, int step, int height, int minAnchorY, int maxAnchorY, byte[] carvedColumn) { - KList anchors = new KList<>(); - int startY = alignAnchorScanStart(minAnchorY, step); - for (int y = startY; y < maxAnchorY; y += step) { - if (!isCarved(carvedColumn, y)) { - continue; - } - - boolean solidBelow = hasSolidNeighbor(carvedColumn, y, height, -1); - boolean solidAbove = hasSolidNeighbor(carvedColumn, y, height, 1); - if (matchesCaveAnchor(anchorMode, solidBelow, solidAbove)) { - anchors.add(y); - } - } - return anchors; - } - - private int alignAnchorScanStart(int minAnchorY, int step) { - if (minAnchorY <= BEDROCK_CLEARANCE) { - return BEDROCK_CLEARANCE; - } - - int delta = minAnchorY - BEDROCK_CLEARANCE; - int steps = (delta + step - 1) / step; - return BEDROCK_CLEARANCE + (steps * step); - } - - private boolean isCarved(byte[] carvedColumn, int y) { - return y >= 0 && y < carvedColumn.length && carvedColumn[y] == 1; - } - - private boolean hasSolidNeighbor(byte[] carvedColumn, int y, int height, int direction) { - for (int d = 1; d <= 3; d++) { - int ny = y + (direction * d); - if (ny < 0 || ny >= height) { - return true; - } - if (!isCarved(carvedColumn, ny)) { - return true; - } - } - return false; - } - - private boolean matchesCaveAnchor(CaveAnchorMode anchorMode, boolean solidBelow, boolean solidAbove) { - return switch (anchorMode) { - case PROFILE_DEFAULT, FLOOR -> solidBelow; - case CEILING -> solidAbove; - case CENTER -> !solidBelow && !solidAbove; - case ANY -> true; - }; - } - - private CaveProfile resolveCaveProfile(CaveProfile preferred, CaveProfile secondary) { - CaveProfile dimensionProfile = CaveProfiles.declaredBy(engine.getDimension()); - if (preferred != null && preferred.enabled()) { - return preferred; - } - - if (secondary != null && secondary.enabled()) { - return secondary; - } - - if (dimensionProfile != null) { - return dimensionProfile; - } - - return DEFAULT_CAVE_PROFILE; - } - - private CaveAnchorMode resolveAnchorMode(IrisObjectPlacement objectPlacement, CaveProfile caveProfile) { - CaveAnchorMode placementMode = objectPlacement.getCaveAnchorMode(); - if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { - return placementMode; - } - - if (caveProfile == null) { - return CaveAnchorMode.FLOOR; - } - - CaveAnchorMode profileMode = caveProfile.defaultObjectAnchor(); - if (profileMode == null || profileMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { - return CaveAnchorMode.FLOOR; - } - - return profileMode; - } - - private int resolveAnchorScanStep(CaveProfile caveProfile) { - if (caveProfile == null) { - return 1; - } - - return Math.max(1, caveProfile.anchorScanStep()); - } - - private int resolveObjectMinDepthBelowSurface(CaveProfile caveProfile) { - if (caveProfile == null) { - return 6; - } - - return Math.max(0, caveProfile.objectMinDepthBelowSurface()); - } - - private int resolveAnchorSearchAttempts(CaveProfile caveProfile) { - if (caveProfile == null) { - return 6; - } - - return Math.max(1, caveProfile.anchorSearchAttempts()); - } - - private boolean isRegenTraceThread() { - return Thread.currentThread().getName().startsWith("Iris-Regen-") - && IrisSettings.get().getGeneral().isDebug(); - } - - private record ObjectPlacementSummary( - int biomeSurfacePlacersChecked, - int biomeSurfacePlacersTriggered, - int biomeCavePlacersChecked, - int biomeCavePlacersTriggered, - int regionSurfacePlacersChecked, - int regionSurfacePlacersTriggered, - int regionCavePlacersChecked, - int regionCavePlacersTriggered, - int objectAttempts, - int objectPlaced, - int objectRejected, - int objectNull, - int objectErrors - ) { - } - - private record ObjectPlacementResult(int attempts, int placed, int rejected, int nullObjects, int errors) { - } - - private record CavePlacementAnchor(int x, int y, int z) { - } - - private record ContainedPlacementResult( - int resultY, - CaveObjectPlacementTransaction.CommitResult commitResult - ) { - } - - private static final class CaveRejectLogState { - private final AtomicLong lastLogMs = new AtomicLong(0L); - private final AtomicInteger suppressed = new AtomicInteger(0); - } - - @BlockCoordinates - private Set guessPlacedKeys(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { - Set f = new KSet<>(); - for (int i = 0; i < objectPlacement.getDensity(rng, x, z, engine.getData()); i++) { - IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(engine.getComplex(), rng), engine); - if (v == null) { - continue; - } - - f.add(v.getLoadKey()); - } - - return f; - } - - public Set guess(int x, int z) { - // todo The guess doesnt bring into account that the placer may return -1 - RNG rng = applyNoise(x, z, CacheKey.key(x, z) + engine.getSeedManager().getMantle()); - IrisBiome biome = engine.getSurfaceBiome((x << 4) + 8, (z << 4) + 8); - IrisRegion region = engine.getRegion((x << 4) + 8, (z << 4) + 8); - Set v = new KSet<>(); - for (IrisObjectPlacement i : ObjectPlacements.surface(biome)) { - if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - v.addAll(guessPlacedKeys(rng, x, z, i)); - } - } - - for (IrisObjectPlacement i : ObjectPlacements.surface(region)) { - if (rng.chance(i.getChance() + rng.d(-0.005, 0.005))) { - v.addAll(guessPlacedKeys(rng, x, z, i)); - } - } - - return v; + return keys; } /** How far, in blocks along X and Z, placements may write beyond their chunk. */ - public int reach() { - IrisDimension dimension = engine.getDimension(); - KMap sizeCache = new KMap<>(); - KSet warnedLargeObjects = new KSet<>(); - int radius = 0; - for (IrisRegion region : dimension.getAllRegions(engine)) { - if (region == null) { - continue; - } - radius = Math.max(radius, computePlacementRadius(ObjectPlacements.all(region), sizeCache, warnedLargeObjects)); - radius = Math.max(radius, computeProceduralRadius(ObjectPlacements.procedural(region))); - } - for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - if (biome == null) { - continue; - } - radius = Math.max(radius, computePlacementRadius(ObjectPlacements.all(biome), sizeCache, warnedLargeObjects)); - radius = Math.max(radius, computeProceduralRadius(ObjectPlacements.procedural(biome))); - } - - return radius; + public int reach(PackSettings settings) { + return new PlacementReach(host, log).ofPack(settings); } - - private int computePlacementRadius( - KList placements, - KMap sizeCache, - KSet warnedLargeObjects - ) { - int radius = 0; - for (IrisObjectPlacement placement : placements) { - if (placement == null) { - continue; - } - for (String objectKey : placement.getPlace()) { - try { - IrisBlockVector size = loadObjectSize(sizeCache, objectKey); - if (size == null) { - continue; - } - int reach = calculatePlacementReach(size, placement); - if (reach > 128 && warnedLargeObjects.add(objectKey)) { - log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); - } - radius = Math.max(radius, reach); - } catch (Throwable e) { - log.error("Failed to work out the reach of an object placement", e); - } - } - } - return radius; - } - - private int computeProceduralRadius(ResolvedProceduralObjects procedural) { - if (procedural == null || procedural.isEmpty()) { - return 0; - } - int radius = 0; - for (IrisProceduralPlacement placement : procedural.getAllPlacements()) { - if (placement == null) { - continue; - } - KList variants = placement.getVariantObjects(engine.getData()); - if (variants == null) { - continue; - } - IrisObjectPlacement objectPlacement = placement.asPlacement(); - for (IrisObject variant : variants) { - if (variant == null) { - continue; - } - IrisBlockVector size = new IrisBlockVector(variant.getW(), variant.getH(), variant.getD()); - radius = Math.max(radius, calculatePlacementReach(size, objectPlacement)); - } - } - return radius; - } - - static int calculatePlacementReach(IrisBlockVector size, IrisObjectPlacement placement) { - if (size == null) { - return 0; - } - if (placement == null) { - return Math.max(Math.abs(size.getBlockX()), Math.abs(size.getBlockZ())); - } - - double scale = placement.getScale() != null ? Math.max(1D, placement.getScale().getMaxScale()) : 1D; - int width = scaledDimension(size.getBlockX(), scale); - int height = scaledDimension(size.getBlockY(), scale); - int depth = scaledDimension(size.getBlockZ(), scale); - IrisObjectRotation rotation = placement.getRotation(); - boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().enabled(); - boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().enabled(); - int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); - int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); - int warp = placement.getWarp() != null && !placement.getWarp().isFlat() - ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) - : 0; - int vacuum = placement.getMode().placeMode().bendsTerrain() - ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode().placeMode().vacuum(), placement.getVacuumSettings()) - : 0; - long reach = (long) footprint + translation + warp + vacuum; - return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; - } - - private static int scaledDimension(int dimension, double scale) { - int absoluteDimension = Math.abs(dimension); - if (scale <= 1D) { - return absoluteDimension; - } - return (int) Math.ceil((absoluteDimension * scale) + (scale * 2D)); - } - - private static int calculateTranslationReach(IrisObjectTranslate translate, IrisObjectRotation rotation, boolean rotateVertically) { - if (translate == null || !translate.canTranslate()) { - return 0; - } - double x = translate.getX(); - double y = translate.getY(); - double z = translate.getZ(); - if (rotateVertically) { - return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); - } - boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().enabled(); - return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); - } - - private IrisBlockVector loadObjectSize(KMap sizeCache, String objectKey) { - return sizeCache.computeIfAbsent(objectKey, k -> { - try { - return IrisObject.sampleSize(engine.getData().getObjectLoader().findFile(objectKey)); - } catch (IOException e) { - log.error("Failed to size an object", e); - } - - return null; - }); - } - - private final class CaveAnchorCache { - private final Long2ObjectOpenHashMap>> settingCaches; - private final Long2ObjectOpenHashMap carvedColumns; - private final Long2IntOpenHashMap surfaceHeights; - - private CaveAnchorCache() { - this.settingCaches = new Long2ObjectOpenHashMap<>(); - this.carvedColumns = new Long2ObjectOpenHashMap<>(); - this.surfaceHeights = new Long2IntOpenHashMap(); - this.surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); - } - - private KList get(MantleWriter writer, CaveAnchorMode anchorMode, int anchorScanStep, int objectMinDepthBelowSurface, int x, int z) { - if (anchorScanStep > 65535 || objectMinDepthBelowSurface > 65535) { - return scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); - } - - long settingKey = ((long) anchorMode.ordinal() << 32) | ((long) anchorScanStep << 16) | objectMinDepthBelowSurface; - Long2ObjectOpenHashMap> columnCache = settingCaches.get(settingKey); - if (columnCache == null) { - columnCache = new Long2ObjectOpenHashMap<>(); - settingCaches.put(settingKey, columnCache); - } - - long columnKey = CacheKey.key(x, z); - KList anchors = columnCache.get(columnKey); - if (anchors != null) { - return anchors; - } - - anchors = scanCaveAnchorColumn(writer, anchorMode, anchorScanStep, objectMinDepthBelowSurface, x, z, this); - columnCache.put(columnKey, anchors); - return anchors; - } - - private byte[] getCarvedColumn(MantleWriter writer, int x, int z, int height) { - long columnKey = CacheKey.key(x, z); - byte[] carvedColumn = carvedColumns.get(columnKey); - if (carvedColumn != null && carvedColumn.length == height) { - return carvedColumn; - } - - carvedColumn = writer.getCarvedColumn(x, z, height); - carvedColumns.put(columnKey, carvedColumn); - return carvedColumn; - } - - private int getSurfaceHeight(int x, int z) { - long columnKey = CacheKey.key(x, z); - int surfaceY = surfaceHeights.get(columnKey); - if (surfaceY != Integer.MIN_VALUE) { - return surfaceY; - } - - surfaceY = engine.getHeight(x, z); - surfaceHeights.put(columnKey, surfaceY); - return surfaceY; - } - } - } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 5f8855641..6b9241941 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -18,17 +18,19 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; -import art.arcane.iris.engine.object.procedural.IrisProceduralPlacement; -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 art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralPlacement; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.world.PackWorld; import java.util.Comparator; +import java.util.List; /** * Builds what object placing would build on first use, for every object placement and procedural object the world's @@ -38,55 +40,48 @@ import java.util.Comparator; */ final class ObjectWarmUp { private static final long ROOT_SEED_SALT = 7777L; - private static final int PROBE_COORDINATE = 0; - private final Engine engine; + private final ObjectHost host; private final RNG root; private int warmed; - ObjectWarmUp(Engine engine) { - this.engine = engine; - this.root = new RNG(engine.getSeedManager().getComponent() + ROOT_SEED_SALT); + ObjectWarmUp(PackWorld world) { + this.host = ObjectHost.of(world); + this.root = new RNG(IrisSeed.COMPONENT.of(world) + ROOT_SEED_SALT); } void warm() { - KList biomes = engine.getAllBiomes(); - biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); - for (IrisBiome biome : biomes) { - warmPlacements(ObjectPlacements.all(biome)); - warmProcedural(ObjectPlacements.procedural(biome)); - } - - KList regions = engine.getDimension().getAllRegions(engine); - regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); - for (IrisRegion region : regions) { - warmPlacements(ObjectPlacements.all(region)); - warmProcedural(ObjectPlacements.procedural(region)); - } - } - - private void warmPlacements(KList placements) { - if (placements == null) { - return; - } - for (IrisObjectPlacement placement : placements) { - if (placement == null) { - continue; + List> placements = byKey(host.declarations(ObjectSettings.class)); + List> procedural = byKey(host.declarations(ProceduralObjectSettings.class)); + for (Target level : new Target[]{Target.BIOME, Target.REGION}) { + for (Declaration declaration : placements) { + if (declaration.level() == level) { + warmPlacements(declaration.settings().objects()); + } + } + for (Declaration declaration : procedural) { + if (declaration.level() == level) { + warmProcedural(declaration.settings()); + } } - RNG rng = root.nextParallelRNG(warmed++); - placement.getSurfaceWarp(rng, engine.getData(), engine); - placement.getDensity(rng, PROBE_COORDINATE, PROBE_COORDINATE, engine.getData()); } } - private void warmProcedural(ResolvedProceduralObjects procedural) { - if (procedural == null) { - return; - } - for (IrisProceduralPlacement placement : procedural.getAllPlacements()) { + private static List> byKey(List> declarations) { + return declarations.stream().sorted(Comparator.comparing(Declaration::key)).toList(); + } + + private void warmPlacements(List placements) { + for (ObjectPlacement placement : placements) { if (placement != null) { - placement.getVariantObject(engine.getData(), root.nextParallelRNG(warmed++)); + host.warm(placement, root.nextParallelRNG(warmed++)); } } } + + private void warmProcedural(ProceduralObjectSettings settings) { + for (ProceduralPlacement placement : host.procedural(settings)) { + placement.variant(root.nextParallelRNG(warmed++)); + } + } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java new file mode 100644 index 000000000..c98c94fd3 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -0,0 +1,170 @@ +/* + * 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.anchor.PlaceMode; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSize; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.ProceduralPlacement; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** How far, in blocks along X and Z, the objects a pack places may write beyond their chunk. */ +final class PlacementReach { + private static final int LARGE_REACH_WARNING_BLOCKS = 128; + private static final int MAX_VACUUM_RADIUS_BLOCKS = 128; + private static final double SCALE_PADDING_FACTOR = 2D; + + private final ObjectHost host; + private final ModuleLog log; + private final Map> sizes = new HashMap<>(); + private final Set warnedLargeObjects = new HashSet<>(); + + PlacementReach(ObjectHost host, ModuleLog log) { + this.host = host; + this.log = log; + } + + /** The largest reach of any object placement or procedural object the pack's regions and biomes declare. */ + int ofPack(PackSettings settings) { + int radius = 0; + for (Entry entry : settings.declared(ObjectSettings.class)) { + radius = Math.max(radius, ofPlacements(entry.value().objects())); + } + for (Entry entry : settings.declared(ProceduralObjectSettings.class)) { + radius = Math.max(radius, ofProcedural(entry.value())); + } + return radius; + } + + private int ofPlacements(List placements) { + int radius = 0; + for (ObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.place()) { + radius = Math.max(radius, ofObject(placement, objectKey)); + } + } + return radius; + } + + private int ofObject(ObjectPlacement placement, String objectKey) { + try { + Optional size = sizes.computeIfAbsent(objectKey, host::sizeOf); + if (size.isEmpty()) { + return 0; + } + int reach = of(size.get(), placement); + if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) { + log.warn("Object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + return reach; + } catch (Throwable failure) { + log.error("Failed to work out the reach of an object placement", failure); + return 0; + } + } + + private int ofProcedural(ProceduralObjectSettings settings) { + int radius = 0; + for (ProceduralPlacement placement : host.procedural(settings)) { + for (PlaceableObject variant : placement.variants()) { + radius = Math.max(radius, of(new ObjectSize(variant.width(), variant.height(), variant.depth()), placement)); + } + } + return radius; + } + + /** The reach of an object of {@code size} placed with the options a procedural object has. */ + static int of(ObjectSize size, ProceduralPlacement placement) { + return of(size, placement.mode().placeMode(), null, placement.rotation(), placement.translate(), null, + placement.vacuumSettings().orElse(null)); + } + + static int of(ObjectSize size, ObjectPlacement placement) { + return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.translate(), + placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(), + placement.vacuumSettings().orElse(null)); + } + + private static int of(ObjectSize size, PlaceMode mode, Double maxScale, ObjectRotation rotation, ObjectTranslate translate, + Double warpMultiplier, VacuumSettings vacuum) { + double scale = maxScale == null ? 1D : Math.max(1D, maxScale); + int width = scaledDimension(size.width(), scale); + int height = scaledDimension(size.height(), scale); + int depth = scaledDimension(size.depth(), scale); + boolean rotateX = rotation != null && rotation.enabled() && rotation.xAxis() != null && rotation.xAxis().enabled(); + boolean rotateZ = rotation != null && rotation.enabled() && rotation.zAxis() != null && rotation.zAxis().enabled(); + int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); + int translation = translationReach(translate, rotation, rotateX || rotateZ); + int warp = warpMultiplier == null ? 0 : (int) Math.ceil(Math.abs(warpMultiplier) / 2D); + int vacuumReach = mode.bendsTerrain() ? 2 * vacuumRadius(mode, vacuum) : 0; + long reach = (long) footprint + translation + warp + vacuumReach; + return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + } + + private static int scaledDimension(int dimension, double scale) { + int absoluteDimension = Math.abs(dimension); + if (scale <= 1D) { + return absoluteDimension; + } + return (int) Math.ceil((absoluteDimension * scale) + (scale * SCALE_PADDING_FACTOR)); + } + + private static int translationReach(ObjectTranslate translate, ObjectRotation rotation, boolean rotateVertically) { + if (translate == null || (translate.x() == 0 && translate.y() == 0 && translate.z() == 0)) { + return 0; + } + double x = translate.x(); + double y = translate.y(); + double z = translate.z(); + if (rotateVertically) { + return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); + } + AxisRotationClamp yAxis = rotation == null ? null : rotation.yAxis(); + boolean rotateY = rotation != null && rotation.enabled() && yAxis != null && yAxis.enabled(); + return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); + } + + private static int vacuumRadius(PlaceMode mode, VacuumSettings settings) { + int radius = mode.vacuum().defaultRadiusBlocks(); + if (settings != null && settings.radius() > 0) { + radius = settings.radius(); + } + return Math.max(0, Math.min(MAX_VACUUM_RADIUS_BLOCKS, radius)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index e97c60212..68bb0e90a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -73,7 +73,7 @@ public final class StructureModule implements IrisModule, ModuleLifecycle { @Override public void install(StageGraph graph) { - graph.define(IrisStages.Structure.PLACE).requires(IrisStages.Objects.PLACE).softAfter(IrisStages.Floating.OBJECTS.ref()) + graph.define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE.ref(), IrisStages.Floating.OBJECTS.ref()) .reach(this::reach).run(StructureModule::place); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index bd8a3c3d1..51f73827a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -18,27 +18,22 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.core.modules.PlatformBlockStates; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.placement.ObjectPlacements; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; -import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.objects.ObjectSink; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.TreeMode; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.block.BlockState; import com.volmit.placement.PlacedBlock; +import com.volmit.resource.ResourceId; import com.volmit.service.SaplingGrowth; import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; @@ -60,80 +55,83 @@ public final class TreeGrowing implements SaplingGrowth { @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { - Engine engine = IrisPackWorld.of(world).engine(); - if (!ObjectPlacements.treeGrowth(engine.getDimension()).enabled()) { + ObjectHost host = ObjectHost.of(world); + BlockPosition at = sapling.at(); + TreeGrowthSettings growth = treeGrowth(host, at); + if (!growth.enabled()) { return Optional.empty(); } - - IrisObjectPlacement placement = pickPlacement(engine, sapling); - if (placement == null) { + Optional placement = pickPlacement(host, growth, sapling); + if (placement.isEmpty()) { return Optional.empty(); } - - IrisData data = engine.getData(); - IrisObject object = data.getObjectLoader().load(placement.getPlace().getRandom(RNG.r)); - GrowthPlacer placer = new GrowthPlacer(engine, surroundings); + List keys = placement.get().place(); + Optional tree = host.object(keys.get(RNG.r.i(keys.size()))); + if (tree.isEmpty()) { + return Optional.empty(); + } + PlaceableObject object = tree.get(); + GrowthSink sink = new GrowthSink(surroundings, host); BlockPosition center = sapling.center(); - object.place(center.x(), center.y() + object.getH() / 2, center.z(), placer, placement, RNG.r, data); - return Optional.of(new Growth(object.getLoadKey(), placer.placed())); + host.placeInto(object, center.x(), center.y() + object.height() / 2, center.z(), placement.get(), sink, RNG.r); + return Optional.of(new Growth(object.key(), sink.placed())); } @Override public TreeObjects treeObjects(PackWorld world) { - Engine engine = IrisPackWorld.of(world).engine(); + ObjectHost host = ObjectHost.of(world); Set objects = new HashSet<>(); Set procedural = new HashSet<>(); - - for (IrisRegion region : engine.getDimension().getAllRegions(engine)) { - if (region != null) { - collectPlacements(ObjectPlacements.all(region), objects); - collectProceduralTrees(ObjectPlacements.procedural(region), procedural); - } + for (Declaration declaration : host.declarations(ObjectSettings.class)) { + collectPlacements(declaration.settings().objects(), objects); } - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - if (biome != null) { - collectPlacements(ObjectPlacements.all(biome), objects); - collectProceduralTrees(ObjectPlacements.procedural(biome), procedural); - } + for (Declaration declaration : host.declarations(ProceduralObjectSettings.class)) { + collectProceduralTrees(declaration.settings().trees(), procedural); } return new TreeObjects(objects, procedural); } - /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species; null for none. */ - private static IrisObjectPlacement pickPlacement(Engine engine, Sapling sapling) { - KList placements = new KList<>(); - boolean useAll = ObjectPlacements.treeGrowth(engine.getDimension()).mode() == TreeMode.ALL; - - BlockPosition at = sapling.at(); - placements.addAll(matching(ObjectPlacements.all(engine.getBiome(at.x(), at.y(), at.z())), sapling.species())); - if (useAll || placements.isEmpty()) { - placements.addAll(matching(ObjectPlacements.all(engine.getRegion(at.x(), at.z())), sapling.species())); + private static TreeGrowthSettings treeGrowth(ObjectHost host, BlockPosition at) { + for (Entry entry : host.columnSettings().at(TreeGrowthSettings.class, at.x(), at.z())) { + if (entry.level() == Target.DIMENSION) { + return entry.value(); + } } - return placements.isNotEmpty() ? placements.getRandom() : null; + return new TreeGrowthSettings(); } - private static KList matching(KList objects, String species) { - KList matches = new KList<>(); - for (IrisObjectPlacement placement : objects) { - if (placement.matches(SAPLING_WIDTH, SAPLING_DEPTH, species)) { + /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species. */ + private static Optional pickPlacement(ObjectHost host, TreeGrowthSettings growth, Sapling sapling) { + List placements = new ArrayList<>(); + BlockPosition at = sapling.at(); + ResourceId biome = host.biomeAt(at.x(), at.y(), at.z()); + host.biomeDeclaration(biome, ObjectSettings.class).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + if (growth.mode() == TreeMode.ALL || placements.isEmpty()) { + ResourceId region = host.regionAt(at.x(), at.z()); + host.regionDeclaration(region, ObjectSettings.class).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + } + if (placements.isEmpty()) { + return Optional.empty(); + } + return Optional.of(placements.get(RNG.r.i(placements.size()))); + } + + private static List matching(ObjectSettings settings, String species) { + List matches = new ArrayList<>(); + for (ObjectPlacement placement : settings.objects()) { + if (placement.trees().stream().anyMatch(tree -> tree.matches(SAPLING_WIDTH, SAPLING_DEPTH, species))) { matches.add(placement); } } return matches; } - private static void collectPlacements(Iterable placements, Set objectKeys) { - if (placements == null) { - return; - } - for (IrisObjectPlacement placement : placements) { - if (placement == null - || placement.getTrees() == null - || placement.getTrees().isEmpty() - || placement.getPlace() == null) { + private static void collectPlacements(List placements, Set objectKeys) { + for (ObjectPlacement placement : placements) { + if (placement == null || placement.trees().isEmpty()) { continue; } - for (String objectKey : placement.getPlace()) { + for (String objectKey : placement.place()) { if (objectKey != null && !objectKey.isBlank()) { objectKeys.add(objectKey); } @@ -141,32 +139,27 @@ public final class TreeGrowing implements SaplingGrowth { } } - private static void collectProceduralTrees(ResolvedProceduralObjects proceduralObjects, Set objectKeys) { - if (proceduralObjects == null || proceduralObjects.getTrees() == null) { - return; - } - for (ResolvedTree resolved : proceduralObjects.getTrees()) { - Tree tree = resolved.settings(); - if (tree.name() == null || tree.name().isBlank()) { + private static void collectProceduralTrees(List trees, Set objectKeys) { + for (Tree tree : trees) { + if (tree == null || tree.name() == null || tree.name().isBlank()) { continue; } int variants = Math.max(1, tree.variants()); for (int index = 0; index < variants; index++) { - objectKeys.add(resolved.getVariantLoadKey(index)); + objectKeys.add(Tree.variantLoadKey(tree.name(), index)); } } } /** Places an object into a list of blocks, reading the world around the sapling through the host. */ - private static final class GrowthPlacer implements IObjectPlacer { - private final Engine engine; + private static final class GrowthSink implements ObjectSink { private final Surroundings surroundings; - private final PlatformBlockStates states = new PlatformBlockStates(key -> IrisPlatforms.get().registries().block(key)); + private final ObjectHost host; private final List placed = new ArrayList<>(); - private GrowthPlacer(Engine engine, Surroundings surroundings) { - this.engine = engine; + private GrowthSink(Surroundings surroundings, ObjectHost host) { this.surroundings = surroundings; + this.host = host; } private List placed() { @@ -174,77 +167,23 @@ public final class TreeGrowing implements SaplingGrowth { } @Override - public int getHighest(int x, int z, IrisData data) { - return surroundings.highest(x, z, false); - } - - @Override - public int getHighest(int x, int z, IrisData data, boolean ignoreFluid) { + public int highest(int x, int z, boolean ignoreFluid) { return surroundings.highest(x, z, ignoreFluid); } @Override - public void set(int x, int y, int z, PlatformBlockState state) { - placed.add(new PlacedBlock(new BlockPosition(x, y, z), states.toApi(state), Optional.empty())); + public BlockState get(int x, int y, int z) { + return surroundings.blockAt(x, y, z); } @Override - public PlatformBlockState get(int x, int y, int z) { - BlockState block = surroundings.blockAt(x, y, z); - return states.toPlatform(block); + public void set(int x, int y, int z, BlockState state) { + placed.add(new PlacedBlock(new BlockPosition(x, y, z), state, Optional.empty())); } @Override - public boolean isPreventingDecay() { - return true; - } - - @Override - public boolean isCarved(int x, int y, int z) { - return false; - } - - @Override - public boolean isSurfaceSolid(int x, int y, int z) { - return isSolid(x, y, z); - } - - @Override - public boolean isSolid(int x, int y, int z) { - return get(x, y, z).isSolid(); - } - - @Override - public boolean isUnderwater(int x, int z) { - return false; - } - - @Override - public int getFluidHeight() { - return engine.getDimension().getFluidHeight(); - } - - @Override - public boolean isDebugSmartBore() { - return false; - } - - @Override - public void setTile(int xx, int yy, int zz, TileData tile) { - } - - @Override - public void setData(int xx, int yy, int zz, T data) { - } - - @Override - public T getData(int xx, int yy, int zz, Class t) { - return null; - } - - @Override - public Engine getEngine() { - return engine; + public int fluidHeight() { + return host.fluidHeight(); } } } 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 index 4296c7c08..f69425cb5 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java @@ -65,7 +65,12 @@ public final class ObjectPlacements { /** The procedural objects {@code owner} declares; none when it declares none. */ public static ResolvedProceduralObjects procedural(IrisRegistrant owner) { Optional settings = owner.getModuleSettings().find(ProceduralObjectSettings.class); - return PROCEDURAL.computeIfAbsent(settings.orElse(NO_PROCEDURAL_OBJECTS), ResolvedProceduralObjects::new); + return procedural(settings.orElse(NO_PROCEDURAL_OBJECTS)); + } + + /** The procedural objects {@code settings} declare. */ + public static ResolvedProceduralObjects procedural(ProceduralObjectSettings settings) { + return PROCEDURAL.computeIfAbsent(settings, ResolvedProceduralObjects::new); } /** Whether {@code dimension} places its objects in the terrain stacked above it too. */ 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 index 5e8e05cb5..3afc0912a 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -18,6 +18,7 @@ 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; @@ -71,7 +72,7 @@ import java.util.function.BiConsumer; */ @Accessors(chain = true) @EqualsAndHashCode(callSuper = false) -public class IrisObject extends IrisRegistrant { +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"); @@ -372,6 +373,26 @@ public class IrisObject extends IrisRegistrant { } } + @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(); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java index 40b007f94..fbad263b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java @@ -63,6 +63,11 @@ public abstract class ResolvedProceduralPlacement implements IrisProceduralPlace return Math.max(1, shape.variants()); } + /** The options this object shares with an object placement. */ + public Shape shape() { + return shape; + } + @Override public String getName() { return shape.name(); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java index 5bf0f7742..36b493834 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -44,16 +44,8 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { this.settings = settings; } - /** The key a variant is loaded under, which placement markers and the sapling tree list name. */ - public static String variantLoadKey(String name, int index) { - if (index < 0) { - throw new IllegalArgumentException("index must not be negative"); - } - return "procedural/tree/" + name + "#" + index; - } - public String getVariantLoadKey(int index) { - return variantLoadKey(settings.name(), index); + return Tree.variantLoadKey(settings.name(), index); } public Tree settings() { From 12ec03d61c6b0612ca2194b4e2524ec917f281b9 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:38:59 +0200 Subject: [PATCH 081/139] iris:terrain ported onto IrisApi and listed in the built-ins jar; bedrock and exploded palettes become dimension settings; layers and palettes are shared classes of the exposed package --- builtin-modules.txt | 4 + source-patterns.txt | 1 - .../iris/builtin/terrain/BedrockSettings.java | 38 +++ .../terrain/BiomeLayers.java | 188 +++++------ .../iris/builtin/terrain/ColumnSlope.java | 24 ++ .../ExplodeBiomePaletteSizeSettings.java | 44 +++ .../terrain/ExplodeBiomePalettesSettings.java | 38 +++ .../terrain/LayerLoad.java} | 17 +- .../iris/builtin/terrain/LayerNoise.java | 37 +++ .../iris/builtin/terrain/LayeredBiome.java | 29 ++ .../terrain/PaletteBlocks.java | 19 +- .../builtin/terrain/PaletteExplosion.java | 41 +++ .../terrain/ResolvedLayer.java | 48 +-- .../terrain/TerrainPalettes.java | 80 ++--- .../iris/engine/actuator/OreWarmUp.java | 50 +-- .../iris/engine/actuator/ResolvedOre.java | 34 +- .../iris/engine/actuator/ResolvedOres.java | 19 +- .../iris/engine/actuator/TerrainModule.java | 234 +------------ .../iris/engine/actuator/TerrainOres.java | 29 +- .../iris/engine/actuator/TerrainShaper.java | 312 ++++++++++++++++++ .../engine/mantle/components/CaveCarving.java | 7 +- .../iris/engine/modifier/CarveModule.java | 3 +- .../iris/engine/modifier/CaveApplying.java | 27 +- .../iris/engine/modifier/FloatingIslands.java | 24 +- .../iris/engine/modifier/IrisLayers.java | 85 +++++ .../engine/object/placement/VacuumModule.java | 7 +- .../object/placement/ValidateModule.java | 4 +- .../world/biome/IrisBiomeColorRenderer.java | 14 +- .../object/world/dimension/IrisDimension.java | 8 - 29 files changed, 949 insertions(+), 516 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java rename src/main/java/art/arcane/iris/{engine => builtin}/terrain/BiomeLayers.java (53%) create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java rename src/main/java/art/arcane/iris/{engine/actuator/HiddenOres.java => builtin/terrain/LayerLoad.java} (58%) create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java rename src/main/java/art/arcane/iris/{engine => builtin}/terrain/PaletteBlocks.java (64%) create mode 100644 src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java rename src/main/java/art/arcane/iris/{engine => builtin}/terrain/ResolvedLayer.java (66%) rename src/main/java/art/arcane/iris/{engine => builtin}/terrain/TerrainPalettes.java (56%) create mode 100644 src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 657dd5fba..27610d09f 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -24,3 +24,7 @@ include art/arcane/iris/engine/modifier/DepositClump*.class include art/arcane/iris/engine/modifier/ResolvedDeposit*.class module art.arcane.iris.engine.actuator.DecorantModule include art/arcane/iris/engine/decorator/** +module art.arcane.iris.engine.actuator.TerrainModule +include art/arcane/iris/engine/actuator/Terrain*.class +include art/arcane/iris/engine/actuator/ResolvedOre*.class +include art/arcane/iris/engine/actuator/OreWarmUp*.class diff --git a/source-patterns.txt b/source-patterns.txt index c42d04a72..31bac204e 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -1,6 +1,5 @@ art/arcane/iris/engine/actuator/** art/arcane/iris/engine/decorator/** -art/arcane/iris/engine/terrain/** art/arcane/iris/engine/modifier/** art/arcane/iris/engine/mantle/components/** art/arcane/iris/engine/object/** diff --git a/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java new file mode 100644 index 000000000..b92e2190d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java @@ -0,0 +1,38 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension has a layer of bedrock at its bottom, written as {@code "bedrock": false}. A dimension without the key has it. */ +@Desc("Should bedrock be generated or not.") +@Feature(id = "iris:terrain/bedrock", name = "Bedrock", key = "bedrock", root = "bedrock", targets = Target.DIMENSION) +public final class BedrockSettings implements IrisFeature { + @Desc("Should bedrock be generated or not.") + private boolean bedrock = true; + + public BedrockSettings() { + } + + public boolean bedrock() { + return bedrock; + } +} diff --git a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/builtin/terrain/BiomeLayers.java similarity index 53% rename from src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java rename to src/main/java/art/arcane/iris/builtin/terrain/BiomeLayers.java index 310c8d546..ed0105594 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/BiomeLayers.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/BiomeLayers.java @@ -15,33 +15,19 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - -package art.arcane.iris.engine.terrain; +package art.arcane.iris.builtin.terrain; import art.arcane.iris.builtin.prepare.SlopeClip; -import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; -import art.arcane.iris.builtin.terrain.LayersSettings; -import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; -import art.arcane.iris.builtin.terrain.LayerBlocks; -import art.arcane.iris.builtin.terrain.LockLayersSettings; -import art.arcane.iris.builtin.terrain.PaletteLayer; -import art.arcane.iris.builtin.terrain.SeaLayersSettings; -import art.arcane.iris.builtin.terrain.WallSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisValues; -import art.arcane.iris.engine.IrisComplex; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.noise.NoiseStyle; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; - import com.volmit.ModuleLog; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.noise.NoiseFactory; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -61,73 +47,62 @@ public final class BiomeLayers { private static final int LOCKED_LAYERS_REFERENCE_HEIGHT = 512; private static final LayersSettings DEFAULT_LAYERS = new LayersSettings(); private static final PaletteLayer NO_LAYER = PaletteLayer.withoutBlocks(); - - private static final class States { - private static final PlatformBlockState BARRIER = B.getState("BARRIER"); - } + private static final BlockState BARRIER = new BlockState("minecraft:barrier"); private final Supplier layerBlocks; + private final Supplier noise; private final ModuleLog log; private final Map resolved = new ConcurrentHashMap<>(); - private final Map>> surfaceHeights = new ConcurrentHashMap<>(); - private final Map>> seaHeights = new ConcurrentHashMap<>(); - private volatile Double busiestBiomeLayerCount; + private final Map>> surfaceHeights = new ConcurrentHashMap<>(); + private final Map>> seaHeights = new ConcurrentHashMap<>(); + private final Map biomes = new ConcurrentHashMap<>(); - /** The layers of the world {@code engine} generates now, reporting failures to {@code log}. */ - public static BiomeLayers of(Engine engine, ModuleLog log) { - return engine.getGeneration().state(BiomeLayers.class, - generating -> new BiomeLayers(() -> LayerBlocks.of(generating.getGeneration().world()), log)); + /** The layers of {@code world}. */ + public static BiomeLayers of(PackWorld world) { + return world.state(BiomeLayers.class, generating -> new BiomeLayers(() -> LayerBlocks.of(generating), () -> generating.resources().noise(), generating.log())); } - /** The layers of a world whose layer blocks {@code layerBlocks} gives, asked for when a layer first picks a block. */ - public BiomeLayers(Supplier layerBlocks, ModuleLog log) { + /** The layers of a world whose layer blocks {@code layerBlocks} and noise {@code noise} give, asked for when a layer first needs them. */ + public BiomeLayers(Supplier layerBlocks, Supplier noise, ModuleLog log) { this.layerBlocks = layerBlocks; + this.noise = noise; this.log = log; } /** {@code layer} ready for this world; its block picks are the world's {@link LayerBlocks}. */ public ResolvedLayer resolve(PaletteLayer layer) { - return resolved.computeIfAbsent(layer, declared -> ResolvedLayer.of(declared, layerBlocks)); + return resolved.computeIfAbsent(layer, declared -> ResolvedLayer.of(declared, layerBlocks, noise)); + } + + /** What the biome {@code id} declares about its layers, read once from {@code settings}. */ + public LayeredBiome biome(ResourceId id, FeatureSettings settings) { + LayeredBiome known = biomes.get(id); + if (known != null) { + return known; + } + return biomes.computeIfAbsent(id, ignored -> new LayeredBiome( + settings.declaredBy(id, LayersSettings.class).orElse(null), + settings.declaredBy(id, SeaLayersSettings.class).orElse(null), + settings.declaredBy(id, CaveCeilingLayersSettings.class).orElse(null), + settings.declaredBy(id, LockLayersSettings.class).orElse(null), + settings.declaredBy(id, LockLayersMaxSettings.class).orElse(null), + settings.declaredBy(id, WallSettings.class).orElse(null))); } /** The biome's wall, which places no block when the biome declares none. */ - public ResolvedLayer wall(IrisBiome biome) { - PaletteLayer layer = biome.getModuleSettings().find(WallSettings.class).map(WallSettings::layer).orElse(NO_LAYER); + public ResolvedLayer wall(LayeredBiome biome) { + PaletteLayer layer = biome.wall() == null ? NO_LAYER : biome.wall().layer(); return resolve(layer); } - /** The layers of the biome's surface, top first. */ - public static List layersOf(IrisBiome biome) { - return surfaceSettings(biome).layers(); - } - - /** The noise style of each layer of the biome's surface, top first, as Iris's generators know them. */ - public static List layerStyles(IrisBiome biome) { - return layersOf(biome).stream().map(layer -> IrisValues.generatorStyle(layer.style()).getStyle()).toList(); - } - - /** The most layers any biome the dimension reaches has, which is what studio's layer load view compares a biome with. */ - public double busiestLayerCount(Engine engine) { - Double cached = busiestBiomeLayerCount; - if (cached != null) { - return cached; - } - - double busiest = 0D; - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - busiest = Math.max(busiest, layersOf(biome).size()); - } - busiestBiomeLayerCount = busiest; - return busiest; - } - /** The blocks the biome's layers stack up to at the column, top first, at most {@code maxDepth} of them. */ - public KList generateLayers(IrisBiome biome, IrisDimension dimension, double wx, double wz, RNG random, int maxDepth, int height, IrisData data, IrisComplex complex) { + public KList generateLayers(LayeredBiome biome, PaletteExplosion explosion, double wx, double wz, RNG random, int maxDepth, int height, + ColumnSlope slope) { if (isLocked(biome)) { - return generateLockedLayers(biome, wx, wz, random, maxDepth, height, complex); + return generateLockedLayers(biome, wx, wz, random, maxDepth, height, slope); } - KList blocks = new KList<>(); + KList blocks = new KList<>(); if (maxDepth <= 0) { return blocks; } @@ -138,10 +113,10 @@ public final class BiomeLayers { return blocks; } - KList heightNoises = surfaceHeightNoises(settings, random); + KList heightNoises = surfaceHeightNoises(settings, random); for (int i = 0; i < layers.size(); i++) { ResolvedLayer layer = resolve(layers.get(i)); - double depth = layerDepth(layer, heightNoises.get(i), wx, wz, complex); + double depth = layerDepth(layer, heightNoises.get(i), wx, wz, slope); if (depth <= 0) { continue; } @@ -151,26 +126,25 @@ public final class BiomeLayers { break; } - separateLayers(blocks, dimension, maxDepth); + separateLayers(blocks, explosion, maxDepth); } return blocks; } /** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code maxDepth} of them. */ - public KList generateCeilingLayers(IrisBiome biome, IrisDimension dimension, double wx, double wz, RNG random, int maxDepth, int height, IrisData data, IrisComplex complex) { - KList blocks = new KList<>(); + public KList generateCeilingLayers(LayeredBiome biome, PaletteExplosion explosion, double wx, double wz, RNG random, int maxDepth) { + KList blocks = new KList<>(); if (maxDepth <= 0) { return blocks; } - List ceilingLayers = biome.getModuleSettings().find(CaveCeilingLayersSettings.class) - .map(CaveCeilingLayersSettings::layers).orElse(List.of()); + List ceilingLayers = biome.ceilingLayers() == null ? List.of() : biome.ceilingLayers().layers(); if (ceilingLayers.isEmpty()) { return blocks; } - KList heightNoises = surfaceHeightNoises(surfaceSettings(biome), random); + KList heightNoises = surfaceHeightNoises(surfaceSettings(biome), random); // Ceiling layers reuse the surface-layer height noise, so entries beyond the surface layers have none; skip them. int usableLayers = Math.min(ceilingLayers.size(), heightNoises.size()); for (int i = 0; i < usableLayers; i++) { @@ -185,22 +159,22 @@ public final class BiomeLayers { break; } - separateLayers(blocks, dimension, maxDepth); + separateLayers(blocks, explosion, maxDepth); } return blocks; } /** The blocks of the biome's sea layers at the column, from the water surface down, at most {@code maxDepth} of them. */ - public KList generateSeaLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepth, IrisData data) { - KList blocks = new KList<>(); - SeaLayersSettings settings = biome.getModuleSettings().find(SeaLayersSettings.class).orElse(null); + public KList generateSeaLayers(LayeredBiome biome, double wx, double wz, RNG random, int maxDepth) { + KList blocks = new KList<>(); + SeaLayersSettings settings = biome.seaLayers(); if (settings == null || settings.layers().isEmpty()) { return blocks; } List layers = settings.layers(); - KList heightNoises = seaHeightNoises(settings, random); + KList heightNoises = seaHeightNoises(settings, random); for (int i = 0; i < layers.size(); i++) { ResolvedLayer layer = resolve(layers.get(i)); int depth = heightNoises.get(i).fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); @@ -217,9 +191,9 @@ public final class BiomeLayers { return blocks; } - private KList generateLockedLayers(IrisBiome biome, double wx, double wz, RNG random, int maxDepthLimit, int height, IrisComplex complex) { - KList stacked = new KList<>(); - KList locked = new KList<>(); + private KList generateLockedLayers(LayeredBiome biome, double wx, double wz, RNG random, int maxDepthLimit, int height, ColumnSlope slope) { + KList stacked = new KList<>(); + KList locked = new KList<>(); int maxDepth = Math.min(maxDepthLimit, lockedLayersMax(biome)); if (maxDepth <= 0) { return stacked; @@ -228,10 +202,10 @@ public final class BiomeLayers { LayersSettings settings = surfaceSettings(biome); List layers = settings.layers(); if (!layers.isEmpty()) { - KList heightNoises = surfaceHeightNoises(settings, random); + KList heightNoises = surfaceHeightNoises(settings, random); for (int i = 0; i < layers.size(); i++) { ResolvedLayer layer = resolve(layers.get(i)); - double depth = layerDepth(layer, heightNoises.get(i), wx, wz, complex); + double depth = layerDepth(layer, heightNoises.get(i), wx, wz, slope); if (depth <= 0) { continue; } @@ -252,7 +226,7 @@ public final class BiomeLayers { return locked; } - private void stackLayer(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random, int maxDepth) { + private void stackLayer(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random, int maxDepth) { for (int j = 0; j < depth; j++) { if (blocks.size() >= maxDepth) { break; @@ -262,14 +236,14 @@ public final class BiomeLayers { } } - private void stackLayerUnlimited(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random) { + private void stackLayerUnlimited(KList blocks, ResolvedLayer layer, int index, double depth, double wx, double wz, RNG random) { for (int j = 0; j < depth; j++) { addBlock(blocks, layer, index, j, wx, wz, random); } } /** Adds the layer's block {@code j} blocks down; a layer that fails to pick adds nothing. */ - private void addBlock(KList blocks, ResolvedLayer layer, int index, int j, double wx, double wz, RNG random) { + private void addBlock(KList blocks, ResolvedLayer layer, int index, int j, double wx, double wz, RNG random) { double zoom = layer.zoom(); try { blocks.add(layer.get(random, index + j, (wx + j) / zoom, j, (wz - j) / zoom)); @@ -279,13 +253,13 @@ public final class BiomeLayers { } /** The barrier blocks a dimension puts between layers to show them apart. */ - private void separateLayers(KList blocks, IrisDimension dimension, int maxDepth) { - if (!dimension.isExplodeBiomePalettes()) { + private void separateLayers(KList blocks, PaletteExplosion explosion, int maxDepth) { + if (!explosion.exploded()) { return; } - for (int j = 0; j < dimension.getExplodeBiomePaletteSize(); j++) { - blocks.add(States.BARRIER); + for (int j = 0; j < explosion.size(); j++) { + blocks.add(BARRIER); if (blocks.size() >= maxDepth) { break; } @@ -293,39 +267,39 @@ public final class BiomeLayers { } /** How thick the layer is at the column: nothing where the slope is outside the layer's limits. */ - private double layerDepth(ResolvedLayer layer, CNG heightNoise, double wx, double wz, IrisComplex complex) { + private double layerDepth(ResolvedLayer layer, LayerNoise heightNoise, double wx, double wz, ColumnSlope slope) { double depth = layerThickness(layer, heightNoise, wx, wz); - SlopeClip slope = layer.slopeCondition(); - if (!slope.isDefault() && !slope.isValid(complex.getSlopeStream().get(wx, wz))) { + SlopeClip clip = layer.slopeCondition(); + if (!clip.isDefault() && !clip.isValid(slope.at(wx, wz))) { return 0; } return depth; } - private double layerThickness(ResolvedLayer layer, CNG heightNoise, double wx, double wz) { + private double layerThickness(ResolvedLayer layer, LayerNoise heightNoise, double wx, double wz) { double zoom = layer.zoom(); return heightNoise.fit(layer.minHeight(), layer.maxHeight(), wx / zoom, wz / zoom); } - private KList surfaceHeightNoises(LayersSettings settings, RNG rng) { - AtomicCache> cache = surfaceHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); + private KList surfaceHeightNoises(LayersSettings settings, RNG rng) { + AtomicCache> cache = surfaceHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); return heightNoises(cache, settings.layers(), SURFACE_HEIGHT_SEED, rng); } - private KList seaHeightNoises(SeaLayersSettings settings, RNG rng) { - AtomicCache> cache = seaHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); + private KList seaHeightNoises(SeaLayersSettings settings, RNG rng) { + AtomicCache> cache = seaHeights.computeIfAbsent(settings, declared -> new AtomicCache<>()); return heightNoises(cache, settings.layers(), SEA_HEIGHT_SEED, rng); } - private KList heightNoises(AtomicCache> cache, List layers, int firstSeed, RNG rng) { - KList cached = cache.getIfPresent(); + private KList heightNoises(AtomicCache> cache, List layers, int firstSeed, RNG rng) { + KList cached = cache.getIfPresent(); if (cached != null) { return cached; } return cache.aquire(() -> { - KList noises = new KList<>(); + KList noises = new KList<>(); int seed = firstSeed; for (PaletteLayer layer : layers) { noises.add(resolve(layer).heightNoise(rng.nextParallelRNG((seed++) * seed * seed * seed))); @@ -334,15 +308,15 @@ public final class BiomeLayers { }); } - private static LayersSettings surfaceSettings(IrisBiome biome) { - return biome.getModuleSettings().find(LayersSettings.class).orElse(DEFAULT_LAYERS); + private static LayersSettings surfaceSettings(LayeredBiome biome) { + return biome.layers() == null ? DEFAULT_LAYERS : biome.layers(); } - private static boolean isLocked(IrisBiome biome) { - return biome.getModuleSettings().find(LockLayersSettings.class).map(LockLayersSettings::locked).orElse(false); + private static boolean isLocked(LayeredBiome biome) { + return biome.lock() != null && biome.lock().locked(); } - private static int lockedLayersMax(IrisBiome biome) { - return biome.getModuleSettings().find(LockLayersMaxSettings.class).map(LockLayersMaxSettings::layers).orElse(LockLayersMaxSettings.DEFAULT_LAYERS); + private static int lockedLayersMax(LayeredBiome biome) { + return biome.lockMax() == null ? LockLayersMaxSettings.DEFAULT_LAYERS : biome.lockMax().layers(); } } diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java b/src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java new file mode 100644 index 000000000..9a0da0a4b --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java @@ -0,0 +1,24 @@ +/* + * 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.builtin.terrain; + +/** The slope of the terrain at a column, asked only when a layer limits where it shows by slope. */ +@FunctionalInterface +public interface ColumnSlope { + double at(double worldX, double worldZ); +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java new file mode 100644 index 000000000..85a1b81d2 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java @@ -0,0 +1,44 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +/** How many barrier blocks a dimension puts between layers when it explodes its biome palettes, written as {@code "explodeBiomePaletteSize": 3}. */ +@Desc("Customize the palette height explosion") +@Feature(id = "iris:terrain/explode-palette-size", name = "Explode biome palette size", key = "explodeBiomePaletteSize", root = "size", targets = Target.DIMENSION) +public final class ExplodeBiomePaletteSizeSettings implements IrisFeature { + public static final int DEFAULT_SIZE = 3; + + @MinNumber(1) + @MaxNumber(16) + @Desc("Customize the palette height explosion") + private int size = DEFAULT_SIZE; + + public ExplodeBiomePaletteSizeSettings() { + } + + public int size() { + return size; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java new file mode 100644 index 000000000..7a47733aa --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java @@ -0,0 +1,38 @@ +/* + * 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.builtin.terrain; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +/** Whether a dimension puts barrier blocks between the layers of its biomes to show them apart, written as {@code "explodeBiomePalettes": true}. */ +@Desc("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") +@Feature(id = "iris:terrain/explode-palettes", name = "Explode biome palettes", key = "explodeBiomePalettes", root = "explode", targets = Target.DIMENSION) +public final class ExplodeBiomePalettesSettings implements IrisFeature { + @Desc("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") + private boolean explode = false; + + public ExplodeBiomePalettesSettings() { + } + + public boolean explode() { + return explode; + } +} diff --git a/src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java b/src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java similarity index 58% rename from src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java rename to src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java index 48b5a3535..8cf6d635a 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/HiddenOres.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java @@ -15,18 +15,19 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +package art.arcane.iris.builtin.terrain; -package art.arcane.iris.engine.actuator; +import java.util.List; -import art.arcane.iris.builtin.terrain.HideOresSettings; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; +/** The layers of a biome's surface, which studio's layer view counts. */ +public final class LayerLoad { + private static final LayersSettings DEFAULT_LAYERS = new LayersSettings(); -/** Whether a dimension hides its ores ({@code hideOresForHiddenOre}): the terrain places none and the perfection pass turns the rest into their base blocks. */ -public final class HiddenOres { - private HiddenOres() { + private LayerLoad() { } - public static boolean in(IrisDimension dimension) { - return dimension.getModuleSettings().find(HideOresSettings.class).map(HideOresSettings::hide).orElse(false); + /** The layers of the biome's surface, top first; a biome that declares no layers has the one layer of grass the settings default to. */ + public static List layersOf(LayersSettings declared) { + return (declared == null ? DEFAULT_LAYERS : declared).layers(); } } diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java b/src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java new file mode 100644 index 000000000..c99dad96d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java @@ -0,0 +1,37 @@ +/* + * 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.builtin.terrain; + +import com.volmit.noise.NoiseSampler; + +/** The noise that sets how thick a layer is: a number between a layer's limits at every column. */ +public final class LayerNoise { + private final NoiseSampler noise; + + LayerNoise(NoiseSampler noise) { + this.noise = noise; + } + + /** The whole number between {@code min} and {@code max} the noise gives at the column. */ + public int fit(int min, int max, double x, double z) { + if (min == max) { + return min; + } + return (int) Math.round(min + noise.sample(x, z) * (max - min)); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java b/src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java new file mode 100644 index 000000000..4cde1683d --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java @@ -0,0 +1,29 @@ +/* + * 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.builtin.terrain; + + +/** + * What a biome declares about the layers of its ground: the layers of its surface, of its sea floor and of its cave ceilings, whether + * they are locked to the highest height the biome reaches, and its wall. A setting the biome does not declare is null. + */ +public record LayeredBiome(LayersSettings layers, SeaLayersSettings seaLayers, CaveCeilingLayersSettings ceilingLayers, + LockLayersSettings lock, LockLayersMaxSettings lockMax, WallSettings wall) { + /** A biome that declares nothing about its layers: the one layer of grass the settings default to. */ + public static final LayeredBiome UNDECLARED = new LayeredBiome(null, null, null, null, null, null); +} diff --git a/src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java b/src/main/java/art/arcane/iris/builtin/terrain/PaletteBlocks.java similarity index 64% rename from src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java rename to src/main/java/art/arcane/iris/builtin/terrain/PaletteBlocks.java index 3cedf3006..cf69aef45 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/PaletteBlocks.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/PaletteBlocks.java @@ -15,30 +15,25 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +package art.arcane.iris.builtin.terrain; -package art.arcane.iris.engine.terrain; - -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; import java.util.ArrayList; import java.util.List; -/** A palette's blocks as the platform's, the way terrain layers and palettes always picked from them. */ +/** A palette's blocks, the way terrain layers and palettes always picked from them. */ final class PaletteBlocks { private PaletteBlocks() { } - /** The platform's block of each spec that has one, each repeated by its weight. */ - static List weighted(BlockRegistry registry, List palette) { - List weighted = new ArrayList<>(); + /** The block of each spec, each repeated by its weight. */ + static List weighted(BlockRegistry registry, List palette) { + List weighted = new ArrayList<>(); for (BlockSpec spec : palette) { - PlatformBlockState state = B.getState(registry.resolve(spec).key()); - if (state == null) { - continue; - } + BlockState state = registry.resolve(spec); for (int n = 0; n < spec.weight(); n++) { weighted.add(state); } diff --git a/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java b/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java new file mode 100644 index 000000000..0e0201678 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java @@ -0,0 +1,41 @@ +/* + * 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.builtin.terrain; + +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; + +import java.util.List; + +/** Whether a dimension separates the layers of its biomes with barrier blocks to show them apart, and how many barriers it puts between them. */ +public record PaletteExplosion(boolean exploded, int size) { + public static final PaletteExplosion NONE = new PaletteExplosion(false, ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); + + /** What the dimension at the column of {@code settings} declares. */ + public static PaletteExplosion of(FeatureSettings settings, int worldX, int worldZ) { + boolean exploded = dimensionValue(settings.at(ExplodeBiomePalettesSettings.class, worldX, worldZ), ExplodeBiomePalettesSettings::explode, false); + int size = dimensionValue(settings.at(ExplodeBiomePaletteSizeSettings.class, worldX, worldZ), ExplodeBiomePaletteSizeSettings::size, + ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); + return new PaletteExplosion(exploded, size); + } + + private static V dimensionValue(List> entries, java.util.function.Function read, V fallback) { + return entries.stream().filter(entry -> entry.level() == com.volmit.FeatureAttachment.Target.DIMENSION).findFirst() + .map(entry -> read.apply(entry.value())).orElse(fallback); + } +} diff --git a/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java b/src/main/java/art/arcane/iris/builtin/terrain/ResolvedLayer.java similarity index 66% rename from src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java rename to src/main/java/art/arcane/iris/builtin/terrain/ResolvedLayer.java index d2d44d4b3..413669206 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/ResolvedLayer.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/ResolvedLayer.java @@ -15,42 +15,43 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - -package art.arcane.iris.engine.terrain; +package art.arcane.iris.builtin.terrain; import art.arcane.iris.builtin.prepare.SlopeClip; -import art.arcane.iris.builtin.terrain.LayerBlocks; -import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseStyle; import java.util.List; import java.util.function.Supplier; /** - * One {@link PaletteLayer} made ready for one world: its blocks as the platform's, and the noise that decides how thick - * it is here, built when first asked for. Which block it picks where is the world's {@link LayerBlocks}, shared with - * every other module that picks from the layer. + * One {@link PaletteLayer} made ready for one world: its blocks, and the noise that decides how thick it is here, built when first + * asked for. Which block it picks where is the world's {@link LayerBlocks}, shared with every other module that picks from the layer. * *

The thickness noise is built once, from the random of whoever asks first, as the layers of a biome always were. */ public final class ResolvedLayer { + /** The style of the noise that sets a layer's thickness: Iris's signature noise. */ + private static final NoiseStyle THICKNESS_STYLE = NoiseStyle.of("IRIS"); + private final PaletteLayer settings; private final Supplier layerBlocks; - private final AtomicCache> blocks = new AtomicCache<>(); - private final AtomicCache heightNoise = new AtomicCache<>(); + private final Supplier noise; + private final AtomicCache> blocks = new AtomicCache<>(); + private final AtomicCache heightNoise = new AtomicCache<>(); - private ResolvedLayer(PaletteLayer settings, Supplier layerBlocks) { + private ResolvedLayer(PaletteLayer settings, Supplier layerBlocks, Supplier noise) { this.settings = settings; this.layerBlocks = layerBlocks; + this.noise = noise; } /** {@code settings} ready for the world whose layer blocks {@code layerBlocks} gives, asked for when first needed. */ - static ResolvedLayer of(PaletteLayer settings, Supplier layerBlocks) { - return new ResolvedLayer(settings, layerBlocks); + static ResolvedLayer of(PaletteLayer settings, Supplier layerBlocks, Supplier noise) { + return new ResolvedLayer(settings, layerBlocks, noise); } public PaletteLayer settings() { @@ -79,32 +80,33 @@ public final class ResolvedLayer { } /** The noise that sets the layer's thickness, built from {@code rng} unless an earlier caller's is already kept. */ - public CNG heightNoise(RNG rng) { - CNG cached = heightNoise.getIfPresent(); + public LayerNoise heightNoise(RNG rng) { + LayerNoise cached = heightNoise.getIfPresent(); if (cached != null) { return cached; } - return heightNoise.aquire(() -> CNG.signature(rng.nextParallelRNG(settings.minHeight() * settings.maxHeight() + blocks().size()))); + return heightNoise.aquire(() -> new LayerNoise(noise.get().sampler(THICKNESS_STYLE, + rng.nextParallelRNG(settings.minHeight() * settings.maxHeight() + blocks().size()).getSeed()))); } /** The layer's block at the position, picked as {@link LayerBlocks#pick} says, or null when the palette has no block. */ - public PlatformBlockState get(RNG parent, int signature, double x, double y, double z) { + public BlockState get(RNG parent, int signature, double x, double y, double z) { int index = layerBlocks.get().pick(settings, parent, signature, x, y, z); return index == LayerBlocks.NONE ? null : blocks().get(index); } /** {@link #get(RNG, int, double, double, double)} for a layer asked once per column, such as a slab or a wall. */ - public PlatformBlockState get(RNG rng, double x, double y, double z) { + public BlockState get(RNG rng, double x, double y, double z) { return get(rng, 0, x, y, z); } - private List blocks() { - List cached = blocks.getIfPresent(); + private List blocks() { + List cached = blocks.getIfPresent(); if (cached != null) { return cached; } - return blocks.aquire(() -> layerBlocks.get().blocks(settings).stream().map(block -> B.getState(block.key())).toList()); + return blocks.aquire(() -> layerBlocks.get().blocks(settings)); } } diff --git a/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java similarity index 56% rename from src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java rename to src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java index b98a20459..1d991d0ae 100644 --- a/src/main/java/art/arcane/iris/engine/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java @@ -15,21 +15,19 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +package art.arcane.iris.builtin.terrain; -package art.arcane.iris.engine.terrain; - -import art.arcane.iris.builtin.terrain.FluidPaletteSettings; -import art.arcane.iris.builtin.terrain.RockPaletteSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisPackResources; -import art.arcane.iris.engine.UpperDimensionContext; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; +import com.volmit.world.UpperDimension; import java.util.List; import java.util.Map; @@ -53,21 +51,23 @@ public final class TerrainPalettes { @FunctionalInterface public interface ColumnBlocks { /** The block at the column, or null when the palette has no block. */ - PlatformBlockState at(double x, double z); + BlockState at(double x, double z); } - private final Engine engine; + private final PackWorld world; + private final long complexSeed; private final AtomicCache rock = new AtomicCache<>(); private final AtomicCache fluid = new AtomicCache<>(); - private final Map upperRocks = new ConcurrentHashMap<>(); + private final Map upperRocks = new ConcurrentHashMap<>(); - TerrainPalettes(Engine engine) { - this.engine = engine; + TerrainPalettes(PackWorld world) { + this.world = world; + this.complexSeed = IrisSeed.COMPLEX.of(world); } - /** The palettes of the world {@code engine} generates now. */ - public static TerrainPalettes of(Engine engine) { - return engine.getGeneration().state(TerrainPalettes.class, TerrainPalettes::new); + /** The palettes of {@code world}. */ + public static TerrainPalettes of(PackWorld world) { + return world.state(TerrainPalettes.class, TerrainPalettes::new); } /** Builds the rock and fluid noise now instead of when first asked for. */ @@ -77,54 +77,60 @@ public final class TerrainPalettes { } /** The rock at the column, below the biome's layers. */ - public PlatformBlockState rockAt(double x, double z) { + public BlockState rockAt(double x, double z) { return rock().at(x, z); } /** The fluid at the column, above the terrain up to the fluid height. */ - public PlatformBlockState fluidAt(double x, double z) { + public BlockState fluidAt(double x, double z) { return fluid().at(x, z); } /** The rock at the column of the upper dimension: the world's own when the upper dimension is the dimension itself. */ - public PlatformBlockState upperRockAt(UpperDimensionContext upper, double x, double z) { - return upperRocks.computeIfAbsent(upper, this::upperRock).at(x, z); + public BlockState upperRockAt(UpperDimension upper, double x, double z) { + return upperRocks.computeIfAbsent(upper.key(), key -> upperRock(upper, x, z)).at(x, z); } private ColumnBlocks rock() { - return rock.aquireOrThrow(() -> columns(rockPalette(engine.getDimension()), complexRng().nextParallelRNG(ROCK_SIGNATURE), engine.getData())); + return rock.aquireOrThrow(() -> columns(rockPalette(world.settings().declared(RockPaletteSettings.class)), complexRng().nextParallelRNG(ROCK_SIGNATURE), + world.resources())); } private ColumnBlocks fluid() { - return fluid.aquireOrThrow(() -> columns(fluidPalette(engine.getDimension()), complexRng().nextParallelRNG(FLUID_SIGNATURE), engine.getData())); + return fluid.aquireOrThrow(() -> columns(fluidPalette(world.settings().declared(FluidPaletteSettings.class)), complexRng().nextParallelRNG(FLUID_SIGNATURE), + world.resources())); } private RNG complexRng() { - return new RNG(engine.getSeedManager().getComplex()); + return new RNG(complexSeed); } - private ColumnBlocks upperRock(UpperDimensionContext upper) { - if (upper.isSelfReferencing()) { + private ColumnBlocks upperRock(UpperDimension upper, double x, double z) { + if (upper.isThisDimension()) { return rock(); } - long seedOffset = upper.getDimension().getLoadKey().hashCode(); - RNG rng = new RNG(engine.getSeedManager().getComplex() ^ seedOffset); - return columns(rockPalette(upper.getDimension()), rng.nextParallelRNG(ROCK_SIGNATURE), upper.getData()); + long seedOffset = upper.key().hashCode(); + RNG rng = new RNG(complexSeed ^ seedOffset); + List> declared = upper.settings().at(RockPaletteSettings.class, (int) x, (int) z); + return columns(rockPalette(declared), rng.nextParallelRNG(ROCK_SIGNATURE), upper.resources()); } - private static PaletteSpec rockPalette(IrisDimension dimension) { - return dimension.getModuleSettings().find(RockPaletteSettings.class).orElseGet(RockPaletteSettings::new).palette(); + private static PaletteSpec rockPalette(List> declared) { + return dimensionLevel(declared).map(Entry::value).orElseGet(RockPaletteSettings::new).palette(); } - private static PaletteSpec fluidPalette(IrisDimension dimension) { - return dimension.getModuleSettings().find(FluidPaletteSettings.class).orElseGet(FluidPaletteSettings::new).palette(); + private static PaletteSpec fluidPalette(List> declared) { + return dimensionLevel(declared).map(Entry::value).orElseGet(FluidPaletteSettings::new).palette(); + } + + private static java.util.Optional> dimensionLevel(List> declared) { + return declared.stream().filter(entry -> entry.level() == Target.DIMENSION).findFirst(); } /** The palette's blocks over the columns, picked by its noise: the noise at a column, from 0 to 1, is how far down the weighted list the block is. */ - private static ColumnBlocks columns(PaletteSpec palette, RNG rng, IrisData data) { - IrisPackResources resources = data.getPackResources(); - List blocks = PaletteBlocks.weighted(resources.blocks(), palette.palette()); + private static ColumnBlocks columns(PaletteSpec palette, RNG rng, PackResources resources) { + List blocks = PaletteBlocks.weighted(resources.blocks(), palette.palette()); if (blocks.isEmpty()) { return (x, z) -> null; } diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java index 11935ef1f..f3812b71a 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -15,16 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.actuator; -import art.arcane.iris.engine.framework.Engine; -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 art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.terrain.OreSettings; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; import java.util.Comparator; +import java.util.List; import java.util.function.LongSupplier; /** @@ -35,36 +37,40 @@ import java.util.function.LongSupplier; final class OreWarmUp { private static final long ROOT_SEED_SALT = 7777L; - private final Engine engine; + private final PackWorld world; private final TerrainOres ores; private final RNG root; private int warmed; - OreWarmUp(Engine engine) { - this(engine, TerrainOres.of(engine)); + OreWarmUp(PackWorld world) { + this(world, TerrainOres.of(world)); } - OreWarmUp(Engine engine, TerrainOres ores) { - this.engine = engine; + OreWarmUp(PackWorld world, TerrainOres ores) { + this.world = world; this.ores = ores; - this.root = new RNG(engine.getSeedManager().getComponent() + ROOT_SEED_SALT); + this.root = new RNG(IrisSeed.COMPONENT.of(world) + ROOT_SEED_SALT); } void warm() { LongSupplier seeds = () -> root.nextParallelRNG(warmed++).getSeed(); - KList biomes = engine.getAllBiomes(); - biomes.sort(Comparator.comparing(IrisBiome::getLoadKey)); - for (IrisBiome biome : biomes) { - ores.of(biome).warm(seeds); - } + List> declared = world.settings().declared(OreSettings.class); + warmLevel(declared, Target.BIOME, seeds); + warmLevel(declared, Target.REGION, seeds); + warmLevel(declared, Target.DIMENSION, seeds); + } - KList regions = engine.getDimension().getAllRegions(engine); - regions.sort(Comparator.comparing(IrisRegion::getLoadKey)); - for (IrisRegion region : regions) { - ores.of(region).warm(seeds); - } + /** The ores of every owner at {@code level}, ordered by the key of the biome, region or dimension that declares them. */ + private void warmLevel(List> declared, Target level, LongSupplier seeds) { + declared.stream() + .filter(entry -> entry.level() == level) + .sorted(Comparator.comparing((Entry entry) -> key(entry.source()))) + .forEach(entry -> ores.of(entry.value()).warm(seeds)); + } - ores.of(engine.getDimension()).warm(seeds); + private static String key(ResourceId source) { + String path = source.path(); + return path.substring(path.indexOf('/') + 1); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java index ec1d1c72c..9593b00cb 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java @@ -15,25 +15,23 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.terrain.OreGenerator; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; import com.volmit.block.PaletteSampler; import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseSampler; +import com.volmit.resource.PackResources; import java.util.ArrayList; import java.util.List; /** - * One {@link OreGenerator} made ready for one world: its palette resolved to the platform's blocks and the noise that + * One {@link OreGenerator} made ready for one world: its palette resolved to blocks and the noise that * decides where it places ore, built from the seed it is warmed with or, when nothing warmed it, from the terrain seed * of its first use. The palette picks with the terrain seed. What the generator describes stays in the settings; * everything that needs the platform, the pack or the world seed is here. @@ -43,7 +41,7 @@ final class ResolvedOre { private final NoiseFactory noise; private final BlockRegistry blockRegistry; private final long terrainSeed; - private final List blocks; + private final List blocks; private final AtomicCache chance = new AtomicCache<>(); private final AtomicCache palette = new AtomicCache<>(); @@ -51,7 +49,7 @@ final class ResolvedOre { * @param terrainSeed the seed the palette picks with, and the noise is built from when nothing warmed it first * @param blocks the palette as the platform's blocks, each repeated by its weight */ - ResolvedOre(OreGenerator settings, NoiseFactory noise, BlockRegistry blockRegistry, long terrainSeed, List blocks) { + ResolvedOre(OreGenerator settings, NoiseFactory noise, BlockRegistry blockRegistry, long terrainSeed, List blocks) { this.settings = settings; this.noise = noise; this.blockRegistry = blockRegistry; @@ -59,20 +57,16 @@ final class ResolvedOre { this.blocks = List.copyOf(blocks); } - /** {@code settings} ready for {@code engine}: its blocks resolved through the pack, its picks seeded with the terrain seed. */ - static ResolvedOre of(OreGenerator settings, Engine engine) { - var resources = engine.getData().getPackResources(); + /** {@code settings} ready for a world with {@code resources}: its blocks resolved through the pack, its picks seeded with the terrain seed. */ + static ResolvedOre of(OreGenerator settings, PackResources resources, long terrainSeed) { BlockRegistry registry = resources.blocks(); - return new ResolvedOre(settings, resources.noise(), registry, engine.getSeedManager().getTerrain(), weighted(registry, settings.palette().palette())); + return new ResolvedOre(settings, resources.noise(), registry, terrainSeed, weighted(registry, settings.palette().palette())); } - private static List weighted(BlockRegistry registry, List specs) { - List weighted = new ArrayList<>(); + private static List weighted(BlockRegistry registry, List specs) { + List weighted = new ArrayList<>(); for (BlockSpec spec : specs) { - PlatformBlockState state = B.getState(registry.resolve(spec).key()); - if (state == null) { - continue; - } + BlockState state = registry.resolve(spec); for (int n = 0; n < spec.weight(); n++) { weighted.add(state); } @@ -98,7 +92,7 @@ final class ResolvedOre { } /** The ore block at the position, or null when the position is out of the band, the chance noise is above the threshold or the palette has no block. */ - PlatformBlockState generate(int x, int y, int z) { + BlockState generate(int x, int y, int z) { if (!settings.range().contains(y)) { return null; } @@ -120,7 +114,7 @@ final class ResolvedOre { return chance.aquire(() -> noise.sampler(settings.chanceStyle(), terrainSeed)); } - private PlatformBlockState pick(int x, int y, int z) { + private BlockState pick(int x, int y, int z) { if (blocks.isEmpty()) { return null; } @@ -128,6 +122,6 @@ final class ResolvedOre { return blocks.getFirst(); } PaletteSampler sampler = palette.aquire(() -> blockRegistry.palette(settings.palette(), terrainSeed)); - return B.getState(sampler.at(x, y, z).key()); + return sampler.at(x, y, z); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java index e3df4ad35..ed313ea66 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java @@ -15,13 +15,12 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.terrain.OreGenerator; import art.arcane.iris.builtin.terrain.OreSettings; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; +import com.volmit.resource.PackResources; import java.util.ArrayList; import java.util.List; @@ -49,12 +48,12 @@ final class ResolvedOres { this.undergroundBand = YBand.of(underground); } - /** {@code settings} ready for {@code engine}; generators the pack wrote as {@code null} are left out. */ - static ResolvedOres of(OreSettings settings, Engine engine) { + /** {@code settings} ready for a world with {@code resources}; generators the pack wrote as {@code null} are left out. */ + static ResolvedOres of(OreSettings settings, PackResources resources, long terrainSeed) { List ores = new ArrayList<>(); for (OreGenerator generator : settings.generators()) { if (generator != null) { - ores.add(ResolvedOre.of(generator, engine)); + ores.add(ResolvedOre.of(generator, resources, terrainSeed)); } } return ores.isEmpty() ? NONE : new ResolvedOres(ores); @@ -77,17 +76,17 @@ final class ResolvedOres { } } - PlatformBlockState generateSurface(int x, int y, int z) { + BlockState generateSurface(int x, int y, int z) { return firstOre(surface, x, y, z); } - PlatformBlockState generateUnderground(int x, int y, int z) { + BlockState generateUnderground(int x, int y, int z) { return firstOre(underground, x, y, z); } - private static PlatformBlockState firstOre(List ores, int x, int y, int z) { + private static BlockState firstOre(List ores, int x, int y, int z) { for (int index = 0; index < ores.size(); index++) { - PlatformBlockState ore = ores.get(index).generate(x, y, z); + BlockState ore = ores.get(index).generate(x, y, z); if (ore != null) { return ore; } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 9237e9ea4..3ddcba9e3 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -15,51 +15,33 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.terrain.BedrockSettings; import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.ExplodeBiomePaletteSizeSettings; +import art.arcane.iris.builtin.terrain.ExplodeBiomePalettesSettings; import art.arcane.iris.builtin.terrain.FluidPaletteSettings; +import art.arcane.iris.builtin.terrain.HideOresSettings; import art.arcane.iris.builtin.terrain.LayersSettings; import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; import art.arcane.iris.builtin.terrain.LockLayersSettings; +import art.arcane.iris.builtin.terrain.OreSettings; import art.arcane.iris.builtin.terrain.RockPaletteSettings; import art.arcane.iris.builtin.terrain.SeaLayersSettings; import art.arcane.iris.builtin.terrain.SlabSettings; import art.arcane.iris.builtin.terrain.WallSettings; -import art.arcane.iris.builtin.terrain.HideOresSettings; -import art.arcane.iris.builtin.terrain.OreSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.core.modules.IrisPackWorld; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.UpperDimensionContext; -import art.arcane.iris.engine.actuator.ResolvedOres.YBand; -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.world.region.IrisRegion; -import art.arcane.iris.engine.terrain.BiomeLayers; -import art.arcane.iris.engine.terrain.TerrainPalettes; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.context.ChunkedDataCache; -import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.documentation.BlockCoordinates; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; -import com.volmit.ModuleLog; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.StageGraph; import com.volmit.world.PackWorld; +import art.arcane.iris.builtin.terrain.TerrainPalettes; + /** * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up * to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and @@ -87,14 +69,16 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { registry.registerSettings(FluidPaletteSettings.class); registry.registerSettings(OreSettings.class); registry.registerSettings(HideOresSettings.class); + registry.registerSettings(BedrockSettings.class); + registry.registerSettings(ExplodeBiomePalettesSettings.class); + registry.registerSettings(ExplodeBiomePaletteSizeSettings.class); registry.registerLifecycle(this); } @Override public void warmUp(PackWorld world) { - Engine engine = IrisPackWorld.of(world).engine(); - TerrainPalettes.of(engine).warm(); - new OreWarmUp(engine).warm(); + TerrainPalettes.of(world).warm(); + new OreWarmUp(world).warm(); } @Override @@ -103,198 +87,6 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { } private static void shape(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - ModuleLog log = context.log(); - chunk.state(TerrainShaper.class, generating -> new TerrainShaper(generating, log)).shape(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.context()); - } - - /** What shaping terrain keeps for one engine runtime: the terrain stream's random. */ - static final class TerrainShaper { - private static final PlatformBlockState BEDROCK = B.getState("BEDROCK"); - - private final Engine engine; - private final TerrainPalettes palettes; - private final BiomeLayers layers; - private final TerrainOres ores; - private final RNG rng; - - TerrainShaper(Engine engine, ModuleLog log) { - this(engine, TerrainPalettes.of(engine), BiomeLayers.of(engine, log), TerrainOres.of(engine)); - } - - TerrainShaper(Engine engine, TerrainPalettes palettes, BiomeLayers layers, TerrainOres ores) { - this.engine = engine; - this.palettes = palettes; - this.layers = layers; - this.ores = ores; - this.rng = new RNG(engine.getSeedManager().getTerrain()); - } - - /** Fills the 16 x 16 columns of the chunk whose first block is {@code originX}, {@code originZ}, one slice along x at a time. */ - @BlockCoordinates - void shape(int originX, int originZ, Hunk blocks, ChunkContext context) { - PrecisionStopwatch stopwatch = PrecisionStopwatch.start(); - for (int sliceX = 0; sliceX < blocks.getWidth(); sliceX++) { - shapeSliver(originX, originZ, sliceX, blocks, context); - } - engine.getMetrics().getTerrain().put(stopwatch.getMilliseconds()); - } - - /** One plane from the sky to bedrock, one block thick along x. */ - @BlockCoordinates - private void shapeSliver(int x, int z, int xf, Hunk h, ChunkContext context) { - int chunkHeight = h.getHeight(); - int chunkDepth = h.getDepth(); - IrisDimension dimension = engine.getDimension(); - IrisData data = engine.getData(); - IrisComplex complex = engine.getComplex(); - RNG localRng = rng; - int fluidHeight = dimension.getFluidHeight(); - int clampedFluidHeight = Math.min(chunkHeight, fluidHeight); - boolean bedrockEnabled = dimension.isBedrock(); - boolean hideOres = HiddenOres.in(dimension); - ChunkedDataCache biomeCache = context.getBiome(); - ChunkedDataCache regionCache = context.getRegion(); - int realX = xf + x; - UpperDimensionContext upperContext = engine.getUpperContext(); - // Dimension-level ore lookups are chunk-invariant; resolving them per column paid - // the settings lookup times 256 per chunk for a constant. - ResolvedOres dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(dimension); - YBand dimensionSurfaceBand = dimensionOres.surfaceBand(); - YBand dimensionUndergroundBand = dimensionOres.undergroundBand(); - - for (int zf = 0; zf < chunkDepth; zf++) { - int realZ = zf + z; - IrisBiome biome = biomeCache.get(xf, zf); - IrisRegion region = regionCache.get(xf, zf); - int he = Math.min(chunkHeight, context.getRoundedHeight(xf, zf)); - int hf = Math.max(clampedFluidHeight, he); - if (hf < 0) { - continue; - } - - int topY = Math.min(hf, chunkHeight - 1); - PlatformBlockState fluid = palettes.fluidAt(realX, realZ); - PlatformBlockState rock = palettes.rockAt(realX, realZ); - PlatformBlockState mappedSurfaceBlock = complex.getImageMapRuntime().sampleSurfaceBlock(realX, realZ); - ResolvedOres biomeOres = hideOres ? ResolvedOres.NONE : ores.of(biome); - ResolvedOres regionOres = hideOres ? ResolvedOres.NONE : ores.of(region); - YBand biomeSurfaceBand = biomeOres.surfaceBand(); - YBand regionSurfaceBand = regionOres.surfaceBand(); - YBand biomeUndergroundBand = biomeOres.undergroundBand(); - YBand regionUndergroundBand = regionOres.undergroundBand(); - boolean hasSurfaceOres = biomeSurfaceBand.hasOres() || regionSurfaceBand.hasOres() || dimensionSurfaceBand.hasOres(); - boolean hasUndergroundOres = biomeUndergroundBand.hasOres() || regionUndergroundBand.hasOres() || dimensionUndergroundBand.hasOres(); - KList blocks = null; - KList fblocks = null; - - for (int i = topY; i >= 0; i--) { - if (i == 0 && bedrockEnabled) { - h.setRaw(xf, i, zf, BEDROCK); - continue; - } - - PlatformBlockState ore = null; - if (hasSurfaceOres) { - if (biomeSurfaceBand.contains(i)) { - ore = biomeOres.generateSurface(realX, i, realZ); - } - if (ore == null && regionSurfaceBand.contains(i)) { - ore = regionOres.generateSurface(realX, i, realZ); - } - if (ore == null && dimensionSurfaceBand.contains(i)) { - ore = dimensionOres.generateSurface(realX, i, realZ); - } - } - if (ore != null) { - h.setRaw(xf, i, zf, ore); - continue; - } - - if (i > he && i <= hf) { - int fdepth = hf - i; - if (fblocks == null) { - fblocks = layers.generateSeaLayers(biome, realX, realZ, localRng, hf - he, data); - } - - if (fblocks.hasIndex(fdepth)) { - h.setRaw(xf, i, zf, fblocks.get(fdepth)); - } else { - h.setRaw(xf, i, zf, fluid); - } - continue; - } - - if (i <= he) { - int depth = he - i; - if (depth == 0 && mappedSurfaceBlock != null) { - h.setRaw(xf, i, zf, mappedSurfaceBlock); - continue; - } - if (blocks == null) { - blocks = layers.generateLayers(biome, dimension, realX, realZ, localRng, he, he, data, complex); - } - - if (blocks.hasIndex(depth)) { - h.setRaw(xf, i, zf, blocks.get(depth)); - continue; - } - - if (hasUndergroundOres) { - if (biomeUndergroundBand.contains(i)) { - ore = biomeOres.generateUnderground(realX, i, realZ); - } - if (ore == null && regionUndergroundBand.contains(i)) { - ore = regionOres.generateUnderground(realX, i, realZ); - } - if (ore == null && dimensionUndergroundBand.contains(i)) { - ore = dimensionOres.generateUnderground(realX, i, realZ); - } - } - - if (ore != null) { - h.setRaw(xf, i, zf, ore); - } else { - h.setRaw(xf, i, zf, rock); - } - } - } - - if (upperContext != null) { - int rawUpperSurface = upperContext.getUpperSurfaceY(realX, realZ); - int upperGap = dimension.getUpperDimensionGap(); - int upperSurfaceY = Math.max(rawUpperSurface, he + upperGap); - - if (upperSurfaceY < chunkHeight - 1) { - IrisBiome upperBiome = upperContext.getUpperBiome(realX, realZ); - PlatformBlockState upperRock = palettes.upperRockAt(upperContext, realX, realZ); - PlatformBlockState upperMappedSurface = upperContext.getSurfaceBlock(realX, realZ); - int upperThickness = chunkHeight - 1 - upperSurfaceY; - KList upperBlocks = upperBiome != null - ? layers.generateLayers(upperBiome, upperContext.getDimension(), - realX, realZ, localRng, upperThickness, upperThickness, - upperContext.getData(), complex) - : null; - - for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { - if (y == chunkHeight - 1 && bedrockEnabled) { - h.setRaw(xf, y, zf, BEDROCK); - continue; - } - if (y == upperSurfaceY && upperMappedSurface != null) { - h.setRaw(xf, y, zf, upperMappedSurface); - continue; - } - int depthFromFace = y - upperSurfaceY; - if (upperBlocks != null && upperBlocks.hasIndex(depthFromFace)) { - h.setRaw(xf, y, zf, upperBlocks.get(depthFromFace)); - } else { - h.setRaw(xf, y, zf, upperRock); - } - } - } - } - } - } + TerrainShaper.of(context.world()).shape(context); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java index 1eb73d719..d68bb2432 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -15,12 +15,12 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - package art.arcane.iris.engine.actuator; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.terrain.OreSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.framework.Engine; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -30,24 +30,25 @@ import java.util.concurrent.ConcurrentHashMap; * ({@link ResolvedOres}), built from their {@link OreSettings} when first asked for or ahead of generation by {@link OreWarmUp}. */ final class TerrainOres { - private final Engine engine; + private final PackResources resources; + private final long terrainSeed; private final Map resolved = new ConcurrentHashMap<>(); - TerrainOres(Engine engine) { - this.engine = engine; + TerrainOres(PackWorld world) { + this.resources = world.resources(); + this.terrainSeed = IrisSeed.TERRAIN.of(world); } - /** The ores of the world {@code engine} generates now. */ - static TerrainOres of(Engine engine) { - return engine.getGeneration().state(TerrainOres.class, TerrainOres::new); + /** The ores of {@code world}. */ + static TerrainOres of(PackWorld world) { + return world.state(TerrainOres.class, TerrainOres::new); } /** - * The ore generators {@code owner}, a dimension, region or biome, declares; {@link ResolvedOres#NONE} when it declares none. The - * terrain asks this for two owners per column, so a resolved set is read without taking the map's lock. + * The ore generators {@code settings}, those a dimension, region or biome declares, make ready; {@link ResolvedOres#NONE} when it + * declares none. The terrain asks this for two owners per column, so a resolved set is read without taking the map's lock. */ - ResolvedOres of(IrisRegistrant owner) { - OreSettings settings = owner.getModuleSettings().find(OreSettings.class).orElse(null); + ResolvedOres of(OreSettings settings) { if (settings == null) { return ResolvedOres.NONE; } @@ -55,6 +56,6 @@ final class TerrainOres { if (existing != null) { return existing; } - return resolved.computeIfAbsent(settings, declared -> ResolvedOres.of(declared, engine)); + return resolved.computeIfAbsent(settings, declared -> ResolvedOres.of(declared, resources, terrainSeed)); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java new file mode 100644 index 000000000..894b40636 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -0,0 +1,312 @@ +/* + * 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.actuator; + +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.terrain.BedrockSettings; +import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.engine.actuator.ResolvedOres.YBand; +import art.arcane.iris.builtin.terrain.BiomeLayers; +import art.arcane.iris.builtin.terrain.ColumnSlope; +import art.arcane.iris.builtin.terrain.LayeredBiome; +import art.arcane.iris.builtin.terrain.PaletteExplosion; +import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; +import com.volmit.world.UpperDimension; + +import java.util.List; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.function.Function; + +/** What shaping terrain keeps for one world: the terrain stream's random and the palettes, layers and ores the columns are filled from. */ +final class TerrainShaper { + private static final BlockState BEDROCK = new BlockState("minecraft:bedrock"); + private static final int CHUNK_CENTRE = 7; + + private final TerrainPalettes palettes; + private final BiomeLayers layers; + private final TerrainOres ores; + private final RNG rng; + private final boolean levelsBelowTheDimensionDeclareOres; + + static TerrainShaper of(PackWorld world) { + return world.state(TerrainShaper.class, TerrainShaper::new); + } + + TerrainShaper(PackWorld world) { + this(world, TerrainPalettes.of(world), BiomeLayers.of(world), TerrainOres.of(world)); + } + + TerrainShaper(PackWorld world, TerrainPalettes palettes, BiomeLayers layers, TerrainOres ores) { + this.palettes = palettes; + this.layers = layers; + this.ores = ores; + this.rng = new RNG(IrisSeed.TERRAIN.of(world)); + this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).stream() + .anyMatch(entry -> entry.level() != Target.DIMENSION); + } + + /** Fills the 16 x 16 columns of the chunk, one slice along x at a time. */ + void shape(ChunkStageContext context) { + Chunk chunk = new Chunk(context); + for (int sliceX = 0; sliceX < chunk.blocks.getWidth(); sliceX++) { + shapeSliver(chunk, sliceX); + } + } + + /** One plane from the sky to bedrock, one block thick along x. */ + private void shapeSliver(Chunk chunk, int xf) { + Hunk h = chunk.blocks; + int chunkHeight = h.getHeight(); + int chunkDepth = h.getDepth(); + int realX = xf + chunk.originX; + + for (int zf = 0; zf < chunkDepth; zf++) { + int realZ = zf + chunk.originZ; + int he = Math.min(chunkHeight, (int) Math.round(chunk.terrain.surfaceY(realX, realZ))); + int hf = Math.max(chunk.clampedFluidHeight, he); + if (hf < 0) { + continue; + } + + int topY = Math.min(hf, chunkHeight - 1); + BlockState fluid = palettes.fluidAt(realX, realZ); + BlockState rock = palettes.rockAt(realX, realZ); + BlockState mappedSurfaceBlock = chunk.terrain.surfaceBlock(realX, realZ).orElse(null); + LayeredBiome biome = layers.biome(chunk.terrain.surfaceBiome(realX, realZ), chunk.settings); + ColumnOres columnOres = chunk.oresAt(realX, realZ); + ResolvedOres biomeOres = columnOres.biome; + ResolvedOres regionOres = columnOres.region; + YBand biomeSurfaceBand = biomeOres.surfaceBand(); + YBand regionSurfaceBand = regionOres.surfaceBand(); + YBand biomeUndergroundBand = biomeOres.undergroundBand(); + YBand regionUndergroundBand = regionOres.undergroundBand(); + ResolvedOres dimensionOres = chunk.dimensionOres; + YBand dimensionSurfaceBand = dimensionOres.surfaceBand(); + YBand dimensionUndergroundBand = dimensionOres.undergroundBand(); + boolean hasSurfaceOres = biomeSurfaceBand.hasOres() || regionSurfaceBand.hasOres() || dimensionSurfaceBand.hasOres(); + boolean hasUndergroundOres = biomeUndergroundBand.hasOres() || regionUndergroundBand.hasOres() || dimensionUndergroundBand.hasOres(); + KList blocks = null; + KList fblocks = null; + + for (int i = topY; i >= 0; i--) { + if (i == 0 && chunk.bedrockEnabled) { + place(h, xf, i, zf, BEDROCK); + continue; + } + + BlockState ore = null; + if (hasSurfaceOres) { + if (biomeSurfaceBand.contains(i)) { + ore = biomeOres.generateSurface(realX, i, realZ); + } + if (ore == null && regionSurfaceBand.contains(i)) { + ore = regionOres.generateSurface(realX, i, realZ); + } + if (ore == null && dimensionSurfaceBand.contains(i)) { + ore = dimensionOres.generateSurface(realX, i, realZ); + } + } + if (ore != null) { + place(h, xf, i, zf, ore); + continue; + } + + if (i > he && i <= hf) { + int fdepth = hf - i; + if (fblocks == null) { + fblocks = layers.generateSeaLayers(biome, realX, realZ, rng, hf - he); + } + + if (fblocks.hasIndex(fdepth)) { + place(h, xf, i, zf, fblocks.get(fdepth)); + } else { + place(h, xf, i, zf, fluid); + } + continue; + } + + if (i <= he) { + int depth = he - i; + if (depth == 0 && mappedSurfaceBlock != null) { + place(h, xf, i, zf, mappedSurfaceBlock); + continue; + } + if (blocks == null) { + blocks = layers.generateLayers(biome, chunk.explosion, realX, realZ, rng, he, he, chunk.slope); + } + + if (blocks.hasIndex(depth)) { + place(h, xf, i, zf, blocks.get(depth)); + continue; + } + + if (hasUndergroundOres) { + if (biomeUndergroundBand.contains(i)) { + ore = biomeOres.generateUnderground(realX, i, realZ); + } + if (ore == null && regionUndergroundBand.contains(i)) { + ore = regionOres.generateUnderground(realX, i, realZ); + } + if (ore == null && dimensionUndergroundBand.contains(i)) { + ore = dimensionOres.generateUnderground(realX, i, realZ); + } + } + + place(h, xf, i, zf, ore != null ? ore : rock); + } + } + + if (chunk.upper.isPresent()) { + fillUpperDimension(chunk, chunk.upper.get(), xf, zf, realX, realZ); + } + } + } + + /** The upper dimension's ground, filled in from the top of the column down to where it ends. */ + private void fillUpperDimension(Chunk chunk, UpperDimension upper, int xf, int zf, int realX, int realZ) { + Hunk h = chunk.blocks; + int chunkHeight = h.getHeight(); + OptionalInt upperY = chunk.terrain.upperDimensionY(realX, realZ); + if (upperY.isEmpty()) { + return; + } + int upperSurfaceY = upperY.getAsInt(); + if (upperSurfaceY >= chunkHeight - 1) { + return; + } + + FeatureSettings upperSettings = upper.settings(); + BlockState upperRock = palettes.upperRockAt(upper, realX, realZ); + BlockState upperMappedSurface = upper.surfaceBlock(realX, realZ).orElse(null); + int upperThickness = chunkHeight - 1 - upperSurfaceY; + LayeredBiome upperBiome = upperBiome(upperSettings, realX, realZ); + KList upperBlocks = layers.generateLayers(upperBiome, PaletteExplosion.of(upperSettings, realX, realZ), + realX, realZ, rng, upperThickness, upperThickness, chunk.slope); + + for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { + if (y == chunkHeight - 1 && chunk.bedrockEnabled) { + place(h, xf, y, zf, BEDROCK); + continue; + } + if (y == upperSurfaceY && upperMappedSurface != null) { + place(h, xf, y, zf, upperMappedSurface); + continue; + } + int depthFromFace = y - upperSurfaceY; + if (upperBlocks.hasIndex(depthFromFace)) { + place(h, xf, y, zf, upperBlocks.get(depthFromFace)); + } else { + place(h, xf, y, zf, upperRock); + } + } + } + + /** What the biome of the upper dimension at the column declares about its layers. */ + private LayeredBiome upperBiome(FeatureSettings upperSettings, int worldX, int worldZ) { + return new LayeredBiome(biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LayersSettings.class, worldX, worldZ), null, null, + biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LockLayersSettings.class, worldX, worldZ), + biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LockLayersMaxSettings.class, worldX, worldZ), null); + } + + private static S biomeLevel(FeatureSettings settings, Class type, int worldX, int worldZ) { + return settings.at(type, worldX, worldZ).stream().filter(entry -> entry.level() == Target.BIOME).map(Entry::value).findFirst().orElse(null); + } + + /** A block the palette has none of leaves the column as it is. */ + private static void place(Hunk blocks, int x, int y, int z, BlockState block) { + if (block != null) { + blocks.set(x, y, z, block); + } + } + + /** The ores of a column's region and biome. */ + private record ColumnOres(ResolvedOres region, ResolvedOres biome) { + static final ColumnOres NONE = new ColumnOres(ResolvedOres.NONE, ResolvedOres.NONE); + } + + /** What one chunk's columns share: its views, its dimension's switches and ores. */ + private final class Chunk { + final Hunk blocks; + final TerrainSampler terrain; + final FeatureSettings settings; + final int originX; + final int originZ; + final int clampedFluidHeight; + final boolean bedrockEnabled; + final PaletteExplosion explosion; + final ColumnSlope slope; + final Optional upper; + final ResolvedOres dimensionOres; + private final boolean hideOres; + + Chunk(ChunkStageContext context) { + this.blocks = context.hunk(BlockState.class); + this.terrain = context.terrain(); + this.settings = context.settings(); + this.originX = context.originX(); + this.originZ = context.originZ(); + this.clampedFluidHeight = Math.min(blocks.getHeight(), terrain.fluidHeight()); + int centreX = originX + CHUNK_CENTRE; + int centreZ = originZ + CHUNK_CENTRE; + this.bedrockEnabled = dimensionValue(settings.at(BedrockSettings.class, centreX, centreZ), BedrockSettings::bedrock, true); + this.hideOres = dimensionValue(settings.at(HideOresSettings.class, centreX, centreZ), HideOresSettings::hide, false); + this.explosion = PaletteExplosion.of(settings, centreX, centreZ); + this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); + this.upper = terrain.upperDimension(); + // Dimension-level ore lookups are chunk-invariant; resolving them per column paid the settings lookup times 256 per chunk for a constant. + this.dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(levelValue(settings.at(OreSettings.class, centreX, centreZ), Target.DIMENSION)); + } + + /** The ores of the column's region and biome; none where the levels below the dimension declare none, or the dimension hides ores. */ + ColumnOres oresAt(int worldX, int worldZ) { + if (hideOres || !levelsBelowTheDimensionDeclareOres) { + return ColumnOres.NONE; + } + List> declared = settings.at(OreSettings.class, worldX, worldZ); + return new ColumnOres(ores.of(levelValue(declared, Target.REGION)), ores.of(levelValue(declared, Target.BIOME))); + } + } + + private static V dimensionValue(List> entries, Function read, V fallback) { + S declared = levelValue(entries, Target.DIMENSION); + return declared == null ? fallback : read.apply(declared); + } + + private static S levelValue(List> entries, Target level) { + for (Entry entry : entries) { + if (entry.level() == level) { + return entry.value(); + } + } + return null; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 7046d1da8..e6f319f7a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -24,7 +24,7 @@ import art.arcane.iris.engine.IrisComplex; import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.terrain.TerrainPalettes; +import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; @@ -471,7 +471,7 @@ public class CaveCarving { private void prefillProfileFieldSamples(int startX, int startZ, IrisComplex complex, BlendScratch blendScratch) { fillFieldHeights(complex.getHeightStream(), startX, startZ, blendScratch.fieldSurfaceHeights); - fillFieldFluidPresence(TerrainPalettes.of(engine), startX, startZ, blendScratch.fieldHasFluid); + fillFieldFluidPresence(TerrainPalettes.of(engine.getGeneration().world()), startX, startZ, blendScratch.fieldHasFluid); fillFieldObjects(complex.getRegionStream(), startX, startZ, blendScratch.fieldRegions); fillFieldObjects(complex.getTrueBiomeStream(), startX, startZ, blendScratch.fieldSurfaceBiomes); fillFieldObjects(complex.getCaveBiomeStream(), startX, startZ, blendScratch.fieldCaveBiomes); @@ -499,7 +499,8 @@ public class CaveCarving { for (int fieldX = 0; fieldX < FIELD_SIZE; fieldX++) { int worldX = startX + fieldX; for (int fieldZ = 0; fieldZ < FIELD_SIZE; fieldZ++) { - target[(fieldX * FIELD_SIZE) + fieldZ] = B.isFluid(palettes.fluidAt(worldX, startZ + fieldZ)); + com.volmit.block.BlockState fluid = palettes.fluidAt(worldX, startZ + fieldZ); + target[(fieldX * FIELD_SIZE) + fieldZ] = fluid != null && B.isFluid(B.getState(fluid.key())); } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index e0af25ba4..7deea6467 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -67,7 +67,8 @@ public final class CarveModule implements IrisModule { @Override public void install(StageGraph graph) { graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); - graph.define(IrisStages.Carve.APPLY).requires(IrisStages.Terrain.SHAPE).run(CarveModule::applyCaves); + // Ordering only: iris:terrain ships in the built-ins jar, which a pack may not have. + graph.define(IrisStages.Carve.APPLY).softAfter(IrisStages.Terrain.SHAPE.ref()).run(CarveModule::applyCaves); } private static void planCaves(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index acd76e0bc..82f579475 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -22,8 +22,8 @@ import art.arcane.iris.engine.UpperDimensionContext; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.decorator.DecoratedBiome; import art.arcane.iris.engine.decorator.DecorationScene; -import art.arcane.iris.engine.terrain.BiomeLayers; -import art.arcane.iris.engine.terrain.TerrainPalettes; +import art.arcane.iris.builtin.terrain.BiomeLayers; +import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.iris.engine.decorator.IrisCeilingDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; import art.arcane.iris.engine.framework.Engine; @@ -75,8 +75,8 @@ public class CaveApplying { public CaveApplying(Engine engine, ModuleLog log) { this.engine = engine; rng = new RNG(engine.getSeedManager().getCarve()); - layers = BiomeLayers.of(engine, log); - palettes = TerrainPalettes.of(engine); + layers = BiomeLayers.of(engine.getGeneration().world()); + palettes = TerrainPalettes.of(engine.getGeneration().world()); } /** Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}. */ @@ -153,7 +153,7 @@ public class CaveApplying { if (explicitCarveIntent) { // Only a fluid cavern consumes the fluid sample, and on the maintenance path that // sample is a full procedural stream evaluation, so never take it per voxel. - PlatformBlockState fluid = isFluidIntent(cavern) ? palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; + PlatformBlockState fluid = isFluidIntent(cavern) ? IrisLayers.platform(palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz)) : null; output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR)); } else if (usesDefaultLava(caveLavaHeight, yy)) { output.setRaw(rx, yy, rz, LAVA); @@ -180,7 +180,7 @@ public class CaveApplying { : resolveCustomBiome(customBiomeCache, customBiome); if (biome != null) { - PlatformBlockState data = layers.wall(biome).get(rng, worldX, yy, worldZ); + PlatformBlockState data = IrisLayers.platform(layers.wall(IrisLayers.wallOf(biome)).get(rng, worldX, yy, worldZ)); int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { @@ -515,8 +515,8 @@ public class CaveApplying { } if (floorBiome != null) { - KList floorLayers = layers.generateLayers(floorBiome, - engine.getDimension(), worldX, worldZ, rng, 3, zoneFloor, engine.getData(), engine.getComplex()); + KList floorLayers = IrisLayers.platform(layers.generateLayers(IrisLayers.biome(floorBiome), + IrisLayers.explosion(engine.getDimension()), worldX, worldZ, rng, 3, zoneFloor, IrisLayers.slope(engine))); for (int i = 0; i < zoneFloor - 1; i++) { if (!floorLayers.hasIndex(i)) { break; @@ -540,8 +540,8 @@ public class CaveApplying { if (ceilingBiome != null) { int worldMaxY = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - KList ceilingLayers = layers.generateCeilingLayers(ceilingBiome, - engine.getDimension(), worldX, worldZ, rng, 3, zoneCeiling, engine.getData(), engine.getComplex()); + KList ceilingLayers = IrisLayers.platform(layers.generateCeilingLayers(IrisLayers.biome(ceilingBiome), + IrisLayers.explosion(engine.getDimension()), worldX, worldZ, rng, 3)); for (int i = 0; i < ceilingLayers.size(); i++) { int ceilingY = zoneCeiling + i + 1; if (ceilingY >= worldMaxY) { @@ -602,7 +602,7 @@ public class CaveApplying { } if (floorBiome != null) { - KList floorBlocks = layers.generateLayers(floorBiome, engine.getDimension(), xx, zz, rng, 3, zone.floor, engine.getData(), engine.getComplex()); + KList floorBlocks = IrisLayers.platform(layers.generateLayers(IrisLayers.biome(floorBiome), IrisLayers.explosion(engine.getDimension()), xx, zz, rng, 3, zone.floor, IrisLayers.slope(engine))); for (int i = 0; i < zone.floor - 1; i++) { if (!floorBlocks.hasIndex(i)) { break; @@ -622,7 +622,7 @@ public class CaveApplying { } if (ceilingBiome != null) { - KList ceilingBlocks = layers.generateCeilingLayers(ceilingBiome, engine.getDimension(), xx, zz, rng, 3, zone.ceiling, engine.getData(), engine.getComplex()); + KList ceilingBlocks = IrisLayers.platform(layers.generateCeilingLayers(IrisLayers.biome(ceilingBiome), IrisLayers.explosion(engine.getDimension()), xx, zz, rng, 3)); for (int i = 0; i < ceilingBlocks.size(); i++) { int cy = zone.ceiling + i + 1; if (cy >= maxY) { @@ -642,6 +642,9 @@ public class CaveApplying { } DecorationScene scene = SCRATCH.get().decoration; + if (scene == null) { + return; + } if (floorBiome != null) { DecoratedBiome floor = IrisDecoratedBiomes.of(floorBiome, BiomeKind.CAVE); if (scene.decorators().hasDecorators(floor, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz)) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index f6c97f1ea..e1d0c249c 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -27,6 +27,8 @@ import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.IrisComplex; +import art.arcane.iris.builtin.terrain.ExplodeBiomePaletteSizeSettings; +import art.arcane.iris.builtin.terrain.ExplodeBiomePalettesSettings; import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.engine.decorator.FloatingDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; @@ -34,14 +36,14 @@ import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.terrain.BiomeLayers; -import art.arcane.iris.engine.terrain.ResolvedLayer; +import art.arcane.iris.builtin.terrain.BiomeLayers; +import art.arcane.iris.builtin.terrain.LayerNoise; +import art.arcane.iris.builtin.terrain.ResolvedLayer; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.engine.object.world.dimension.IrisDimension; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.iris.util.project.hunk.Hunk; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.MatterBiomeInject; @@ -86,7 +88,7 @@ public class FloatingIslands { int generatorSeed = 7235; for (int i = 0; i < layers.size(); i++) { ResolvedLayer layer = biomeLayers.resolve(layers.get(i)); - CNG heightGenerator = layer.heightNoise(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed)); + LayerNoise heightGenerator = layer.heightNoise(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed)); if (heightGenerator == null) { continue; } @@ -107,7 +109,7 @@ public class FloatingIslands { } try { - generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom())); + generated.add(IrisLayers.platform(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom()))); } catch (Throwable e) { log.error("Failed to pick a block of a floating island's palette", e); } @@ -117,9 +119,11 @@ public class FloatingIslands { break; } - if (dimension != null && dimension.isExplodeBiomePalettes()) { + if (dimension != null && dimension.getModuleSettings().find(ExplodeBiomePalettesSettings.class).map(ExplodeBiomePalettesSettings::explode).orElse(false)) { PlatformBlockState barrier = B.getState("minecraft:barrier"); - for (int j = 0; j < dimension.getExplodeBiomePaletteSize(); j++) { + int gap = dimension.getModuleSettings().find(ExplodeBiomePaletteSizeSettings.class).map(ExplodeBiomePaletteSizeSettings::size) + .orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); + for (int j = 0; j < gap; j++) { generated.add(barrier); if (generated.size() >= maxDepth) { @@ -188,9 +192,9 @@ public class FloatingIslands { IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); int entrySeed = entry == null || entry.settings().biome() == null ? 0 : entry.settings().biome().hashCode(); RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed)); - KList topBlocks = target == null ? null : biomeLayers.generateLayers(target, dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); + KList topBlocks = target == null ? null : IrisLayers.platform(biomeLayers.generateLayers(IrisLayers.biome(target), IrisLayers.explosion(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, IrisLayers.slope(engine))); if (topBlocks == null || topBlocks.isEmpty()) { - topBlocks = biomeLayers.generateLayers(parent, dimension, wx, wz, layerRng, paletteDepth, paletteDepth, data, complex); + topBlocks = IrisLayers.platform(biomeLayers.generateLayers(IrisLayers.biome(parent), IrisLayers.explosion(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, IrisLayers.slope(engine))); } KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex); return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone")); @@ -212,7 +216,7 @@ public class FloatingIslands { this.engine = engine; this.log = log; rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); - biomeLayers = BiomeLayers.of(engine, log); + biomeLayers = BiomeLayers.of(engine.getGeneration().world()); } /** Fills the islands' solids into the chunk whose first block is {@code x}, {@code z}. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java b/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java new file mode 100644 index 000000000..bfd50f4d0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java @@ -0,0 +1,85 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.builtin.terrain.ExplodeBiomePaletteSizeSettings; +import art.arcane.iris.builtin.terrain.ExplodeBiomePalettesSettings; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; +import art.arcane.iris.builtin.terrain.LockLayersSettings; +import art.arcane.iris.builtin.terrain.SeaLayersSettings; +import art.arcane.iris.builtin.terrain.WallSettings; +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.builtin.terrain.ColumnSlope; +import art.arcane.iris.builtin.terrain.LayeredBiome; +import art.arcane.iris.builtin.terrain.PaletteExplosion; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import art.arcane.volmlib.util.collection.KList; +import com.volmit.block.BlockState; + +/** What Iris's carving and floating islands, which hold Iris's own types, hand the terrain's layers and palettes, and take back as the platform's blocks. */ +final class IrisLayers { + private IrisLayers() { + } + + /** What the biome declares about its layers. */ + static LayeredBiome biome(IrisBiome biome) { + return new LayeredBiome( + biome.getModuleSettings().find(LayersSettings.class).orElse(null), + biome.getModuleSettings().find(SeaLayersSettings.class).orElse(null), + biome.getModuleSettings().find(CaveCeilingLayersSettings.class).orElse(null), + biome.getModuleSettings().find(LockLayersSettings.class).orElse(null), + biome.getModuleSettings().find(LockLayersMaxSettings.class).orElse(null), + biome.getModuleSettings().find(WallSettings.class).orElse(null)); + } + + /** The biome with only its wall, for a caller that asks for nothing else. */ + static LayeredBiome wallOf(IrisBiome biome) { + return new LayeredBiome(null, null, null, null, null, biome.getModuleSettings().find(WallSettings.class).orElse(null)); + } + + static PaletteExplosion explosion(IrisDimension dimension) { + if (dimension == null) { + return PaletteExplosion.NONE; + } + return new PaletteExplosion( + dimension.getModuleSettings().find(ExplodeBiomePalettesSettings.class).map(ExplodeBiomePalettesSettings::explode).orElse(false), + dimension.getModuleSettings().find(ExplodeBiomePaletteSizeSettings.class).map(ExplodeBiomePaletteSizeSettings::size) + .orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE)); + } + + static ColumnSlope slope(Engine engine) { + return (x, z) -> engine.getComplex().getSlopeStream().get(x, z); + } + + static PlatformBlockState platform(BlockState block) { + return block == null ? null : B.getState(block.key()); + } + + static KList platform(KList blocks) { + KList converted = new KList<>(blocks.size()); + for (BlockState block : blocks) { + converted.add(platform(block)); + } + return converted; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 35d1b7cb6..56798a229 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -26,7 +26,7 @@ import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.core.modules.IrisPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.terrain.TerrainPalettes; +import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.project.noise.SimplexNoise; @@ -98,7 +98,7 @@ public final class VacuumModule implements IrisModule { this.placement = IrisPlacement.current(); this.prepared = prepared; this.world = new PlacementWorld(context.access(), placement.states()); - this.palettes = engine.getComplex() == null ? null : TerrainPalettes.of(engine); + this.palettes = engine.getComplex() == null ? null : TerrainPalettes.of(engine.getGeneration().world()); VacuumSettings settings = prepared.config().getVacuumSettings(); this.radius = IrisObjectVacuum.resolveRadius(vacuum, settings); this.step = vacuum.columnStepBlocks(); @@ -161,7 +161,8 @@ public final class VacuumModule implements IrisModule { } private void raise(int x, int z, int fromY, int toY) { - PlatformBlockState fill = palettes != null ? palettes.rockAt(x, z) : null; + com.volmit.block.BlockState rock = palettes != null ? palettes.rockAt(x, z) : null; + PlatformBlockState fill = rock != null ? B.getState(rock.key()) : null; if (B.isAir(fill)) { fill = IrisObject.States.STONE; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index d73057b02..bb3b1114d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.object.placement; +import art.arcane.iris.builtin.terrain.BedrockSettings; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.validate.ObjectLimit; @@ -101,7 +102,8 @@ public final class ValidateModule implements IrisModule { private static boolean isOnBedrock(PreparedPlacement prepared, int y) { Engine engine = prepared.terrain().getEngine(); - return engine != null && engine.getDimension().isBedrock() && y <= BEDROCK_ROW; + return engine != null && y <= BEDROCK_ROW + && engine.getDimension().getModuleSettings().find(BedrockSettings.class).map(BedrockSettings::bedrock).orElse(true); } private static boolean lacksSurfaceSupport(IrisPlacement placement, PreparedPlacement prepared) { 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 index 2ba60b158..406b00d48 100644 --- 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 @@ -20,7 +20,8 @@ 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.engine.terrain.BiomeLayers; +import art.arcane.iris.builtin.terrain.LayerLoad; +import art.arcane.iris.builtin.terrain.LayersSettings; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.render.RenderType; @@ -87,8 +88,11 @@ final class IrisBiomeColorRenderer { } case LAYER_LOAD -> { return biome.getCacheColorLayerLoad().aquire(() -> { - BiomeLayers layers = BiomeLayers.of(engine, engine.getGeneration().world().log()); - return Color.getHSBColor(0.625f, (float) (BiomeLayers.layersOf(biome).size() / layers.busiestLayerCount(engine)), 1f); + 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); }); } } @@ -96,6 +100,10 @@ final class IrisBiomeColorRenderer { 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/dimension/IrisDimension.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java index 67db0f231..589b1ce03 100644 --- 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 @@ -111,14 +111,8 @@ public class IrisDimension extends IrisRegistrant { 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("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") - private boolean explodeBiomePalettes = false; @Desc("Studio Mode for testing different parts of the world") private StudioMode studioMode = StudioMode.NORMAL; - @MinNumber(1) - @MaxNumber(16) - @Desc("Customize the palette height explosion") - private int explodeBiomePaletteSize = 3; @MinNumber(2) @MaxNumber(16) @Desc("Every X/Z % debugCrossSectionsMod == 0 cuts the chunk") @@ -128,8 +122,6 @@ public class IrisDimension extends IrisRegistrant { @MinNumber(0) @Desc("The version of this dimension. Changing this will stop users from accidentally upgrading (and breaking their worlds).") private int version = 1; - @Desc("Should bedrock be generated or not.") - private boolean bedrock = true; @MinNumber(0) @MaxNumber(1) @Desc("The land chance. Up to 1.0 for total land or 0.0 for total sea") From 36d464d0a33793c37c67fa1d16bd0a11cf5e86ef Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:57:42 +0200 Subject: [PATCH 082/139] Carve and floating islands read a biome's layers once per biome and convert layer blocks once per block instance; the upper dimension's palette explosion is read once per chunk --- .../iris/engine/actuator/TerrainShaper.java | 11 +++- .../iris/engine/modifier/CaveApplying.java | 18 +++--- .../iris/engine/modifier/FloatingIslands.java | 8 ++- .../iris/engine/modifier/IrisLayers.java | 58 ++++++++++++++----- 4 files changed, 67 insertions(+), 28 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index 894b40636..5a5429466 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -209,7 +209,7 @@ final class TerrainShaper { BlockState upperMappedSurface = upper.surfaceBlock(realX, realZ).orElse(null); int upperThickness = chunkHeight - 1 - upperSurfaceY; LayeredBiome upperBiome = upperBiome(upperSettings, realX, realZ); - KList upperBlocks = layers.generateLayers(upperBiome, PaletteExplosion.of(upperSettings, realX, realZ), + KList upperBlocks = layers.generateLayers(upperBiome, chunk.upperExplosion(upperSettings, realX, realZ), realX, realZ, rng, upperThickness, upperThickness, chunk.slope); for (int y = chunkHeight - 1; y >= upperSurfaceY; y--) { @@ -267,6 +267,7 @@ final class TerrainShaper { final Optional upper; final ResolvedOres dimensionOres; private final boolean hideOres; + private PaletteExplosion upperExplosion; Chunk(ChunkStageContext context) { this.blocks = context.hunk(BlockState.class); @@ -286,6 +287,14 @@ final class TerrainShaper { this.dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(levelValue(settings.at(OreSettings.class, centreX, centreZ), Target.DIMENSION)); } + /** What the upper dimension declares about exploded palettes: a setting of the dimension, so the same for every column of the chunk. */ + PaletteExplosion upperExplosion(FeatureSettings upperSettings, int worldX, int worldZ) { + if (upperExplosion == null) { + upperExplosion = PaletteExplosion.of(upperSettings, worldX, worldZ); + } + return upperExplosion; + } + /** The ores of the column's region and biome; none where the levels below the dimension declare none, or the dimension hides ores. */ ColumnOres oresAt(int worldX, int worldZ) { if (hideOres || !levelsBelowTheDimensionDeclareOres) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 82f579475..dd75aaf2c 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -70,12 +70,14 @@ public class CaveApplying { private final PlatformBlockState AIR = B.getState("CAVE_AIR"); private final PlatformBlockState LAVA = B.getState("LAVA"); private final BiomeLayers layers; + private final IrisLayers glue; private final TerrainPalettes palettes; public CaveApplying(Engine engine, ModuleLog log) { this.engine = engine; rng = new RNG(engine.getSeedManager().getCarve()); layers = BiomeLayers.of(engine.getGeneration().world()); + glue = new IrisLayers(engine); palettes = TerrainPalettes.of(engine.getGeneration().world()); } @@ -153,7 +155,7 @@ public class CaveApplying { if (explicitCarveIntent) { // Only a fluid cavern consumes the fluid sample, and on the maintenance path that // sample is a full procedural stream evaluation, so never take it per voxel. - PlatformBlockState fluid = isFluidIntent(cavern) ? IrisLayers.platform(palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz)) : null; + PlatformBlockState fluid = isFluidIntent(cavern) ? glue.platform(palettes.fluidAt(chunkBlockX + rx, chunkBlockZ + rz)) : null; output.setRaw(rx, yy, rz, resolveExplicitCarveState(cavern, fluid, LAVA, AIR)); } else if (usesDefaultLava(caveLavaHeight, yy)) { output.setRaw(rx, yy, rz, LAVA); @@ -180,7 +182,7 @@ public class CaveApplying { : resolveCustomBiome(customBiomeCache, customBiome); if (biome != null) { - PlatformBlockState data = IrisLayers.platform(layers.wall(IrisLayers.wallOf(biome)).get(rng, worldX, yy, worldZ)); + PlatformBlockState data = glue.platform(layers.wall(IrisLayers.wallOf(biome)).get(rng, worldX, yy, worldZ)); int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); if (data != null && B.isSolid(output.getRaw(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { @@ -515,8 +517,8 @@ public class CaveApplying { } if (floorBiome != null) { - KList floorLayers = IrisLayers.platform(layers.generateLayers(IrisLayers.biome(floorBiome), - IrisLayers.explosion(engine.getDimension()), worldX, worldZ, rng, 3, zoneFloor, IrisLayers.slope(engine))); + KList floorLayers = glue.platform(layers.generateLayers(glue.biome(floorBiome), + glue.explosion(), worldX, worldZ, rng, 3, zoneFloor, glue.slope())); for (int i = 0; i < zoneFloor - 1; i++) { if (!floorLayers.hasIndex(i)) { break; @@ -540,8 +542,8 @@ public class CaveApplying { if (ceilingBiome != null) { int worldMaxY = engine.getWorld().maxHeight() - engine.getWorld().minHeight(); - KList ceilingLayers = IrisLayers.platform(layers.generateCeilingLayers(IrisLayers.biome(ceilingBiome), - IrisLayers.explosion(engine.getDimension()), worldX, worldZ, rng, 3)); + KList ceilingLayers = glue.platform(layers.generateCeilingLayers(glue.biome(ceilingBiome), + glue.explosion(), worldX, worldZ, rng, 3)); for (int i = 0; i < ceilingLayers.size(); i++) { int ceilingY = zoneCeiling + i + 1; if (ceilingY >= worldMaxY) { @@ -602,7 +604,7 @@ public class CaveApplying { } if (floorBiome != null) { - KList floorBlocks = IrisLayers.platform(layers.generateLayers(IrisLayers.biome(floorBiome), IrisLayers.explosion(engine.getDimension()), xx, zz, rng, 3, zone.floor, IrisLayers.slope(engine))); + KList floorBlocks = glue.platform(layers.generateLayers(glue.biome(floorBiome), glue.explosion(), xx, zz, rng, 3, zone.floor, glue.slope())); for (int i = 0; i < zone.floor - 1; i++) { if (!floorBlocks.hasIndex(i)) { break; @@ -622,7 +624,7 @@ public class CaveApplying { } if (ceilingBiome != null) { - KList ceilingBlocks = IrisLayers.platform(layers.generateCeilingLayers(IrisLayers.biome(ceilingBiome), IrisLayers.explosion(engine.getDimension()), xx, zz, rng, 3)); + KList ceilingBlocks = glue.platform(layers.generateCeilingLayers(glue.biome(ceilingBiome), glue.explosion(), xx, zz, rng, 3)); for (int i = 0; i < ceilingBlocks.size(); i++) { int cy = zone.ceiling + i + 1; if (cy >= maxY) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index e1d0c249c..575d6c8ec 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -70,6 +70,7 @@ public class FloatingIslands { private final Engine engine; private final RNG rng; private final BiomeLayers biomeLayers; + private final IrisLayers glue; private final ModuleLog log; private KList generateBottomPaletteLayers(ResolvedFloatingChild entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { @@ -109,7 +110,7 @@ public class FloatingIslands { } try { - generated.add(IrisLayers.platform(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom()))); + generated.add(glue.platform(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom()))); } catch (Throwable e) { log.error("Failed to pick a block of a floating island's palette", e); } @@ -192,9 +193,9 @@ public class FloatingIslands { IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); int entrySeed = entry == null || entry.settings().biome() == null ? 0 : entry.settings().biome().hashCode(); RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed)); - KList topBlocks = target == null ? null : IrisLayers.platform(biomeLayers.generateLayers(IrisLayers.biome(target), IrisLayers.explosion(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, IrisLayers.slope(engine))); + KList topBlocks = target == null ? null : glue.platform(biomeLayers.generateLayers(glue.biome(target), IrisLayers.explosionOf(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, glue.slope())); if (topBlocks == null || topBlocks.isEmpty()) { - topBlocks = IrisLayers.platform(biomeLayers.generateLayers(IrisLayers.biome(parent), IrisLayers.explosion(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, IrisLayers.slope(engine))); + topBlocks = glue.platform(biomeLayers.generateLayers(glue.biome(parent), IrisLayers.explosionOf(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, glue.slope())); } KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex); return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone")); @@ -217,6 +218,7 @@ public class FloatingIslands { this.log = log; rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); biomeLayers = BiomeLayers.of(engine.getGeneration().world()); + glue = new IrisLayers(engine); } /** Fills the islands' solids into the chunk whose first block is {@code x}, {@code z}. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java b/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java index bfd50f4d0..7427ad2fb 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java @@ -36,20 +36,35 @@ import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.collection.KList; import com.volmit.block.BlockState; -/** What Iris's carving and floating islands, which hold Iris's own types, hand the terrain's layers and palettes, and take back as the platform's blocks. */ +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Map; + +/** + * What Iris's carving and floating islands, which hold Iris's own types, hand the terrain's layers and palettes, and take back as the + * platform's blocks. One per engine: what a biome declares about its layers is read once for each biome. + */ final class IrisLayers { - private IrisLayers() { + private final Engine engine; + private final Map biomes = Collections.synchronizedMap(new IdentityHashMap<>()); + private final Map platformStates = Collections.synchronizedMap(new IdentityHashMap<>()); + private final ColumnSlope slope; + private volatile PaletteExplosion explosion; + + IrisLayers(Engine engine) { + this.engine = engine; + this.slope = (x, z) -> engine.getComplex().getSlopeStream().get(x, z); } /** What the biome declares about its layers. */ - static LayeredBiome biome(IrisBiome biome) { - return new LayeredBiome( - biome.getModuleSettings().find(LayersSettings.class).orElse(null), - biome.getModuleSettings().find(SeaLayersSettings.class).orElse(null), - biome.getModuleSettings().find(CaveCeilingLayersSettings.class).orElse(null), - biome.getModuleSettings().find(LockLayersSettings.class).orElse(null), - biome.getModuleSettings().find(LockLayersMaxSettings.class).orElse(null), - biome.getModuleSettings().find(WallSettings.class).orElse(null)); + LayeredBiome biome(IrisBiome biome) { + return biomes.computeIfAbsent(biome, declared -> new LayeredBiome( + declared.getModuleSettings().find(LayersSettings.class).orElse(null), + declared.getModuleSettings().find(SeaLayersSettings.class).orElse(null), + declared.getModuleSettings().find(CaveCeilingLayersSettings.class).orElse(null), + declared.getModuleSettings().find(LockLayersSettings.class).orElse(null), + declared.getModuleSettings().find(LockLayersMaxSettings.class).orElse(null), + declared.getModuleSettings().find(WallSettings.class).orElse(null))); } /** The biome with only its wall, for a caller that asks for nothing else. */ @@ -57,7 +72,17 @@ final class IrisLayers { return new LayeredBiome(null, null, null, null, null, biome.getModuleSettings().find(WallSettings.class).orElse(null)); } - static PaletteExplosion explosion(IrisDimension dimension) { + /** What the engine's dimension declares about separating layers with barriers. */ + PaletteExplosion explosion() { + PaletteExplosion known = explosion; + if (known == null) { + known = explosionOf(engine.getDimension()); + explosion = known; + } + return known; + } + + static PaletteExplosion explosionOf(IrisDimension dimension) { if (dimension == null) { return PaletteExplosion.NONE; } @@ -67,15 +92,16 @@ final class IrisLayers { .orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE)); } - static ColumnSlope slope(Engine engine) { - return (x, z) -> engine.getComplex().getSlopeStream().get(x, z); + ColumnSlope slope() { + return slope; } - static PlatformBlockState platform(BlockState block) { - return block == null ? null : B.getState(block.key()); + /** The platform's block for {@code block}, worked out once for each block instance, since a world's layers hold few. */ + PlatformBlockState platform(BlockState block) { + return block == null ? null : platformStates.computeIfAbsent(block, known -> B.getState(known.key())); } - static KList platform(KList blocks) { + KList platform(KList blocks) { KList converted = new KList<>(blocks.size()); for (BlockState block : blocks) { converted.add(platform(block)); From f0fcfbe30480e47bff3969feb69afad900c47099 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 12 Oct 2026 02:57:57 +0200 Subject: [PATCH 083/139] README and package docs: decorant, terrain and deposit in the jar, their new dimension keys, the shared layer classes --- README.md | 19 +++++++++++++------ .../art/arcane/iris/builtin/package-info.java | 3 ++- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3c3ad9e5f..3df560ec5 100644 --- a/README.md +++ b/README.md @@ -58,13 +58,15 @@ The settings of both modules are `builtin.loot` and `builtin.spawn` types of Iri `iris:spawn` declares `entitySpawners` (list of spawner keys) for the same and `effects` (list, `iris:spawn/effects`) for regions and biomes. The loot tables, spawners, entities and markers are plain module types too (`LootTable`, `Spawner`, `EntityDefinition`, `SpawnMarker`). `PlacementLoot` picks the table an object placement gives one of its chests. -`iris:decorant` keeps its per-world `Decorating` in the world's state store (`context.world().state(...)`); the other -built-ins still reach the same store through `IrisChunk.state(...)` / `engine.getGeneration().state(...)`. +`iris:decorant`, `iris:terrain` and `iris:deposit` ship in the built-ins jar and keep their per-world workers (`BiomeDecorators`, `TerrainShaper`, +`DepositPlacer`) in the world's state store (`context.world().state(...)`); the modules still compiled into Iris reach the same store through +`IrisChunk.state(...)` / `engine.getGeneration().state(...)`. Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in `art.arcane.iris.builtin.deposit`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the -palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. +palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. The deposits run one generator after the other, each +with a random of its own; they used to spread over threads on a multicore pregen, which no module can do (stages run on the host's threads). Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, @@ -76,7 +78,9 @@ worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `Reso `iris:decorant` is the second: `DecorantSettings` (biome level) holds `Decorator`s in `art.arcane.iris.builtin.decorant`, written `"decorators": [...]` as always (`@Feature(key = "decorators", root = "decorators")`). `ResolvedDecorator` resolves one decorator's blocks and noise for a world; `BiomeDecorators`, the world's state, keeps them -per biome and place. Other modules that decorate (`iris:cave`'s ceilings, floating islands) ask it. A decorator's noise +per biome and place. A chunk's decorators place into a `DecorationScene` (its blocks, the planned blocks around it, the terrain and the pack's block +rules); other modules that decorate (the caves' floors and ceilings, floating islands) build one from their chunk's stage context. Whether a +dimension decorates at all is its `decorate` key (`DecorateSettings`). A decorator's noise seed is the world's decorator seed, its biome's key and its place in the biome's list. The module's `warmUp` builds them ahead of generation; `iris:terrain` and `iris:objects` warm their ore generators, placements and procedural objects the same way. @@ -84,10 +88,13 @@ objects the same way. `iris:terrain` and `iris:post` own the fields that shape a column's blocks. Per biome: `layers`, `seaLayers`, `caveCeilingLayers` (lists of `PaletteLayer`, the old biome palette layer, in `art.arcane.iris.builtin.terrain`), `slab` and `wall` (one `PaletteLayer` each), `lockLayers` (a boolean) and `lockLayersMax` (a number). Per dimension: `rockPalette` and `fluidPalette` (a `PaletteSpec` each) in `art.arcane.iris.builtin.terrain`, and -`postProcessing`, `postProcessingSlabs`, `postProcessingWalls` (booleans) in `art.arcane.iris.builtin.post`. A key a pack leaves out has the +`postProcessing`, `postProcessingSlabs`, `postProcessingWalls` (booleans) in `art.arcane.iris.builtin.post`; `bedrock`, `explodeBiomePalettes` and +`explodeBiomePaletteSize` are dimension keys of `iris:terrain` too. A key a pack leaves out has the default Iris always had (one grass layer, no slab or wall, stone and water, post processing on). `ResolvedLayer` resolves one layer's blocks and noise for a pack, `BiomeLayers`, the world's state, keeps them and stacks a biome's layers into the blocks of a column, and `TerrainPalettes` is the world's -rock and fluid as a block for every column; the terrain, cave, floating and post stages ask them. The slope limit of a layer, a decorator and an +rock and fluid as a block for every column; the terrain, cave, floating and post stages ask them. Both live in `art.arcane.iris.builtin.terrain`, which +Iris exposes, so the jar's terrain and the carving compiled into Iris share one copy of them: a biome's layer thickness noise is built once, from the random +of whoever asks first, as it always was. The slope limit of a layer, a decorator and an object placement is the one `SlopeClip`. Caves, floating islands and ores are settings of their modules too, written under the keys they always had. `iris:carve` owns diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 4e62e77b1..c667ed488 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -30,7 +30,8 @@ * Besides those, it holds what the compiled-in built-ins and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement * ({@link art.arcane.iris.builtin.IrisSeed}), and per-world state several of them use - * ({@link art.arcane.iris.builtin.terrain.LayerBlocks}). Keep them few: each is a promise. + * ({@link art.arcane.iris.builtin.terrain.LayerBlocks}, {@link art.arcane.iris.builtin.terrain.BiomeLayers}, + * {@link art.arcane.iris.builtin.terrain.TerrainPalettes}). Keep them few: each is a promise. *

* Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A * pack module can require such a stage to run after it, but cannot read its output: the pack load rejects From 182bb12cbca66d1fb816f67828d95c05d64e894b Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 07:08:44 +0200 Subject: [PATCH 084/139] iris:objects docs for the objects facade; ResolvedTree and ResolvedProceduralObjects drop what nothing reads; EffectivePlacements says what the dimension really does --- README.md | 10 ++++++++++ .../art/arcane/iris/builtin/package-info.java | 2 +- .../mantle/components/ChunkObjectPlacing.java | 17 ++++++----------- .../mantle/components/EffectivePlacements.java | 2 +- .../procedural/ResolvedProceduralObjects.java | 9 +-------- .../object/procedural/tree/ResolvedTree.java | 5 ----- 6 files changed, 19 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 3c3ad9e5f..3bc9a7759 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,16 @@ chunk it reaches and every restart fits it the same way. Object place modes are stilt, `VacuumProfile`, `PlaceTrait`s) that the placement stages ask; the pack JSON keeps the mode names. `iris:objects` also provides `SaplingGrowth` (`TreeGrowing`: the tree a sapling grows into, as placed blocks, and which objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). +`iris:objects` ships in the built-ins jar. It declares the settings `objects` (region, biome: the list of `ObjectPlacement`s), +`proceduralObjects` (region, biome), `treeSettings` (dimension), `requireObjectSurfaceSupport`, `objectSurfaceSupportBuffer`, +`upperDimensionObjects` and `upperObjectsForcePlace` (dimension), all written as they always were. `ObjectPlacement` describes +the same JSON as Iris's `IrisObjectPlacement` and keeps the JSON it was read from, because Iris's placement stages still read +a placement as their own class (`ObjectPlacements.host`). What a jar cannot do, Iris does through the facades `ObjectHost` and +`ObjectChunk` in `art.arcane.iris.builtin.objects`: loading and scaling the pack's objects, placing one with the placement +stages into the chunk's mantle (on the surface, in a cave inside the cave's bounds, or hung from the terrain above), reading the +carved space the cave carver planned, and the layout around a position. `ObjectPlacing` and its helpers (`ChunkObjectPlacing`, +`CaveAnchors`, `PlacementReach`) decide what to place and where. The procedural generators (`engine/object/procedural`) stay +compiled in, behind `ProceduralPlacement`, until they build `GeneratedObject`s instead of Iris objects. `iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to them (`LootValidator`), and provides `Loot` (`LootGiving`: which tables a container draws from and the `ItemDrop`s a table gives) and `BlockDrops` (`BlockDropping`). `iris:spawn` owns spawners, entities and markers (`SpawnResources`, diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 4e62e77b1..b609b5b97 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -29,7 +29,7 @@ *

* Besides those, it holds what the compiled-in built-ins and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.IrisSeed}), and per-world state several of them use + * ({@link art.arcane.iris.builtin.IrisSeed}, {@link art.arcane.iris.builtin.objects.ObjectHost}), and per-world state several of them use * ({@link art.arcane.iris.builtin.terrain.LayerBlocks}). Keep them few: each is a promise. *

* Some built-in stages produce Iris's own types, such as the placement settings of {@code iris:prepare}. A diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 677f0aba4..eb8338d9e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -461,7 +461,7 @@ final class ChunkObjectPlacing { private void placeProceduralVariant(ProceduralPlacement placement, PlaceableObject variant, String scope, CaveProfile caveProfile, CaveAnchors.Search search, CaveAnchors.Anchor anchor, int x, int z, int id) { String goldenTag = golden ? scope + "/" + placement.name() : null; - PlacementTags tags = tags(variant, id, "procedural", placement.tree(), placement, false); + PlacementTags tags = tags(variant, id, "procedural", placement.tree(), false); int resultY; String commit = "n/a"; if (anchor != null) { @@ -556,11 +556,10 @@ final class ChunkObjectPlacing { } private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement) { - return tags(object, id, context, treePlacement, placement, placement.isDolphinTarget() && placement.underwater()); + return tags(object, id, context, treePlacement, placement.isDolphinTarget() && placement.underwater()); } - private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement, - boolean buriedTreasure) { + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, boolean buriedTreasure) { return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure); } @@ -608,15 +607,15 @@ final class ChunkObjectPlacing { } private void logCaveDiagnostics(Column column) { - CarvedCount carved = new CarvedCount(); + int carvedBlocks = 0; int maxY = Math.min(worldHeight - 1, column.surfaceY() - DIAGNOSTIC_SURFACE_MARGIN); for (int y = 1; y < maxY; y++) { if (chunk.carved().isCarved(centerX, y, centerZ)) { - carved.blocks++; + carvedBlocks++; } } log.debug("Cave object diag: chunk=" + chunkX + "," + chunkZ + " surfaceBiome=" + column.surface() + " caveBiome=" + column.cave() - + " surfaceY=" + column.surfaceY() + " maxAnchorY=" + maxY + " carvedAtCenter=" + carved.blocks + + " surfaceY=" + column.surfaceY() + " maxAnchorY=" + maxY + " carvedAtCenter=" + carvedBlocks + " biomeCarvingObjects=" + carvingObjects(column.objects().cave()).size() + " regionCarvingObjects=" + carvingObjects(column.objects().region()).size() + " sameBiome=" + column.cave().equals(column.surface())); @@ -649,10 +648,6 @@ final class ChunkObjectPlacing { private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) { } - private static final class CarvedCount { - private int blocks; - } - /** What placing the objects of a chunk came to. */ private static final class Tally { private final java.util.Map scopes = new java.util.LinkedHashMap<>(); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java index 22315d331..6979b60f1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -78,7 +78,7 @@ final class EffectivePlacements { return key.toLowerCase(Locale.ROOT).contains(IMPORTS_FOLDER); } - /** The dimension acts as the floor: it can force support on and widen the buffer, never weaken either. */ + /** The dimension widens the buffer of a placement, never narrows it, and its support requirement applies on top of the placement's own: both have to want it. */ private PlacementChanges withDimensionSurfaceSupport(PlacementSource placement, PlacementChanges changes) { boolean require = placement.requireSurfaceSupport() && dimensionRequiresSurfaceSupport; int buffer = Math.max(placement.surfaceSupportBuffer(), dimensionSurfaceSupportBuffer); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java index e2109ace6..1c294004e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java @@ -34,13 +34,10 @@ import java.util.function.Function; /** The procedural objects a region or biome declares, each made placeable once, in the order the settings list them. */ public final class ResolvedProceduralObjects { private final KList all = new KList<>(); - private final KList trees = new KList<>(); public ResolvedProceduralObjects(ProceduralObjectSettings settings) { for (Tree tree : settings.trees()) { - ResolvedTree resolved = new ResolvedTree(tree); - trees.add(resolved); - all.add(resolved); + all.add(new ResolvedTree(tree)); } addAll(settings.ruins(), ResolvedRuin::new); addAll(settings.formations(), ResolvedFormation::new); @@ -59,10 +56,6 @@ public final class ResolvedProceduralObjects { return all; } - public KList getTrees() { - return trees; - } - public boolean isEmpty() { return all.isEmpty(); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java index 36b493834..3a6004d29 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.spi.IrisLogging; @@ -48,10 +47,6 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { return Tree.variantLoadKey(settings.name(), index); } - public Tree settings() { - return settings; - } - @Override public boolean isPlausible() { return settings.plausible(); From 3eb987680e44e355f527822e3861930bbca87530 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 07:23:42 +0200 Subject: [PATCH 085/139] Carve dresses caves with the terrain and decorant built-ins' layers, palettes and decorators directly, now that all three ship in the jar: CaveDressing becomes carve's own seam --- README.md | 6 +- builtin-modules.txt | 2 + .../art/arcane/iris/builtin/CaveDressing.java | 88 -------------- .../engine/mantle/components/CaveCarving.java | 15 ++- .../engine/modifier/BuiltInCaveDressing.java | 111 ++++++++++++++++++ .../iris/engine/modifier/CarveModule.java | 17 ++- .../iris/engine/modifier/CaveApplying.java | 31 ++--- .../iris/engine/modifier/CaveDressing.java | 55 +++++++++ 8 files changed, 212 insertions(+), 113 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/CaveDressing.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java create mode 100644 src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java diff --git a/README.md b/README.md index 180280cfe..5eb1b32c7 100644 --- a/README.md +++ b/README.md @@ -184,9 +184,9 @@ placement's own states). Its types answer with IrisApi, VolmLib and built-in val (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. `iris:carve` also reads the mantle's matter slices through `MatterMantle` (a facade Iris's mantle implements: the chunk of -`MatterCavern`s and markers it plans and applies, which the platform and the rest of Iris read as slices, not as module layers) and asks -`CaveDressing` for what the biome layers, decorators and fluid palette give a cave's walls, floor and ceiling. `CaveDressing` is -transitional: it goes when `iris:terrain` and `iris:decorant` are modules of the same jar and carve asks their classes directly. +`MatterCavern`s and markers it plans and applies, which the platform and the rest of Iris read as slices, not as module layers). What a +cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`terrain.BiomeLayers`, +`terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its absolute world Y bands convert with `PackWorld.minHeight()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read) and `scaled(...)`. `caveLavaHeight` and `upperDimensionCarving` are its dimension settings. diff --git a/builtin-modules.txt b/builtin-modules.txt index f1fa10c09..0ac32e0b4 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -41,6 +41,8 @@ module art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule include art/arcane/iris/engine/framework/vanillafeatures/** module art.arcane.iris.engine.modifier.CarveModule include art/arcane/iris/engine/modifier/CaveApplying*.class +include art/arcane/iris/engine/modifier/CaveDressing.class +include art/arcane/iris/engine/modifier/BuiltInCaveDressing.class include art/arcane/iris/engine/modifier/CaveBiomeBands*.class include art/arcane/iris/engine/modifier/CaveBiomeCache.class include art/arcane/iris/engine/modifier/CaveBlockClasses.class diff --git a/src/main/java/art/arcane/iris/builtin/CaveDressing.java b/src/main/java/art/arcane/iris/builtin/CaveDressing.java deleted file mode 100644 index 14afe16e0..000000000 --- a/src/main/java/art/arcane/iris/builtin/CaveDressing.java +++ /dev/null @@ -1,88 +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.builtin; - -import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.block.BlockState; -import com.volmit.hunk.Hunk; -import com.volmit.resource.ResourceId; -import com.volmit.world.PackWorld; - -import java.util.List; - -/** - * What a cave's floor, ceiling and walls get from the rest of Iris's terrain and decoration: the blocks of a biome's layers - * and wall, its decorators and the fluid of the dimension's palette. Those features keep their workers per world and are - * ported on their own; until they are modules this narrow interface is the one thing {@code iris:carve} needs from them, in - * IrisApi's types, and Iris's worlds implement it ({@link Source}). - * - *

Transitional: when {@code iris:terrain} and {@code iris:decorant} are modules of the same jar, {@code iris:carve} asks - * their classes directly and this interface goes. - * - *

The methods that give a block take the {@code chunk} hunk the block is for. A block read from here and written to that - * hunk keeps the identity of a content plugin's custom block, as it did when the layers wrote the platform's states themselves. - */ -public interface CaveDressing { - /** The dressing of {@code world}, which must be a world Iris generates. */ - static CaveDressing of(PackWorld world) { - if (world instanceof Source source) { - return source.caveDressing(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); - } - - /** Iris's worlds answer for their dressing. */ - interface Source { - CaveDressing caveDressing(); - } - - /** Whether the dimension's fluid palette gives a fluid (water, lava) at the column; false where it gives none. */ - boolean fluidPresentAt(int x, int z); - - /** The block the dimension's fluid palette gives at the column; null where it gives none. */ - BlockState fluidAt(Hunk chunk, int x, int z); - - /** The block the biome's wall gives at the position; null where the biome has no wall or the layer gives none. */ - BlockState wall(Hunk chunk, ResourceId biome, RNG rng, int x, int y, int z); - - /** The blocks the biome's surface layers stack up to at the column, top first, at most {@code depth} of them. */ - List floorLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int floorY); - - /** The blocks the biome's cave ceiling layers stack up to at the column, nearest the ceiling first, at most {@code depth} of them. */ - List ceilingLayers(Hunk chunk, ResourceId biome, int x, int z, RNG rng, int depth, int ceilingY); - - /** Whether the biome has a decorator for {@code part}. */ - boolean hasDecorators(ResourceId biome, DecorationPart part); - - /** - * Decorates a cave's floor in the column at {@code chunk}'s {@code localX}, {@code localZ} (world {@code x}, {@code z}) above - * the block at {@code floorY}, with the biome's decorators for {@link DecorationPart#NONE}, in a space {@code airThickness} high. - */ - void decorateFloor(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness); - - /** Decorates a cave's ceiling the same way, from the block at {@code ceilingY} down, with the decorators for {@link DecorationPart#CEILING}. */ - void decorateCeiling(Hunk chunk, int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness); - - /** - * {@code layer}, the block a layer wants in the place of the ore {@code existing}, as the deepslate or the stone variant - * of the ore that fits the rock {@code existing} is; {@code layer} itself where it has no variant. - */ - BlockState deepSlateOre(Hunk chunk, BlockState existing, BlockState layer); -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 94745233d..2cebe417d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.CaveDressing; import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; @@ -63,7 +62,7 @@ public class CaveCarving { private final CarveWorld world; private final DeclaredCaveProfiles declaredProfiles; private final CarvingResolver resolver; - private final CaveDressing dressing; + private final FluidColumns fluidColumns; private final boolean upperDimensionCarving; private final Object profileCarverLock = new Object(); private volatile Map profileCarvers = new IdentityHashMap<>(); @@ -81,11 +80,17 @@ public class CaveCarving { } } - public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving) { + /** Whether the dimension's fluid palette gives a column a fluid, which caves near it blend towards. */ + @FunctionalInterface + public interface FluidColumns { + boolean hasFluid(int worldX, int worldZ); + } + + public CaveCarving(PackWorld packWorld, CarveWorld world, boolean upperDimensionCarving, FluidColumns fluidColumns) { this.world = world; this.declaredProfiles = DeclaredCaveProfiles.of(packWorld); this.resolver = CarvingResolver.of(packWorld); - this.dressing = CaveDressing.of(packWorld); + this.fluidColumns = fluidColumns; this.upperDimensionCarving = upperDimensionCarving; } @@ -430,7 +435,7 @@ public class CaveCarving { int worldZ = startZ + fieldZ; int fieldIndex = (fieldX * FIELD_SIZE) + fieldZ; blendScratch.fieldSurfaceHeights[fieldIndex] = terrain.surfaceY(worldX, worldZ); - blendScratch.fieldHasFluid[fieldIndex] = dressing.fluidPresentAt(worldX, worldZ); + blendScratch.fieldHasFluid[fieldIndex] = fluidColumns.hasFluid(worldX, worldZ); } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java b/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java new file mode 100644 index 000000000..e7ed1001a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java @@ -0,0 +1,111 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.iris.builtin.terrain.BiomeLayers; +import art.arcane.iris.builtin.terrain.ColumnSlope; +import art.arcane.iris.builtin.terrain.PaletteExplosion; +import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; +import art.arcane.iris.engine.decorator.DecorationScene; +import art.arcane.iris.engine.decorator.IrisCeilingDecorator; +import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; +import com.volmit.world.BiomeKind; +import com.volmit.world.TerrainSampler; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** A chunk's {@link CaveDressing} from the world's biome layers, terrain palettes and decorators, which carving shares with the terrain and decorant built-ins. */ +final class BuiltInCaveDressing implements CaveDressing { + private final BiomeLayers layers; + private final TerrainPalettes palettes; + private final FeatureSettings settings; + private final BlockRegistry blocks; + private final PaletteExplosion explosion; + private final ColumnSlope slope; + private final DecorationScene scene; + private final Map decoratedBiomes = new HashMap<>(); + + BuiltInCaveDressing(ChunkStageContext context) { + TerrainSampler terrain = context.terrain(); + this.layers = BiomeLayers.of(context.world()); + this.palettes = TerrainPalettes.of(context.world()); + this.settings = context.settings(); + this.blocks = context.resources().blocks(); + this.explosion = PaletteExplosion.of(settings, context.originX(), context.originZ()); + this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); + this.scene = DecorationScene.of(context); + } + + @Override + public BlockState fluidAt(int x, int z) { + return palettes.fluidAt(x, z); + } + + @Override + public BlockState wall(ResourceId biome, RNG rng, int x, int y, int z) { + return layers.wall(layers.biome(biome, settings)).get(rng, x, y, z); + } + + @Override + public List floorLayers(ResourceId biome, int x, int z, RNG rng, int depth, int floorY) { + return layers.generateLayers(layers.biome(biome, settings), explosion, x, z, rng, depth, floorY, slope); + } + + @Override + public List ceilingLayers(ResourceId biome, int x, int z, RNG rng, int depth) { + return layers.generateCeilingLayers(layers.biome(biome, settings), explosion, x, z, rng, depth); + } + + @Override + public boolean hasDecorators(ResourceId biome, DecorationPart part) { + return scene.decorators().hasDecorators(decorated(biome), part); + } + + @Override + public void decorateFloor(int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness) { + new IrisSurfaceDecorator(scene).decorate(localX, localZ, x, x, x, z, z, z, decorated(biome), floorY, airThickness); + } + + @Override + public void decorateCeiling(int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness) { + new IrisCeilingDecorator(scene).decorate(localX, localZ, x, x, x, z, z, z, decorated(biome), ceilingY, airThickness); + } + + @Override + public BlockState oreFor(BlockState rock, BlockState ore) { + return blocks.oreFor(rock, ore); + } + + /** The decorators' view of a cave biome: what it declares, under the key its settings come from, as other decorated biomes are. */ + private DecoratedBiome decorated(ResourceId biome) { + return decoratedBiomes.computeIfAbsent(biome, id -> new DecoratedBiome(BiomeDecorators.biomeKey(id), + settings.declaredBy(id, DecorantSettings.class).orElse(null), BiomeKind.CAVE)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 0c484456d..eddf4d1a4 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -28,6 +28,7 @@ import art.arcane.iris.builtin.carve.CaveDepthSettings; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings; +import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.iris.engine.mantle.components.CaveCarving; import com.volmit.FeatureRegistry; @@ -38,7 +39,9 @@ import com.volmit.config.FeatureSettings; import com.volmit.config.FeatureSettings.Entry; import com.volmit.FeatureAttachment.Target; import com.volmit.hunk.Hunk; +import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import com.volmit.service.CaveBiomes; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; @@ -99,12 +102,12 @@ public final class CarveModule implements IrisModule { MatterMantle mantle = MatterMantle.of(context.mantle()); Hunk blocks = context.hunk(BlockState.class); caveApplying(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) - .apply(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT, blocks); + .apply(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT, blocks, CaveDressing.of(context)); } private static CaveCarving caveCarving(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { return world.state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, terrain), - upperDimensionCarving(settings, originX, originZ))); + upperDimensionCarving(settings, originX, originZ), fluidColumns(generating))); } private static CaveApplying caveApplying(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { @@ -112,6 +115,16 @@ public final class CarveModule implements IrisModule { upperDimensionCarving(settings, originX, originZ))); } + /** The columns the dimension's fluid palette fills with a fluid. */ + private static CaveCarving.FluidColumns fluidColumns(PackWorld world) { + TerrainPalettes palettes = TerrainPalettes.of(world); + BlockRegistry blocks = world.resources().blocks(); + return (worldX, worldZ) -> { + BlockState fluid = palettes.fluidAt(worldX, worldZ); + return fluid != null && blocks.hasTrait(fluid, BlockTrait.FLUID); + }; + } + /** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */ private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) { int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index a939da5e5..5d77c7741 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.CaveDressing; import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; @@ -66,7 +65,6 @@ public class CaveApplying { private final CarveWorld world; private final PackResources resources; private final BlockRegistry blocks; - private final CaveDressing dressing; private final boolean upperDimensionCarving; private final RNG rng; private final BlockState caveAir; @@ -77,7 +75,6 @@ public class CaveApplying { this.world = world; this.resources = packWorld.resources(); this.blocks = resources.blocks(); - this.dressing = CaveDressing.of(packWorld); this.upperDimensionCarving = upperDimensionCarving; this.rng = new RNG(world.carveSeed()); this.caveAir = blocks.resolve("minecraft:cave_air"); @@ -87,14 +84,15 @@ public class CaveApplying { /** * Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}, whose blocks are {@code output}; the caves are in - * {@code mantle}, and {@code terrain} gives the heights and cave biomes around the chunk. + * {@code mantle}, {@code terrain} gives the heights and cave biomes around the chunk and {@code dressing} what its caves' walls, + * floors and ceilings get. */ - public void apply(MatterMantle mantle, TerrainSampler terrain, int x, int z, Hunk output) { + public void apply(MatterMantle mantle, TerrainSampler terrain, int x, int z, Hunk output, CaveDressing dressing) { MantleChunk mantleChunk = mantle.chunk(x, z); if (mantleChunk == null) { return; } - new Application(mantle, mantleChunk, terrain, x, z, output).run(); + new Application(mantle, mantleChunk, terrain, x, z, output, dressing).run(); } static boolean hasExplicitCarveIntent(MatterCavern cavern) { @@ -153,17 +151,20 @@ public class CaveApplying { private final int chunkX; private final int chunkZ; private final Hunk output; + private final CaveDressing dressing; private final CaveBlockClasses classes = new CaveBlockClasses(blocks); private final CaveBiomeCache caveBiomeCache = new CaveBiomeCache(CAVE_BIOME_CACHE_SIZE); private final IrisCarveScratch scratch = SCRATCH.get(); - Application(MatterMantle mantle, MantleChunk mantleChunk, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output) { + Application(MatterMantle mantle, MantleChunk mantleChunk, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output, + CaveDressing dressing) { this.mantle = mantle; this.mantleChunk = mantleChunk; this.terrain = terrain; this.chunkX = chunkX; this.chunkZ = chunkZ; this.output = output; + this.dressing = dressing; } void run() { @@ -226,7 +227,7 @@ public class CaveApplying { if (explicitCarveIntent) { // Only a fluid cavern consumes the fluid sample, so never take it per voxel. - BlockState fluid = isFluidIntent(cavern) ? dressing.fluidAt(output, chunkBlockX + rx, chunkBlockZ + rz) : null; + BlockState fluid = isFluidIntent(cavern) ? dressing.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; BlockState carved = resolveExplicitCarveState(cavern, fluid, lava, caveAir); output.set(rx, yy, rz, carved == null ? plainAir : carved); } else if (usesDefaultLava(caveLavaHeight, yy)) { @@ -251,7 +252,7 @@ public class CaveApplying { : resolveCustomBiome(customBiomeCache, customBiome); if (biome != null) { - BlockState data = dressing.wall(output, biome, rng, worldX, yy, worldZ); + BlockState data = dressing.wall(biome, rng, worldX, yy, worldZ); int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); if (data != null && classes.isSolid(output.get(rx, yy, rz)) && yy < surfaceHeights[columnIndex]) { @@ -496,7 +497,7 @@ public class CaveApplying { /** Replaces the solid blocks under {@code floorY} with the layers of {@code floorBiome}. */ private void paintFloorLayers(ResourceId floorBiome, int rx, int rz, int worldX, int worldZ, int floorY) { - List floorLayers = dressing.floorLayers(output, floorBiome, worldX, worldZ, rng, LAYER_DEPTH, floorY); + List floorLayers = dressing.floorLayers(floorBiome, worldX, worldZ, rng, LAYER_DEPTH, floorY); for (int i = 0; i < floorY - 1; i++) { if (i >= floorLayers.size()) { break; @@ -507,13 +508,13 @@ public class CaveApplying { if (layer == null || !classes.isSolid(existing) || !canReplaceCaveFloorLayer(output, rx, y, rz, layer, classes)) { continue; } - output.set(rx, y, rz, classes.isOre(existing) ? dressing.deepSlateOre(output, existing, layer) : layer); + output.set(rx, y, rz, classes.isOre(existing) ? dressing.oreFor(existing, layer) : layer); } } /** Replaces the solid blocks over {@code ceilingY} with the cave ceiling layers of {@code ceilingBiome}, below {@code maxY}. */ private void paintCeilingLayers(ResourceId ceilingBiome, int rx, int rz, int worldX, int worldZ, int ceilingY, int maxY) { - List ceilingLayers = dressing.ceilingLayers(output, ceilingBiome, worldX, worldZ, rng, LAYER_DEPTH, ceilingY); + List ceilingLayers = dressing.ceilingLayers(ceilingBiome, worldX, worldZ, rng, LAYER_DEPTH); for (int i = 0; i < ceilingLayers.size(); i++) { int y = ceilingY + i + 1; if (y >= maxY) { @@ -524,7 +525,7 @@ public class CaveApplying { if (layer == null || !classes.isSolid(existing)) { continue; } - output.set(rx, y, rz, classes.isOre(existing) ? dressing.deepSlateOre(output, existing, layer) : layer); + output.set(rx, y, rz, classes.isOre(existing) ? dressing.oreFor(existing, layer) : layer); } } @@ -578,12 +579,12 @@ public class CaveApplying { if (floorBiome != null && dressing.hasDecorators(floorBiome, DecorationPart.NONE) && hasStableCaveFloorSupport(output, rx, zone.getFloor(), rz, classes)) { - dressing.decorateFloor(output, rx, rz, xx, zz, floorBiome, zone.getFloor() - 1, zone.airThickness()); + dressing.decorateFloor(rx, rz, xx, zz, floorBiome, zone.getFloor() - 1, zone.airThickness()); } if (ceilingBiome != null && dressing.hasDecorators(ceilingBiome, DecorationPart.CEILING) && zone.getCeiling() + 1 < maxY && classes.isSolid(output.get(rx, zone.getCeiling() + 1, rz))) { - dressing.decorateCeiling(output, rx, rz, xx, zz, ceilingBiome, zone.getCeiling(), zone.airThickness()); + dressing.decorateCeiling(rx, rz, xx, zz, ceilingBiome, zone.getCeiling(), zone.airThickness()); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java b/src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java new file mode 100644 index 000000000..2cc160d08 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveDressing.java @@ -0,0 +1,55 @@ +/* + * 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.modifier; + +import art.arcane.iris.builtin.decorant.DecorationPart; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; + +import java.util.List; + +/** + * What a cave's walls, floor and ceiling get in one chunk: its biome's layers and decorators and the dimension's fluid palette. + * {@link #of} answers with the terrain and decorant built-ins, which ship in the same jar; tests answer with fixed blocks. + */ +public interface CaveDressing { + /** The built-ins' dressing of the chunk {@code context} generates. */ + static CaveDressing of(ChunkStageContext context) { + return new BuiltInCaveDressing(context); + } + + BlockState fluidAt(int x, int z); + + /** The block of the biome's wall at the position; null when the biome declares no wall. */ + BlockState wall(ResourceId biome, RNG rng, int x, int y, int z); + + List floorLayers(ResourceId biome, int x, int z, RNG rng, int depth, int floorY); + + List ceilingLayers(ResourceId biome, int x, int z, RNG rng, int depth); + + boolean hasDecorators(ResourceId biome, DecorationPart part); + + void decorateFloor(int localX, int localZ, int x, int z, ResourceId biome, int floorY, int airThickness); + + void decorateCeiling(int localX, int localZ, int x, int z, ResourceId biome, int ceilingY, int airThickness); + + /** The ore that suits the {@code rock} it replaces, as the platform decides. */ + BlockState oreFor(BlockState rock, BlockState ore); +} From 0cd2a0e1951f5e6edb6c7e218a7c994ed4806825 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 07:28:26 +0200 Subject: [PATCH 086/139] The bedrock check asks the height first, so a placement above the bottom rows never reads the dimension's bedrock setting --- .../art/arcane/iris/engine/object/placement/ValidateModule.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index cdb7cd885..1940731b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -96,7 +96,7 @@ public final class ValidateModule implements IrisModule { private static boolean isOnBedrock(PreparedPlacement prepared, int y) { PlacementTerrain terrain = prepared.terrain(); - return terrain.hasWorld() && terrain.hasBedrock() && y <= BEDROCK_ROW; + return y <= BEDROCK_ROW && terrain.hasWorld() && terrain.hasBedrock(); } private static boolean lacksSurfaceSupport(ObjectPlacement placement, PreparedPlacement prepared) { From b630efb8184e6445c2ececc4477f11e3ca5aab62 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 11:22:39 +0200 Subject: [PATCH 087/139] Structure placement markers move into the exposed package; the blocks stage looks up spawn markers itself --- source-patterns.txt | 1 - .../art/arcane/iris/builtin/placement/ObjectPlacement.java | 6 +++--- .../structure}/StructurePlacementMarker.java | 2 +- .../iris/engine/mantle/components/StructurePlacing.java | 2 +- .../arcane/iris/engine/object/placement/BlocksModule.java | 3 ++- 5 files changed, 7 insertions(+), 7 deletions(-) rename src/main/java/art/arcane/iris/{engine/framework => builtin/structure}/StructurePlacementMarker.java (98%) diff --git a/source-patterns.txt b/source-patterns.txt index 2d5787b2a..bd9d2ba02 100644 --- a/source-patterns.txt +++ b/source-patterns.txt @@ -11,7 +11,6 @@ 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/StructurePlacementMarker.java art/arcane/iris/engine/framework/StructureVerticalBounds.java art/arcane/iris/engine/framework/PlacedObject.java art/arcane/iris/engine/framework/PlacedStructurePiece.java diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java index 2a8520599..3e8ded0ac 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java @@ -19,10 +19,10 @@ package art.arcane.iris.builtin.placement; import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; +import com.volmit.resource.PackResources; import com.volmit.world.BlockPosition; import java.util.Optional; @@ -94,8 +94,8 @@ public interface ObjectPlacement { */ boolean hasTrait(BlockState state, BlockTrait trait); - /** The marker of the pack named {@code key}, if the pack has one. */ - Optional marker(String key); + /** The resources of the object's pack, where the placement's markers are found. */ + PackResources resources(); /** Reports a buffered write as one of the object's own blocks, which Iris's placement listener hears after the commit. */ void objectBlockWritten(BlockPosition position); diff --git a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java similarity index 98% rename from src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java rename to src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java index 13bd4bed2..97bd7ef67 100644 --- a/src/main/java/art/arcane/iris/engine/framework/StructurePlacementMarker.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java @@ -1,4 +1,4 @@ -package art.arcane.iris.engine.framework; +package art.arcane.iris.builtin.structure; import java.nio.charset.StandardCharsets; import java.util.Base64; 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 index c0acf37e2..06d241f91 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -27,7 +27,7 @@ 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.engine.framework.StructurePlacementMarker; +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; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 21206dc03..11c465e23 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -29,6 +29,7 @@ import art.arcane.iris.builtin.placement.PlacementSettings; import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.spawn.SpawnMarker; +import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; @@ -205,7 +206,7 @@ public final class BlocksModule implements IrisModule { RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; for (MarkerRule rule : settings.markers()) { - Optional marker = placement.marker(rule.marker()); + Optional marker = Optional.ofNullable(SpawnResources.marker(placement.resources(), rule.marker())); int markerSalt = salt++; if (marker.isEmpty()) { continue; From d8612fae275bee745b4eea15ec6a6529bb3ee3f1 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 11:55:18 +0200 Subject: [PATCH 088/139] Procedural objects generate in the built-ins jar The generators build their variants on IrisApi block states through ObjectBuilder, which the host gives out (ObjectHost.builder()), so a content plugin's block keeps its identity. Each world resolves its procedural placements once (ObjectHost.procedural(settings, resolve)); the placements describe themselves (clamp, stilt) and the host reads them as Iris placements. engine/object/procedural goes into iris-builtins.jar. --- builtin-modules.txt | 1 + .../iris/builtin/objects/ObjectBuilder.java | 43 +++++ .../iris/builtin/objects/ObjectHost.java | 9 +- .../builtin/objects/ProceduralPlacement.java | 7 + .../mantle/components/ChunkObjectPlacing.java | 3 +- .../components/FloatingObjectPlacing.java | 4 +- .../mantle/components/ObjectWarmUp.java | 3 +- .../mantle/components/PlacementReach.java | 3 +- .../object/placement/ObjectPlacements.java | 18 +- .../object/prefab/IrisObjectShaping.java | 9 +- .../procedural/IrisProceduralBlocks.java | 111 +++--------- .../procedural/IrisProceduralPlacement.java | 48 ----- .../object/procedural/ProceduralShape.java | 27 +++ .../procedural/ResolvedProceduralObjects.java | 45 ++--- .../ResolvedProceduralPlacement.java | 166 ++++++++++-------- .../procedural/coral/CoralGenerator.java | 24 +-- .../procedural/coral/ResolvedCoral.java | 13 +- .../procedural/crystal/CrystalGenerator.java | 40 ++--- .../procedural/crystal/ResolvedCrystal.java | 13 +- .../formation/FormationBlockResolver.java | 13 +- .../formation/FormationGenerator.java | 12 +- .../formation/ResolvedFormation.java | 18 +- .../procedural/fungi/FungusCapBuilder.java | 1 - .../procedural/fungi/FungusGenerator.java | 28 +-- .../procedural/fungi/FungusStemBuilder.java | 4 +- .../procedural/fungi/ResolvedFungus.java | 28 +-- .../object/procedural/ruin/ResolvedRuin.java | 13 +- .../procedural/ruin/RuinBlockCanvas.java | 12 +- .../procedural/ruin/RuinDecoratorApplier.java | 8 +- .../object/procedural/ruin/RuinGenerator.java | 34 ++-- .../tree/ProceduralTreeGenerator.java | 27 +-- .../object/procedural/tree/ResolvedTree.java | 53 +++--- .../procedural/tree/TreeBlockResolver.java | 51 +++--- .../procedural/tree/TreePlausibility.java | 21 ++- 34 files changed, 451 insertions(+), 459 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java create mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 1940398e8..8935c8a35 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -83,3 +83,4 @@ include art/arcane/iris/engine/mantle/components/PlacementReach*.class include art/arcane/iris/engine/mantle/components/ObjectWarmUp*.class include art/arcane/iris/engine/mantle/components/ObjectLocating*.class include art/arcane/iris/engine/mantle/components/TreeGrowing*.class +include art/arcane/iris/engine/object/procedural/** diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java new file mode 100644 index 000000000..066662abc --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java @@ -0,0 +1,43 @@ +/* + * 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.builtin.objects; + +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; +import com.volmit.object.ObjectBlock; + +import java.util.List; + +/** + * Builds objects block by block for a module, with blocks as the platform has them: a state the builder handed out + * keeps what the platform knows about it when a property is set or the object is built, so a content plugin's block + * stays itself. One builder serves one bake on one thread. + */ +public interface ObjectBuilder { + /** The platform's state for {@code key}; null when the platform has no such block. */ + BlockState block(String key); + + /** The block {@code palette} gives at the position when its noise is seeded with {@code seed}. */ + BlockState pick(PaletteSpec palette, long seed, int x, int y, int z); + + /** {@code state} with the property set, as the platform sets it. */ + BlockState withProperty(BlockState state, String name, String value); + + /** The object of {@code blocks}, put in their order, {@code width} by {@code height} by {@code depth}, placeable like the pack's objects. */ + PlaceableObject build(String loadKey, int width, int height, int depth, List blocks); +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java index ef42019eb..bc85329ad 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java @@ -28,6 +28,7 @@ import com.volmit.world.PackWorld; import java.util.List; import java.util.Optional; +import java.util.function.Function; /** * What {@code iris:objects} asks of Iris: the objects of the pack, how Iris scales and places them, and the layout around @@ -83,8 +84,12 @@ public interface ObjectHost { /** Builds what placing the placement would build on first use, so the first chunk to place it does not wait. */ void warm(ObjectPlacement placement, RNG rng); - /** The procedural objects {@code settings} declare, made placeable once. */ - List procedural(ProceduralObjectSettings settings); + /** The procedural objects {@code settings} declare, made placeable by {@code resolve} once per world. */ + List procedural(ProceduralObjectSettings settings, + Function> resolve); + + /** A builder for one bake of objects made block by block. */ + ObjectBuilder builder(); /** The object settings of the biome and the region of the dimension stacked above, at the column; none where nothing sits above. */ Optional upperObjects(int worldX, int worldZ); diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java index ee0e55fab..6f2adeb0e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java @@ -23,7 +23,9 @@ import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; import art.arcane.volmlib.util.math.RNG; import java.util.List; @@ -80,6 +82,11 @@ public interface ProceduralPlacement extends PlacementSource { Optional vacuumSettings(); + /** The heights the variants may sit between. */ + ObjectLimit clamp(); + + Optional stiltSettings(); + /** One of the variants, picked with {@code rng}; empty when none baked. */ Optional variant(RNG rng); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index eb8338d9e..027f10da0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -36,6 +36,7 @@ import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; @@ -400,7 +401,7 @@ final class ChunkObjectPlacing { } private List proceduralPlacements(ProceduralObjectSettings settings) { - return settings == null ? List.of() : host.procedural(settings); + return settings == null ? List.of() : ResolvedProceduralObjects.of(host, settings); } private void placeProceduralFrom(List placements, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 4dbc0a9ad..aa5359c4a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -35,7 +35,7 @@ import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.prefab.IrisObjectRotation; import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; +import art.arcane.iris.engine.object.prefab.IrisObjectShaping; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.math.IrisBlockVector; @@ -473,7 +473,7 @@ public class FloatingObjectPlacing { } PlatformBlockState existingState = placer.get(x, y, z); boolean wouldReplace = B.isSolid(existingState) && B.isVineBlock(state); - String material = IrisProceduralBlocks.materialKey(state); + String material = IrisObjectShaping.materialKey(state); boolean placesBlock = !material.equals("minecraft:air") && !material.equals("minecraft:cave_air") && !wouldReplace; return state.isCustom() || placesBlock; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 6b9241941..4af693f2a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -25,6 +25,7 @@ import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; import com.volmit.FeatureAttachment.Target; import com.volmit.world.PackWorld; @@ -80,7 +81,7 @@ final class ObjectWarmUp { } private void warmProcedural(ProceduralObjectSettings settings) { - for (ProceduralPlacement placement : host.procedural(settings)) { + for (ProceduralPlacement placement : ResolvedProceduralObjects.of(host, settings)) { placement.variant(root.nextParallelRNG(warmed++)); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java index c98c94fd3..0c3b064b4 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -30,6 +30,7 @@ import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; @@ -101,7 +102,7 @@ final class PlacementReach { private int ofProcedural(ProceduralObjectSettings settings) { int radius = 0; - for (ProceduralPlacement placement : host.procedural(settings)) { + for (ProceduralPlacement placement : ResolvedProceduralObjects.of(host, settings)) { for (PlaceableObject variant : placement.variants()) { radius = Math.max(radius, of(new ObjectSize(variant.width(), variant.height(), variant.depth()), placement)); } 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 index f69425cb5..9d34d6947 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java @@ -20,7 +20,6 @@ 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.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.TreeGrowthSettings; @@ -28,21 +27,18 @@ 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.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.collection.KList; import java.util.Collections; import java.util.Map; -import java.util.Optional; import java.util.WeakHashMap; /** - * The object placements and procedural objects a region or biome declares, as Iris places them: the module settings of + * 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 static final Map PROCEDURAL = Collections.synchronizedMap(new WeakHashMap<>()); private ObjectPlacements() { } @@ -62,17 +58,6 @@ public final class ObjectPlacements { return placementsOf(owner).carving; } - /** The procedural objects {@code owner} declares; none when it declares none. */ - public static ResolvedProceduralObjects procedural(IrisRegistrant owner) { - Optional settings = owner.getModuleSettings().find(ProceduralObjectSettings.class); - return procedural(settings.orElse(NO_PROCEDURAL_OBJECTS)); - } - - /** The procedural objects {@code settings} declare. */ - public static ResolvedProceduralObjects procedural(ProceduralObjectSettings settings) { - return PROCEDURAL.computeIfAbsent(settings, ResolvedProceduralObjects::new); - } - /** 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); @@ -111,7 +96,6 @@ public final class ObjectPlacements { return made; } - private static final ProceduralObjectSettings NO_PROCEDURAL_OBJECTS = new ProceduralObjectSettings(); 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(); 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 index 7b840be99..19ad00a47 100644 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java +++ b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.object.prefab; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.data.VectorMap; @@ -287,7 +286,13 @@ public final class IrisObjectShaping { } public static String materialKey(PlatformBlockState state) { - return IrisProceduralBlocks.materialKey(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) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java index 9a49de54a..8bd7f34db 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java @@ -18,23 +18,23 @@ package art.arcane.iris.engine.object.procedural; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.core.loader.IrisData; -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.builtin.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; +import com.volmit.object.ObjectBlock; +import com.volmit.world.BlockPosition; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Optional; /** - * Shared low-level helpers for building procedural objects in memory: resolving a - * single block id or a noise palette into a platform block state, and assembling a - * raw block map into a centered IrisObject anchored so its y=0 layer sits one block - * above the terrain surface (same convention the tree generator uses). + * Shared low-level helpers for building procedural objects in memory: resolving a single block id or a noise palette + * into a block state, and assembling a raw block map into a centered object shape anchored so its y=0 layer sits one + * block above the terrain surface (same convention the tree generator uses). */ public final class IrisProceduralBlocks { public static final String[] FACE_PROPERTIES = {"north", "east", "south", "west", "up", "down"}; @@ -61,92 +61,39 @@ public final class IrisProceduralBlocks { return palette.filter(IrisProceduralBlocks::paletteSet).isPresent(); } - public static PlatformBlockState resolve(String block, Optional palette, IrisData data, int x, int y, int z, RNG paletteRng) { - return resolve(block, palette.orElse(null), data, x, y, z, paletteRng); + public static BlockState resolve(String block, Optional palette, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { + return resolve(block, palette.orElse(null), blocks, x, y, z, paletteRng); } - public static PlatformBlockState resolve(Optional block, Optional palette, IrisData data, int x, int y, int z, RNG paletteRng) { - return resolve(block.orElse(null), palette.orElse(null), data, x, y, z, paletteRng); + public static BlockState resolve(Optional block, Optional palette, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { + return resolve(block.orElse(null), palette.orElse(null), blocks, x, y, z, paletteRng); } /** The block of {@code palette} at the position, picked with the seed of {@code paletteRng} as the palette's old class did; else {@code block}. */ - public static PlatformBlockState resolve(String block, PaletteSpec palette, IrisData data, int x, int y, int z, RNG paletteRng) { + public static BlockState resolve(String block, PaletteSpec palette, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { if (paletteSet(palette)) { - return pick(palette, data, paletteRng.getSeed(), x, y, z); + return blocks.pick(palette, paletteRng.getSeed(), x, y, z); } if (block != null && !block.isEmpty()) { - return B.getStateOrNull(block, false); + return blocks.block(block); } return null; } - /** The block {@code palette} gives at the position when its noise is seeded with {@code seed}. */ - public static PlatformBlockState pick(PaletteSpec palette, IrisData data, long seed, int x, int y, int z) { - return B.getState(data.getPackResources().blocks().palette(palette, seed).at(x, y, z).key()); + public static boolean hasProperty(BlockState state, String property) { + return state.properties().containsKey(property); } - public static boolean hasProperty(PlatformBlockState state, String property) { - String key = state.key(); - int start = propertyStart(key, property); - if (start < 0) { - return false; - } - int valueStart = start + property.length() + 2; - return key.indexOf(',', valueStart) >= 0 || key.indexOf(']', valueStart) >= 0; + public static String materialKey(BlockState state) { + return state.material().toString(); } - 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 String propertyValue(BlockState state, String property) { + return state.properties().get(property); } - public static String propertyValue(PlatformBlockState state, String property) { - String key = state.key(); - int start = propertyStart(key, property); - if (start < 0) { - return null; - } - int valueStart = start + property.length() + 2; - int end = key.indexOf(',', valueStart); - if (end < 0) { - end = key.indexOf(']', valueStart); - } - if (end < 0) { - return null; - } - return key.substring(valueStart, end); - } - - /** - * Index of the delimiter opening "[property=" or ",property=" within the key, or -1. Scans in place - * rather than building the search needles, and prefers a "[" match over a "," match. - */ - private static int propertyStart(String key, String property) { - int bracket = key.indexOf('['); - if (bracket < 0) { - return -1; - } - int start = delimitedPropertyIndex(key, property, bracket, '['); - return start < 0 ? delimitedPropertyIndex(key, property, bracket, ',') : start; - } - - private static int delimitedPropertyIndex(String key, String property, int from, char delimiter) { - int length = property.length(); - int limit = key.length() - length - 2; - for (int i = key.indexOf(delimiter, from); i >= 0 && i <= limit; i = key.indexOf(delimiter, i + 1)) { - if (key.regionMatches(i + 1, property, 0, length) && key.charAt(i + 1 + length) == '=') { - return i; - } - } - return -1; - } - - public static IrisObject assemble(Map blocks) { + /** The blocks centered on x and z, with their lowest layer one block above the anchor; null when there are none. */ + public static ProceduralShape assemble(Map blocks) { if (blocks == null || blocks.isEmpty()) { return null; } @@ -173,15 +120,15 @@ public final class IrisProceduralBlocks { int cy = h / 2; int cz = d / 2; - IrisObject object = new IrisObject(w, h, d); - for (Map.Entry entry : blocks.entrySet()) { + List placed = new ArrayList<>(blocks.size()); + for (Map.Entry entry : blocks.entrySet()) { Vector3i v = entry.getKey(); int nx = v.getBlockX() - minX - cx; int ny = v.getBlockY() - cy + 1; int nz = v.getBlockZ() - minZ - cz; - object.getBlocks().put(new IrisBlockVector(nx, ny, nz), entry.getValue()); + placed.add(new ObjectBlock(new BlockPosition(nx, ny, nz), entry.getValue())); } - return object; + return new ProceduralShape(w, h, d, placed); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java deleted file mode 100644 index b877a2624..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralPlacement.java +++ /dev/null @@ -1,48 +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.procedural; - -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -/** - * A procedurally generated, placeable thing in a biome or region (trees, ruins, - * formations, coral, fungi, crystals). Implementations bake a deterministic pool - * of in-memory IrisObject variants and expose the placement controls the engine - * needs to scatter them, exactly like an object placement but generated from - * scratch instead of loaded from an iob file. - */ -public interface IrisProceduralPlacement { - String getName(); - - double getChance(); - - int getDensity(); - - boolean isPlausible(); - - IrisObjectPlacement asPlacement(); - - IrisObject getVariantObject(IrisData data, RNG rng); - - KList getVariantObjects(IrisData data); -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java b/src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java new file mode 100644 index 000000000..4443833b8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java @@ -0,0 +1,27 @@ +/* + * 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.procedural; + +import com.volmit.object.ObjectBlock; + +import java.util.List; + +/** A procedural object's blocks around its anchor, in the order they were made, and the size of the box they fill. */ +public record ProceduralShape(int width, int height, int depth, List blocks) { +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java index 1c294004e..da9098e24 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java @@ -18,7 +18,9 @@ package art.arcane.iris.engine.object.procedural; +import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; @@ -26,37 +28,38 @@ import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; -import art.arcane.volmlib.util.collection.KList; +import java.util.ArrayList; import java.util.List; -import java.util.function.Function; +import java.util.function.BiFunction; -/** The procedural objects a region or biome declares, each made placeable once, in the order the settings list them. */ +/** The procedural objects a region or biome declares, each made placeable once per world, in the order the settings list them. */ public final class ResolvedProceduralObjects { - private final KList all = new KList<>(); + private ResolvedProceduralObjects() { + } - public ResolvedProceduralObjects(ProceduralObjectSettings settings) { + /** The placements {@code settings} declare in the world of {@code host}, resolved the first time a world asks. */ + public static List of(ObjectHost host, ProceduralObjectSettings settings) { + return host.procedural(settings, declared -> resolve(declared, host)); + } + + static List resolve(ProceduralObjectSettings settings, ObjectHost host) { + List all = new ArrayList<>(); for (Tree tree : settings.trees()) { - all.add(new ResolvedTree(tree)); + all.add(new ResolvedTree(tree, host)); } - addAll(settings.ruins(), ResolvedRuin::new); - addAll(settings.formations(), ResolvedFormation::new); - addAll(settings.coral(), ResolvedCoral::new); - addAll(settings.fungi(), ResolvedFungus::new); - addAll(settings.crystals(), ResolvedCrystal::new); + addAll(all, settings.ruins(), host, ResolvedRuin::new); + addAll(all, settings.formations(), host, ResolvedFormation::new); + addAll(all, settings.coral(), host, ResolvedCoral::new); + addAll(all, settings.fungi(), host, ResolvedFungus::new); + addAll(all, settings.crystals(), host, ResolvedCrystal::new); + return List.copyOf(all); } - private void addAll(List settings, Function resolve) { + private static void addAll(List all, List settings, ObjectHost host, + BiFunction resolve) { for (S entry : settings) { - all.add(resolve.apply(entry)); + all.add(resolve.apply(entry, host)); } } - - public KList getAllPlacements() { - return all; - } - - public boolean isEmpty() { - return all.isEmpty(); - } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java index fbad263b9..6bf87e22a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java @@ -20,26 +20,28 @@ package art.arcane.iris.engine.object.procedural; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.core.loader.IrisData; import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + /** - * A procedural object's settings made placeable: bakes a deterministic pool of variants from them, once, and turns - * the placement options into the object placement the engine scatters. The settings classes held the same cache - * and methods before they became module settings. + * A procedural object's settings made placeable: bakes a deterministic pool of variants from them, once, through the + * host's object builder, and hands the placement options to {@code iris:objects}. */ -public abstract class ResolvedProceduralPlacement implements IrisProceduralPlacement { +public abstract class ResolvedProceduralPlacement implements ProceduralPlacement { private static final long VARIANT_SEED_STRIDE = 7919L; /** The options every procedural placement shares with an object placement. */ @@ -49,68 +51,126 @@ public abstract class ResolvedProceduralPlacement implements IrisProceduralPlace } private final Shape shape; - private final AtomicCache> variantCache = new AtomicCache<>(); + private final ObjectHost host; + private final AtomicCache> variantCache = new AtomicCache<>(); - protected ResolvedProceduralPlacement(Shape shape) { + protected ResolvedProceduralPlacement(Shape shape, ObjectHost host) { this.shape = shape; + this.host = host; } - /** The object variant {@code index} is baked as, from its own seeded stream. */ - protected abstract IrisObject generate(int index, RNG rng, IrisData data); + /** The shape variant {@code index} is baked as, from its own seeded stream; null when it has no blocks. */ + protected abstract ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks); /** The number of variants to bake; the settings' count, at least one. */ protected int variantCount() { return Math.max(1, shape.variants()); } - /** The options this object shares with an object placement. */ - public Shape shape() { - return shape; - } - @Override - public String getName() { + public String name() { return shape.name(); } @Override - public double getChance() { + public double chance() { return shape.chance(); } @Override - public int getDensity() { + public int density() { return shape.density(); } @Override - public boolean isPlausible() { + public boolean plausible() { return false; } @Override - public KList getVariantObjects(IrisData data) { - return variantCache.aquire(() -> bake(data)); + public boolean tree() { + return false; + } + + @Override + public ObjectPlaceMode mode() { + return shape.mode(); + } + + @Override + public CarvingMode carvingSupport() { + return shape.carvingSupport(); + } + + @Override + public CaveAnchorMode caveAnchorMode() { + return CaveAnchorMode.PROFILE_DEFAULT; + } + + @Override + public boolean underwater() { + return shape.underwater(); + } + + @Override + public ObjectRotation rotation() { + return shape.rotation(); + } + + @Override + public ObjectTranslate translate() { + return shape.translate(); + } + + @Override + public Optional vacuumSettings() { + return Optional.ofNullable(shape.vacuumSettings()); + } + + @Override + public ObjectLimit clamp() { + return shape.clamp(); + } + + @Override + public Optional stiltSettings() { + return Optional.ofNullable(shape.stiltSettings()); + } + + @Override + public List variants() { + return variantCache.aquire(() -> bake(host.builder())); + } + + @Override + public Optional variant(RNG rng) { + List baked = variants(); + if (baked == null || baked.isEmpty()) { + return Optional.empty(); + } + return Optional.of(baked.get(rng.i(baked.size()))); } /** Bakes every variant; the default draws variant {@code i} from {@code seed + i * stride}. */ - protected KList bake(IrisData data) { - KList baked = new KList<>(); + protected List bake(ObjectBuilder blocks) { + List baked = new ArrayList<>(); int count = variantCount(); for (int i = 0; i < count; i++) { - IrisObject object = generate(i, variantRng(i), data); - if (object == null || object.getBlocks().isEmpty()) { + ProceduralShape generated = generate(i, variantRng(i), blocks); + if (generated == null || generated.blocks().isEmpty()) { continue; } - object.setLoadKey("procedural/" + shape.name() + "#" + i); - object.setLoader(data); - baked.add(object); + baked.add(build(blocks, "procedural/" + shape.name() + "#" + i, generated)); } return baked; } + protected static PlaceableObject build(ObjectBuilder blocks, String loadKey, ProceduralShape generated) { + return blocks.build(loadKey, generated.width(), generated.height(), generated.depth(), generated.blocks()); + } + protected final RNG variantRng(int index) { return new RNG(shape.seed() + (index * VARIANT_SEED_STRIDE)); } @@ -118,46 +178,4 @@ public abstract class ResolvedProceduralPlacement implements IrisProceduralPlace protected final long seed() { return shape.seed(); } - - @Override - public IrisObject getVariantObject(IrisData data, RNG rng) { - KList baked = getVariantObjects(data); - if (baked == null || baked.isEmpty()) { - return null; - } - return baked.get(rng.i(baked.size())); - } - - @Override - public IrisObjectPlacement asPlacement() { - IrisObjectPlacement placement = new IrisObjectPlacement(); - placement.setMode(shape.mode()); - placement.setRotation(irisRotation(shape.rotation())); - placement.setClamp(shape.clamp()); - placement.setCarvingSupport(shape.carvingSupport()); - placement.setUnderwater(shape.underwater()); - placement.setTranslate(irisTranslate(shape.translate())); - placement.setStiltSettings(shape.stiltSettings()); - placement.setVacuumSettings(shape.vacuumSettings()); - placement.setChance(shape.chance()); - placement.setDensity(shape.density()); - customize(placement); - return placement; - } - - /** Sets what this kind of placement adds to the common options. */ - protected void customize(IrisObjectPlacement placement) { - } - - private static IrisObjectRotation irisRotation(ObjectRotation rotation) { - return new IrisObjectRotation() - .setEnabled(rotation.enabled()) - .setXAxis(rotation.xAxis()) - .setYAxis(rotation.yAxis()) - .setZAxis(rotation.zAxis()); - } - - private static IrisObjectTranslate irisTranslate(ObjectTranslate translate) { - return new IrisObjectTranslate(translate.x(), translate.y(), translate.yRandom(), translate.z()); - } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java index f0f5d0d18..1699235d9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java @@ -19,11 +19,11 @@ package art.arcane.iris.engine.object.procedural.coral; import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -36,7 +36,7 @@ public final class CoralGenerator { private CoralGenerator() { } - public static IrisObject generate(Coral coral, int variantIndex, RNG rng, IrisData data) { + public static ProceduralShape generate(Coral coral, int variantIndex, RNG rng, ObjectBuilder blocks) { int lo = Math.min(coral.heightMin(), coral.heightMax()); int hi = Math.max(coral.heightMin(), coral.heightMax()); int height = Math.max(2, rng.i(lo, hi + 1)); @@ -51,7 +51,7 @@ public final class CoralGenerator { case TENDRIL -> buildTendril(canvas, coral, height, shapeSeed, rng); } - Map resolved = resolve(canvas, coral, data); + Map resolved = resolve(canvas, coral, blocks); return IrisProceduralBlocks.assemble(resolved); } @@ -230,29 +230,29 @@ public final class CoralGenerator { }; } - private static Map resolve(CoralCanvas canvas, Coral coral, IrisData data) { - Map out = new HashMap<>(); + private static Map resolve(CoralCanvas canvas, Coral coral, ObjectBuilder blocks) { + Map out = new HashMap<>(); RNG paletteRng = new RNG(coral.seed()); for (Map.Entry entry : canvas.getCells().entrySet()) { int[] xyz = CoralCanvas.decode(entry.getKey()); int x = xyz[0]; int y = xyz[1]; int z = xyz[2]; - PlatformBlockState state; + BlockState state; if (entry.getValue() == CoralCanvas.Role.TIP) { - state = IrisProceduralBlocks.resolve(coral.tipBlock(), coral.tipPalette(), data, x, y, z, paletteRng); + state = IrisProceduralBlocks.resolve(coral.tipBlock(), coral.tipPalette(), blocks, x, y, z, paletteRng); if (state == null) { - state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), data, x, y, z, paletteRng); + state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), blocks, x, y, z, paletteRng); } } else { - state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), data, x, y, z, paletteRng); + state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), blocks, x, y, z, paletteRng); } if (state == null) { continue; } if (coral.waterlogged() && IrisProceduralBlocks.hasProperty(state, "waterlogged")) { try { - state = state.withProperty("waterlogged", "true"); + state = blocks.withProperty(state, "waterlogged", "true"); } catch (IllegalArgumentException ignored) { } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java index db3ef9dea..8e99c0bbd 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java @@ -19,8 +19,9 @@ package art.arcane.iris.engine.object.procedural.coral; import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.volmlib.util.math.RNG; @@ -28,15 +29,15 @@ import art.arcane.volmlib.util.math.RNG; public final class ResolvedCoral extends ResolvedProceduralPlacement { private final Coral settings; - public ResolvedCoral(Coral settings) { + public ResolvedCoral(Coral settings, ObjectHost host) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); this.settings = settings; } @Override - protected IrisObject generate(int index, RNG rng, IrisData data) { - return CoralGenerator.generate(settings, index, rng, data); + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { + return CoralGenerator.generate(settings, index, rng, blocks); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java index f2e1c1b2d..2ce127cc0 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java @@ -20,10 +20,10 @@ package art.arcane.iris.engine.object.procedural.crystal; import art.arcane.iris.builtin.objects.crystal.Crystal; import com.volmit.block.PaletteSpec; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -34,14 +34,14 @@ public final class CrystalGenerator { private CrystalGenerator() { } - public static IrisObject generate(Crystal crystal, int variantIndex, RNG rng, IrisData data) { + public static ProceduralShape generate(Crystal crystal, int variantIndex, RNG rng, ObjectBuilder blocks) { CrystalCanvas canvas = new CrystalCanvas(); long structureSeed = rng.getSeed(); CrystalBaseBuilder.build(canvas, crystal, structureSeed + 977L); CrystalShardBuilder.build(canvas, crystal, rng); - Map resolved = new HashMap<>(); + Map resolved = new HashMap<>(); RNG paletteRng = new RNG(crystal.seed()); RNG tipRng = new RNG(crystal.seed() + (variantIndex * 31337L) + 4099L); @@ -50,7 +50,7 @@ public final class CrystalGenerator { int x = position.getBlockX(); int y = position.getBlockY(); int z = position.getBlockZ(); - PlatformBlockState blockData = resolveRole(crystal, entry.getValue(), data, x, y, z, paletteRng, tipRng); + BlockState blockData = resolveRole(crystal, entry.getValue(), blocks, x, y, z, paletteRng, tipRng); if (blockData == null) { continue; } @@ -60,53 +60,53 @@ public final class CrystalGenerator { return IrisProceduralBlocks.assemble(resolved); } - private static PlatformBlockState resolveRole(Crystal crystal, CrystalRole role, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { + private static BlockState resolveRole(Crystal crystal, CrystalRole role, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng, RNG tipRng) { return switch (role) { - case BASE -> resolveBase(crystal, data, x, y, z, paletteRng); - case SHARD -> resolveShard(crystal, data, x, y, z, paletteRng); - case TIP -> resolveTip(crystal, data, x, y, z, paletteRng, tipRng); + case BASE -> resolveBase(crystal, blocks, x, y, z, paletteRng); + case SHARD -> resolveShard(crystal, blocks, x, y, z, paletteRng); + case TIP -> resolveTip(crystal, blocks, x, y, z, paletteRng, tipRng); }; } - private static PlatformBlockState resolveBase(Crystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { + private static BlockState resolveBase(Crystal crystal, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { boolean hasBase = IrisProceduralBlocks.paletteSet(crystal.basePalette()) || (crystal.baseBlock() != null && !crystal.baseBlock().isEmpty()); if (hasBase) { - PlatformBlockState base = IrisProceduralBlocks.resolve(crystal.baseBlock(), crystal.basePalette(), data, x, y, z, paletteRng); + BlockState base = IrisProceduralBlocks.resolve(crystal.baseBlock(), crystal.basePalette(), blocks, x, y, z, paletteRng); if (base != null) { return base; } } - return resolveShard(crystal, data, x, y, z, paletteRng); + return resolveShard(crystal, blocks, x, y, z, paletteRng); } - private static PlatformBlockState resolveShard(Crystal crystal, IrisData data, int x, int y, int z, RNG paletteRng) { - return IrisProceduralBlocks.resolve(crystal.block(), crystal.blockPalette(), data, x, y, z, paletteRng); + private static BlockState resolveShard(Crystal crystal, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { + return IrisProceduralBlocks.resolve(crystal.block(), crystal.blockPalette(), blocks, x, y, z, paletteRng); } - private static PlatformBlockState resolveTip(Crystal crystal, IrisData data, int x, int y, int z, RNG paletteRng, RNG tipRng) { + private static BlockState resolveTip(Crystal crystal, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng, RNG tipRng) { boolean hasTip = IrisProceduralBlocks.paletteSet(crystal.tipPalette()) || (crystal.tipBlock() != null && !crystal.tipBlock().isEmpty()); if (hasTip) { if (tipRng.chance(crystal.tipChance())) { - PlatformBlockState tip = IrisProceduralBlocks.resolve(crystal.tipBlock(), crystal.tipPalette(), data, x, y, z, paletteRng); + BlockState tip = IrisProceduralBlocks.resolve(crystal.tipBlock(), crystal.tipPalette(), blocks, x, y, z, paletteRng); if (tip != null) { return tip; } } - return resolveShard(crystal, data, x, y, z, paletteRng); + return resolveShard(crystal, blocks, x, y, z, paletteRng); } if (crystal.glow() && crystal.glowBlock() != null && !crystal.glowBlock().isEmpty()) { if (tipRng.chance(crystal.tipChance())) { - PlatformBlockState glow = IrisProceduralBlocks.resolve(crystal.glowBlock(), (PaletteSpec) null, data, x, y, z, paletteRng); + BlockState glow = IrisProceduralBlocks.resolve(crystal.glowBlock(), (PaletteSpec) null, blocks, x, y, z, paletteRng); if (glow != null) { return glow; } } } - return resolveShard(crystal, data, x, y, z, paletteRng); + return resolveShard(crystal, blocks, x, y, z, paletteRng); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java index 17a62af06..5a8243174 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java @@ -19,8 +19,9 @@ package art.arcane.iris.engine.object.procedural.crystal; import art.arcane.iris.builtin.objects.crystal.Crystal; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.volmlib.util.math.RNG; @@ -28,15 +29,15 @@ import art.arcane.volmlib.util.math.RNG; public final class ResolvedCrystal extends ResolvedProceduralPlacement { private final Crystal settings; - public ResolvedCrystal(Crystal settings) { + public ResolvedCrystal(Crystal settings, ObjectHost host) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); this.settings = settings; } @Override - protected IrisObject generate(int index, RNG rng, IrisData data) { - return CrystalGenerator.generate(settings, index, rng, data); + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { + return CrystalGenerator.generate(settings, index, rng, blocks); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java index 16b468853..32e59ecdc 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java @@ -21,10 +21,9 @@ package art.arcane.iris.engine.object.procedural.formation; import com.volmit.block.PaletteSpec; import java.util.Optional; import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; +import art.arcane.iris.builtin.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -32,14 +31,14 @@ public final class FormationBlockResolver { private FormationBlockResolver() { } - public static PlatformBlockState resolve(Formation f, IrisData data, FormationCanvas.Role role, Vector3i raw) { + public static BlockState resolve(Formation f, ObjectBuilder blocks, FormationCanvas.Role role, Vector3i raw) { int x = raw.getBlockX(); int y = raw.getBlockY(); int z = raw.getBlockZ(); RNG paletteRng = new RNG(f.seed()); if (role == FormationCanvas.Role.CAP && capDefined(f)) { - PlatformBlockState cap = IrisProceduralBlocks.resolve(f.capBlock(), f.capPalette(), data, x, y, z, paletteRng); + BlockState cap = IrisProceduralBlocks.resolve(f.capBlock(), f.capPalette(), blocks, x, y, z, paletteRng); if (cap != null) { return cap; } @@ -49,13 +48,13 @@ public final class FormationBlockResolver { PaletteSpec strata = f.strataPalette().orElseThrow(); int thickness = Math.max(1, f.strataThickness()); int band = Math.floorDiv(y, thickness); - PlatformBlockState strataState = IrisProceduralBlocks.pick(strata, data, f.seed() + (band * 31L), x, band, z); + BlockState strataState = blocks.pick(strata, f.seed() + (band * 31L), x, band, z); if (strataState != null) { return strataState; } } - return IrisProceduralBlocks.resolve(f.block(), f.blockPalette(), data, x, y, z, paletteRng); + return IrisProceduralBlocks.resolve(f.block(), f.blockPalette(), blocks, x, y, z, paletteRng); } private static boolean capDefined(Formation f) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java index bd066d8e2..40cbd260e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java @@ -19,10 +19,10 @@ package art.arcane.iris.engine.object.procedural.formation; import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -33,7 +33,7 @@ public final class FormationGenerator { private FormationGenerator() { } - public static IrisObject generate(Formation f, int variantIndex, RNG rng, IrisData data) { + public static ProceduralShape generate(Formation f, int variantIndex, RNG rng, ObjectBuilder blocks) { int lo = Math.min(f.heightMin(), f.heightMax()); int hi = Math.max(f.heightMin(), f.heightMax()); int height = Math.max(3, rng.i(lo, hi + 1)); @@ -61,9 +61,9 @@ public final class FormationGenerator { return null; } - Map resolved = new HashMap<>(); + Map resolved = new HashMap<>(); for (Map.Entry entry : canvas.getCells().entrySet()) { - PlatformBlockState bd = FormationBlockResolver.resolve(f, data, entry.getValue(), entry.getKey()); + BlockState bd = FormationBlockResolver.resolve(f, blocks, entry.getValue(), entry.getKey()); if (bd == null) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java index 6c4b0dcd3..0f1c8c775 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java @@ -19,9 +19,9 @@ package art.arcane.iris.engine.object.procedural.formation; import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.volmlib.util.math.RNG; @@ -29,20 +29,20 @@ import art.arcane.volmlib.util.math.RNG; public final class ResolvedFormation extends ResolvedProceduralPlacement { private final Formation settings; - public ResolvedFormation(Formation settings) { + public ResolvedFormation(Formation settings, ObjectHost host) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); this.settings = settings; } @Override - protected void customize(IrisObjectPlacement placement) { - placement.setSurfaceSupportBuffer(settings.surfaceSupportBuffer()); + public int surfaceSupportBuffer() { + return settings.surfaceSupportBuffer(); } @Override - protected IrisObject generate(int index, RNG rng, IrisData data) { - return FormationGenerator.generate(settings, index, rng, data); + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { + return FormationGenerator.generate(settings, index, rng, blocks); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java index 90519d6bf..c42949d6d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java @@ -22,7 +22,6 @@ import com.volmit.block.PaletteSpec; import java.util.Optional; import art.arcane.iris.builtin.objects.fungi.FungusCapShape; import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.engine.object.material.IrisMaterialPalette; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.volmlib.util.math.Vector3i; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java index 7f4581543..f0892715e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java @@ -19,10 +19,10 @@ package art.arcane.iris.engine.object.procedural.fungi; import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -33,7 +33,7 @@ public final class FungusGenerator { private FungusGenerator() { } - public static IrisObject generate(Fungus fungus, int height, RNG rng, IrisData data) { + public static ProceduralShape generate(Fungus fungus, int height, RNG rng, ObjectBuilder blocks) { Map roles = new HashMap<>(); long baseSeed = rng.getSeed(); @@ -48,10 +48,10 @@ public final class FungusGenerator { } RNG paletteRng = new RNG(fungus.seed()); - Map resolved = new HashMap<>(); + Map resolved = new HashMap<>(); for (Map.Entry entry : roles.entrySet()) { Vector3i pos = entry.getKey(); - PlatformBlockState bd = resolveRole(fungus, entry.getValue(), data, pos, paletteRng); + BlockState bd = resolveRole(fungus, entry.getValue(), blocks, pos, paletteRng); if (bd == null) { continue; } @@ -63,7 +63,7 @@ public final class FungusGenerator { private static void buildUpright(Map roles, Fungus fungus, int height, RNG rng, long baseSeed) { int stemHeight = Math.max(1, height); - Map stemCells = new HashMap<>(); + Map stemCells = new HashMap<>(); double[] top = FungusStemBuilder.build(stemCells, fungus, stemHeight, baseSeed); for (Vector3i v : stemCells.keySet()) { roles.put(v, FungusCellRole.STEM); @@ -84,20 +84,20 @@ public final class FungusGenerator { return rng.i(lo, hi + 1); } - private static PlatformBlockState resolveRole(Fungus fungus, FungusCellRole role, IrisData data, Vector3i pos, RNG paletteRng) { + private static BlockState resolveRole(Fungus fungus, FungusCellRole role, ObjectBuilder blocks, Vector3i pos, RNG paletteRng) { int x = pos.getBlockX(); int y = pos.getBlockY(); int z = pos.getBlockZ(); return switch (role) { - case STEM -> IrisProceduralBlocks.resolve(fungus.stem(), fungus.stemPalette(), data, x, y, z, paletteRng); - case CAP -> IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), data, x, y, z, paletteRng); + case STEM -> IrisProceduralBlocks.resolve(fungus.stem(), fungus.stemPalette(), blocks, x, y, z, paletteRng); + case CAP -> IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), blocks, x, y, z, paletteRng); case GILL -> { - PlatformBlockState gill = IrisProceduralBlocks.resolve(fungus.gillBlock(), fungus.gillPalette(), data, x, y, z, paletteRng); - yield gill != null ? gill : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), data, x, y, z, paletteRng); + BlockState gill = IrisProceduralBlocks.resolve(fungus.gillBlock(), fungus.gillPalette(), blocks, x, y, z, paletteRng); + yield gill != null ? gill : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), blocks, x, y, z, paletteRng); } case SPOT -> { - PlatformBlockState spot = IrisProceduralBlocks.resolve(fungus.spotBlock(), fungus.spotPalette(), data, x, y, z, paletteRng); - yield spot != null ? spot : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), data, x, y, z, paletteRng); + BlockState spot = IrisProceduralBlocks.resolve(fungus.spotBlock(), fungus.spotPalette(), blocks, x, y, z, paletteRng); + yield spot != null ? spot : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), blocks, x, y, z, paletteRng); } }; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java index 186c31b8b..2a4429d19 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.fungi; import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import java.util.Map; @@ -29,7 +29,7 @@ public final class FungusStemBuilder { private FungusStemBuilder() { } - public static double[] build(Map stemCells, Fungus fungus, int stemHeight, long seed) { + public static double[] build(Map stemCells, Fungus fungus, int stemHeight, long seed) { int width = Math.max(1, Math.min(3, fungus.stemWidth())); double maxLean = stemHeight * Math.tan(Math.toRadians(Math.max(0.0, fungus.stemCurve()))); double leanRad = Math.toRadians(fungus.stemLeanAzimuth()); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java index fd8ca1209..14f29c521 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java @@ -18,32 +18,36 @@ package art.arcane.iris.engine.object.procedural.fungi; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import java.util.ArrayList; +import java.util.List; + /** A fungus made placeable: its variants are baked by {@link FungusGenerator}. */ public final class ResolvedFungus extends ResolvedProceduralPlacement { private final Fungus settings; - public ResolvedFungus(Fungus settings) { + public ResolvedFungus(Fungus settings, ObjectHost host) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); this.settings = settings; } @Override - protected IrisObject generate(int index, RNG rng, IrisData data) { + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { throw new UnsupportedOperationException("A fungus bakes its variants itself, from the stem heights"); } @Override - protected KList bake(IrisData data) { - KList baked = new KList<>(); + protected List bake(ObjectBuilder blocks) { + List baked = new ArrayList<>(); int count = variantCount(); int lo = Math.min(settings.stemHeightMin(), settings.stemHeightMax()); int hi = Math.max(settings.stemHeightMin(), settings.stemHeightMax()); @@ -60,13 +64,11 @@ public final class ResolvedFungus extends ResolvedProceduralPlacement { height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); } - IrisObject object = FungusGenerator.generate(settings, Math.max(1, height), variantRng(i), data); - if (object == null || object.getBlocks().isEmpty()) { + ProceduralShape generated = FungusGenerator.generate(settings, Math.max(1, height), variantRng(i), blocks); + if (generated == null || generated.blocks().isEmpty()) { continue; } - object.setLoadKey("procedural/" + getName() + "#" + i); - object.setLoader(data); - baked.add(object); + baked.add(build(blocks, "procedural/" + name() + "#" + i, generated)); } return baked; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java index 48b464512..ede9c4bdc 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java @@ -19,8 +19,9 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.volmlib.util.math.RNG; @@ -28,15 +29,15 @@ import art.arcane.volmlib.util.math.RNG; public final class ResolvedRuin extends ResolvedProceduralPlacement { private final Ruin settings; - public ResolvedRuin(Ruin settings) { + public ResolvedRuin(Ruin settings, ObjectHost host) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); this.settings = settings; } @Override - protected IrisObject generate(int index, RNG rng, IrisData data) { - return RuinGenerator.generate(settings, index, rng, data); + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { + return RuinGenerator.generate(settings, index, rng, blocks); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java index 0b6cf7003..a45cc8ccd 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.ruin; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import java.util.HashMap; @@ -33,7 +33,7 @@ final class RuinBlockCanvas { static final class Cell { private Role role; private boolean structural; - private PlatformBlockState accentData; + private BlockState accentData; Cell(Role role, boolean structural) { this.role = role; @@ -48,7 +48,7 @@ final class RuinBlockCanvas { return structural; } - PlatformBlockState accentData() { + BlockState accentData() { return accentData; } @@ -57,7 +57,7 @@ final class RuinBlockCanvas { this.structural = this.structural || structuralNext; } - void makeAccent(PlatformBlockState data) { + void makeAccent(BlockState data) { this.role = Role.ACCENT; this.structural = false; this.accentData = data; @@ -80,14 +80,14 @@ final class RuinBlockCanvas { } } - void accent(int x, int y, int z, PlatformBlockState data) { + void accent(int x, int y, int z, BlockState data) { if (data == null) { return; } cells.put(new Vector3i(x, y, z), accentCell(data)); } - private static Cell accentCell(PlatformBlockState data) { + private static Cell accentCell(BlockState data) { Cell cell = new Cell(Role.ACCENT, false); cell.makeAccent(data); return cell; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java index f99c429e5..8930ed718 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java @@ -19,9 +19,9 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.builtin.objects.ruin.RuinDecorator; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.builtin.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -36,7 +36,7 @@ final class RuinDecoratorApplier { private RuinDecoratorApplier() { } - static void apply(RuinBlockCanvas canvas, RuinDecorator decorator, IrisData data, long seed, RNG rng) { + static void apply(RuinBlockCanvas canvas, RuinDecorator decorator, ObjectBuilder blocks, long seed, RNG rng) { List candidates = switch (decorator.target()) { case TOP -> topCandidates(canvas); case SURFACE -> surfaceCandidates(canvas); @@ -48,7 +48,7 @@ final class RuinDecoratorApplier { if (!rng.chance(decorator.chance())) { continue; } - PlatformBlockState bd = IrisProceduralBlocks.resolve(decorator.block(), decorator.palette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + BlockState bd = IrisProceduralBlocks.resolve(decorator.block(), decorator.palette(), blocks, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); if (bd != null) { canvas.accent(v.getBlockX(), v.getBlockY(), v.getBlockZ(), bd); } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java index 35370c21f..72fdd68da 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java @@ -20,10 +20,10 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.builtin.objects.ruin.RuinDecorator; import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; @@ -37,7 +37,7 @@ public final class RuinGenerator { private RuinGenerator() { } - public static IrisObject generate(Ruin ruin, int variantIndex, RNG rng, IrisData data) { + public static ProceduralShape generate(Ruin ruin, int variantIndex, RNG rng, ObjectBuilder blocks) { int count = Math.max(1, ruin.variants()); int height = pick(ruin.heightMin(), ruin.heightMax(), variantIndex, count, rng); int width = pick(ruin.widthMin(), ruin.widthMax(), variantIndex, count, rng); @@ -54,9 +54,9 @@ public final class RuinGenerator { applyBurial(ruin, canvas, height); applyErosion(ruin, canvas); - applyAccents(ruin, canvas, rng, data); + applyAccents(ruin, canvas, rng, blocks); - return resolve(ruin, canvas, data); + return resolve(ruin, canvas, blocks); } private static int pick(int lo, int hi, int variantIndex, int count, RNG rng) { @@ -121,18 +121,18 @@ public final class RuinGenerator { } } - private static void applyAccents(Ruin ruin, RuinBlockCanvas canvas, RNG rng, IrisData data) { + private static void applyAccents(Ruin ruin, RuinBlockCanvas canvas, RNG rng, ObjectBuilder blocks) { if (ruin.accents() == null || ruin.accents().isEmpty()) { return; } int decoratorIndex = 0; for (art.arcane.iris.builtin.objects.ruin.RuinDecorator decorator : ruin.accents()) { - RuinDecoratorApplier.apply(canvas, decorator, data, ruin.seed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); + RuinDecoratorApplier.apply(canvas, decorator, blocks, ruin.seed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); decoratorIndex++; } } - private static IrisObject resolve(Ruin ruin, RuinBlockCanvas canvas, IrisData data) { + private static ProceduralShape resolve(Ruin ruin, RuinBlockCanvas canvas, ObjectBuilder blocks) { if (canvas.cells().isEmpty()) { return null; } @@ -149,25 +149,25 @@ public final class RuinGenerator { } int span = Math.max(1, maxY - minY); - Map blocks = new HashMap<>(); + Map resolved = new HashMap<>(); for (Map.Entry entry : canvas.cells().entrySet()) { Vector3i v = entry.getKey(); RuinBlockCanvas.Cell cell = entry.getValue(); - PlatformBlockState bd; + BlockState bd; if (cell.role() == RuinBlockCanvas.Role.ACCENT) { bd = cell.accentData(); } else { - bd = structuralBlock(ruin, cell, v, data, paletteRng, scale, mossiness, weatherSeed, minY, span); + bd = structuralBlock(ruin, cell, v, blocks, paletteRng, scale, mossiness, weatherSeed, minY, span); } if (bd != null) { - blocks.put(v, bd); + resolved.put(v, bd); } } - return IrisProceduralBlocks.assemble(blocks); + return IrisProceduralBlocks.assemble(resolved); } - private static PlatformBlockState structuralBlock(Ruin ruin, RuinBlockCanvas.Cell cell, Vector3i v, IrisData data, RNG paletteRng, double scale, double mossiness, long weatherSeed, int minY, int span) { + private static BlockState structuralBlock(Ruin ruin, RuinBlockCanvas.Cell cell, Vector3i v, ObjectBuilder blocks, RNG paletteRng, double scale, double mossiness, long weatherSeed, int minY, int span) { boolean weathered = false; if (mossiness > 0.0) { int sx = (int) Math.round(v.getBlockX() * scale); @@ -180,12 +180,12 @@ public final class RuinGenerator { } if (weathered) { - PlatformBlockState wd = IrisProceduralBlocks.resolve(ruin.weatheredBlock(), ruin.weatheringPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + BlockState wd = IrisProceduralBlocks.resolve(ruin.weatheredBlock(), ruin.weatheringPalette(), blocks, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); if (wd != null) { return wd; } } - return IrisProceduralBlocks.resolve(ruin.block(), ruin.blockPalette(), data, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); + return IrisProceduralBlocks.resolve(ruin.block(), ruin.blockPalette(), blocks, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); } private static double clamp01(double value) { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java index 860f30d52..bf40fa8b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -18,12 +18,13 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.builtin.objects.ObjectBuilder; import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.object.ObjectBlock; +import com.volmit.world.BlockPosition; import java.util.ArrayList; import java.util.HashMap; @@ -36,7 +37,7 @@ public final class ProceduralTreeGenerator { private ProceduralTreeGenerator() { } - public static IrisObject generate(Tree tree, int height, RNG rng, IrisData data) { + public static ProceduralShape generate(Tree tree, int height, RNG rng, ObjectBuilder blocks) { TreeBlockCanvas canvas = new TreeBlockCanvas(); long baseSeed = rng.getSeed(); @@ -63,12 +64,12 @@ public final class ProceduralTreeGenerator { TreeSupport.ensureLeavesSupported(canvas, 24); } - Map resolved = new HashMap<>(); + Map resolved = new HashMap<>(); Set trunkPositions = new HashSet<>(); Set leafPositions = new HashSet<>(); for (Map.Entry entry : canvas.getCells().entrySet()) { TreeBlockCanvas.Cell cell = entry.getValue(); - PlatformBlockState state = TreeBlockResolver.resolve(tree, data, cell, entry.getKey()); + BlockState state = TreeBlockResolver.resolve(tree, blocks, cell, entry.getKey()); if (state == null) { continue; } @@ -80,12 +81,12 @@ public final class ProceduralTreeGenerator { } } - TreePlausibility.apply(resolved, trunkPositions, leafPositions, tree); + TreePlausibility.apply(resolved, trunkPositions, leafPositions, tree, blocks); return assemble(resolved); } - private static IrisObject assemble(Map resolved) { + private static ProceduralShape assemble(Map resolved) { if (resolved.isEmpty()) { return null; } @@ -112,15 +113,15 @@ public final class ProceduralTreeGenerator { int cy = h / 2; int cz = d / 2; - IrisObject object = new IrisObject(w, h, d); - for (Map.Entry entry : resolved.entrySet()) { + List placed = new ArrayList<>(resolved.size()); + for (Map.Entry entry : resolved.entrySet()) { TreeBlockCanvas.Vec v = entry.getKey(); int nx = v.x() - minX - cx; int ny = v.y() - cy + 1; int nz = v.z() - minZ - cz; - object.getBlocks().put(new IrisBlockVector(nx, ny, nz), entry.getValue()); + placed.add(new ObjectBlock(new BlockPosition(nx, ny, nz), entry.getValue())); } - return object; + return new ProceduralShape(w, h, d, placed); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java index 3a6004d29..bd47810ec 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -18,15 +18,16 @@ package art.arcane.iris.engine.object.procedural.tree; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import java.io.File; +import java.util.ArrayList; +import java.util.List; /** A procedural tree made placeable: its variants are baked by {@link ProceduralTreeGenerator}, at heights spread between its limits. */ public final class ResolvedTree extends ResolvedProceduralPlacement { @@ -36,10 +37,10 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { private final Tree settings; - public ResolvedTree(Tree settings) { + public ResolvedTree(Tree settings, ObjectHost host) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null))); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); this.settings = settings; } @@ -48,18 +49,23 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { } @Override - public boolean isPlausible() { + public boolean plausible() { return settings.plausible(); } @Override - protected IrisObject generate(int index, RNG rng, IrisData data) { + public boolean tree() { + return true; + } + + @Override + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { throw new UnsupportedOperationException("Tree variants are baked with heights spread over the limits"); } @Override - protected KList bake(IrisData data) { - KList baked = new KList<>(); + protected List bake(ObjectBuilder blocks) { + List baked = new ArrayList<>(); int count = Math.max(1, settings.variants()); int lo = Math.min(settings.heightMin(), settings.heightMax()); int hi = Math.max(settings.heightMin(), settings.heightMax()); @@ -67,17 +73,14 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { for (int i = 0; i < count; i++) { int height = variantHeight(heightRng, lo, hi, count, i); - IrisObject object = ProceduralTreeGenerator.generate(settings, Math.max(MINIMUM_HEIGHT, height), - new RNG(settings.seed() + (i * VARIANT_SEED_STRIDE)), data); - if (object == null || object.getBlocks().isEmpty()) { + ProceduralShape generated = ProceduralTreeGenerator.generate(settings, Math.max(MINIMUM_HEIGHT, height), + new RNG(settings.seed() + (i * VARIANT_SEED_STRIDE)), blocks); + if (generated == null || generated.blocks().isEmpty()) { continue; } - object.setLoadKey(getVariantLoadKey(i)); - object.setLoader(data); - baked.add(object); + baked.add(build(blocks, getVariantLoadKey(i), generated)); } - digestForGoldenDebug(baked); return baked; } @@ -90,18 +93,4 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { double jitter = heightRng.d(-step * HEIGHT_JITTER_FRACTION, step * HEIGHT_JITTER_FRACTION); return (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); } - - private static void digestForGoldenDebug(KList baked) { - if (!new File("plugins/Iris/goldendebug.txt").isFile()) { - return; - } - for (IrisObject object : baked) { - long[] digest = new long[]{0L}; - object.getBlocks().forEach((vector, state) -> { - long position = ((long) vector.getBlockX() << 40) ^ ((long) vector.getBlockY() << 20) ^ vector.getBlockZ(); - digest[0] ^= Long.rotateLeft(position * 0x9E3779B97F4A7C15L ^ state.key().hashCode(), (int) (position & 63)); - }); - IrisLogging.debug("Goldendebug bake: " + object.getLoadKey() + " blocks=" + object.getBlocks().size() + " digest=" + Long.toHexString(digest[0])); - } - } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java index 9fdcfa109..82c944f9d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java @@ -20,41 +20,40 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; import art.arcane.iris.builtin.objects.tree.TreeDecorator; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.builtin.objects.ObjectBuilder; import com.volmit.block.PaletteSpec; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.RNG; public final class TreeBlockResolver { private TreeBlockResolver() { } - public static PlatformBlockState resolve(Tree tree, IrisData data, TreeBlockCanvas.Cell cell, TreeBlockCanvas.Vec pos) { + public static BlockState resolve(Tree tree, ObjectBuilder blocks, TreeBlockCanvas.Cell cell, TreeBlockCanvas.Vec pos) { RNG paletteRng = new RNG(tree.seed()); RNG posRng = new RNG(tree.seed() ^ positionHash(pos)); switch (cell.role()) { case TRUNK -> { - PlatformBlockState state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), data, pos, paletteRng); - return finishTrunk(state, cell); + BlockState state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), blocks, pos, paletteRng); + return finishTrunk(state, cell, blocks); } case SECONDARY_TRUNK -> { - PlatformBlockState state = resolveBlock(tree.secondaryTrunk().orElse(null), tree.secondaryTrunkPalette().orElse(null), data, pos, paletteRng); + BlockState state = resolveBlock(tree.secondaryTrunk().orElse(null), tree.secondaryTrunkPalette().orElse(null), blocks, pos, paletteRng); if (state == null) { - state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), data, pos, paletteRng); + state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), blocks, pos, paletteRng); } - return finishTrunk(state, cell); + return finishTrunk(state, cell, blocks); } case LEAF -> { - return resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), data, pos, paletteRng); + return resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), blocks, pos, paletteRng); } case SECONDARY_LEAF -> { - PlatformBlockState state = resolveSecondaryLeaf(tree, data, pos, paletteRng, posRng); + BlockState state = resolveSecondaryLeaf(tree, blocks, pos, paletteRng, posRng); if (state == null) { - state = resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), data, pos, paletteRng); + state = resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), blocks, pos, paletteRng); } return state; } @@ -64,10 +63,10 @@ public final class TreeBlockResolver { return null; } TreeDecorator dec = tree.decorators().get(index); - PlatformBlockState state = resolveBlock(dec.block(), dec.palette().orElse(null), data, pos, paletteRng); + BlockState state = resolveBlock(dec.block(), dec.palette().orElse(null), blocks, pos, paletteRng); if (state != null && cell.facing() != null && IrisProceduralBlocks.hasProperty(state, "facing")) { try { - state = state.withProperty("facing", cell.facing().toLowerCase()); + state = blocks.withProperty(state, "facing", cell.facing().toLowerCase()); } catch (IllegalArgumentException ignored) { } } @@ -79,33 +78,33 @@ public final class TreeBlockResolver { } } - private static PlatformBlockState finishTrunk(PlatformBlockState state, TreeBlockCanvas.Cell cell) { + private static BlockState finishTrunk(BlockState state, TreeBlockCanvas.Cell cell, ObjectBuilder blocks) { if (state == null) { return null; } if (cell.axis() != TreeBlockCanvas.Axis.NONE && IrisProceduralBlocks.hasProperty(state, "axis")) { try { - state = state.withProperty("axis", cell.axis().name().toLowerCase()); + state = blocks.withProperty(state, "axis", cell.axis().name().toLowerCase()); } catch (IllegalArgumentException ignored) { } } if (cell.exposed()) { - return woodCap(state); + return woodCap(state, blocks); } return state; } - private static PlatformBlockState resolveSecondaryLeaf(Tree tree, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng, RNG posRng) { + private static BlockState resolveSecondaryLeaf(Tree tree, ObjectBuilder blocks, TreeBlockCanvas.Vec pos, RNG paletteRng, RNG posRng) { PaletteSpec secondaryPalette = tree.secondaryLeavesPalette().orElse(null); if (IrisProceduralBlocks.paletteSet(secondaryPalette)) { - return IrisProceduralBlocks.pick(secondaryPalette, data, paletteRng.getSeed(), pos.x(), pos.y(), pos.z()); + return blocks.pick(secondaryPalette, paletteRng.getSeed(), pos.x(), pos.y(), pos.z()); } if (tree.weightedSecondaryLeaves() != null && !tree.weightedSecondaryLeaves().isEmpty()) { String picked = pickWeighted(tree, posRng); - return picked == null ? null : B.getStateOrNull(picked, false); + return picked == null ? null : blocks.block(picked); } if (tree.secondaryLeaves().isPresent() && !tree.secondaryLeaves().get().isEmpty()) { - return B.getStateOrNull(tree.secondaryLeaves().get(), false); + return blocks.block(tree.secondaryLeaves().get()); } return null; } @@ -129,11 +128,11 @@ public final class TreeBlockResolver { return tree.weightedSecondaryLeaves().get(tree.weightedSecondaryLeaves().size() - 1).block(); } - private static PlatformBlockState resolveBlock(String block, PaletteSpec palette, IrisData data, TreeBlockCanvas.Vec pos, RNG paletteRng) { - return IrisProceduralBlocks.resolve(block, palette, data, pos.x(), pos.y(), pos.z(), paletteRng); + private static BlockState resolveBlock(String block, PaletteSpec palette, ObjectBuilder blocks, TreeBlockCanvas.Vec pos, RNG paletteRng) { + return IrisProceduralBlocks.resolve(block, palette, blocks, pos.x(), pos.y(), pos.z(), paletteRng); } - private static PlatformBlockState woodCap(PlatformBlockState state) { + private static BlockState woodCap(BlockState state, ObjectBuilder blocks) { String key = state.key(); int bracket = key.indexOf('['); String base = bracket < 0 ? key : key.substring(0, bracket); @@ -146,14 +145,14 @@ public final class TreeBlockResolver { if (woodKey == null) { return state; } - PlatformBlockState wood = B.getStateOrNull(woodKey, false); + BlockState wood = blocks.block(woodKey); if (wood == null) { return state; } String axis = IrisProceduralBlocks.propertyValue(state, "axis"); if (axis != null && IrisProceduralBlocks.hasProperty(wood, "axis")) { try { - wood = wood.withProperty("axis", axis); + wood = blocks.withProperty(wood, "axis", axis); } catch (IllegalArgumentException ignored) { } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java index e62b28499..71e441cc6 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java @@ -20,7 +20,8 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.builtin.objects.ObjectBuilder; +import com.volmit.block.BlockState; import java.util.ArrayDeque; import java.util.HashMap; @@ -37,11 +38,11 @@ public final class TreePlausibility { private TreePlausibility() { } - public static void apply(Map resolved, Set trunkPositions, - Set leafPositions, Tree tree) { + public static void apply(Map resolved, Set trunkPositions, + Set leafPositions, Tree tree, ObjectBuilder blocks) { Set realLeaves = new HashSet<>(); for (TreeBlockCanvas.Vec v : leafPositions) { - PlatformBlockState state = resolved.get(v); + BlockState state = resolved.get(v); if (state != null && IrisProceduralBlocks.hasProperty(state, "persistent") && IrisProceduralBlocks.hasProperty(state, "distance")) { realLeaves.add(v); } @@ -53,19 +54,23 @@ public final class TreePlausibility { Map distance = computeDistances(trunkPositions, realLeaves); for (TreeBlockCanvas.Vec v : realLeaves) { - PlatformBlockState leaf = resolved.get(v); + BlockState leaf = resolved.get(v); Integer d = distance.get(v); if (!tree.plausible()) { - leaf = leaf.withProperty("persistent", "true").withProperty("distance", "1"); + leaf = withLeafState(blocks, leaf, "true", "1"); } else if (d != null && d < MAX_DISTANCE) { - leaf = leaf.withProperty("persistent", "false").withProperty("distance", String.valueOf(Math.max(1, d))); + leaf = withLeafState(blocks, leaf, "false", String.valueOf(Math.max(1, d))); } else { - leaf = leaf.withProperty("persistent", "true").withProperty("distance", String.valueOf(MAX_DISTANCE)); + leaf = withLeafState(blocks, leaf, "true", String.valueOf(MAX_DISTANCE)); } resolved.put(v, leaf); } } + private static BlockState withLeafState(ObjectBuilder blocks, BlockState leaf, String persistent, String distance) { + return blocks.withProperty(blocks.withProperty(leaf, "persistent", persistent), "distance", distance); + } + static Map computeDistances(Set trunkPositions, Set realLeaves) { Map distance = new HashMap<>(); ArrayDeque queue = new ArrayDeque<>(); From 2ae16b9c9e9d14a8a250c163433930c1b0638f56 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 12:36:10 +0200 Subject: [PATCH 089/139] Floating islands generate in the built-ins jar FloatingModule, FloatingIslands, the island sampling and the floating object placing move to the jar on IrisApi types. Iris answers through a FloatingHost facade: surface biomes, biome lookups and heights, sky biome painting, object footprints, shrinking and the placement of an object against an island face (IslandAnchor). FloatingChildren becomes the per-world FloatingWorld, IslandObjectPlacer the jar's IslandFace, and UndersideTurn turns a footprint the way Iris's flipped rotation does. The island memos key columns by a Column record instead of packed longs, whose Long hash collides along diagonals. --- builtin-modules.txt | 7 + .../builtin/floating/FloatingChildBiome.java | 22 +- .../iris/builtin/floating/FloatingHost.java | 93 ++ .../iris/builtin/floating/IslandAnchor.java | 37 + .../builtin/floating/IslandFootprint.java | 38 + .../FloatingIslandSampleResolver.java | 70 +- .../FloatingObjectPlacementTransaction.java | 12 +- .../components/FloatingObjectPlacing.java | 831 +++++++----------- .../mantle/components/IslandAnchorPlacer.java | 128 +++ .../engine/mantle/components/IslandFace.java | 141 +++ .../mantle/components/IslandObjectPlacer.java | 220 ----- .../mantle/components/UndersideTurn.java | 40 + .../iris/engine/modifier/FloatingIslands.java | 602 +++++++------ .../iris/engine/modifier/FloatingModule.java | 34 +- .../iris/engine/modifier/IrisLayers.java | 111 --- .../terrain/floating/Column.java} | 20 +- .../terrain/floating/FloatingChildren.java | 69 -- .../FloatingIslandBoundarySampler.java | 102 ++- .../floating/FloatingIslandEdgeProfile.java | 8 +- .../floating/FloatingIslandSample.java | 145 ++- .../terrain/floating/FloatingWorld.java | 155 ++++ .../floating/ResolvedFloatingChild.java | 230 ++--- 22 files changed, 1574 insertions(+), 1541 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java create mode 100644 src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java create mode 100644 src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IslandAnchorPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java delete mode 100644 src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java rename src/main/java/art/arcane/iris/engine/{modifier/IrisDecoratedBiomes.java => object/terrain/floating/Column.java} (54%) delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java create mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 8935c8a35..83c2e59b2 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -84,3 +84,10 @@ include art/arcane/iris/engine/mantle/components/ObjectWarmUp*.class include art/arcane/iris/engine/mantle/components/ObjectLocating*.class include art/arcane/iris/engine/mantle/components/TreeGrowing*.class include art/arcane/iris/engine/object/procedural/** +module art.arcane.iris.engine.modifier.FloatingModule +include art/arcane/iris/engine/modifier/FloatingIslands*.class +include art/arcane/iris/engine/object/terrain/floating/** +include art/arcane/iris/engine/mantle/components/FloatingObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver*.class +include art/arcane/iris/engine/mantle/components/IslandFace*.class +include art/arcane/iris/engine/mantle/components/UndersideTurn*.class diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java index efd8dd462..3702ab55f 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.floating; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; @@ -37,9 +37,7 @@ import java.util.OptionalInt; /** * A floating island above a biome's terrain, an entry of the biome's {@code floatingChildBiomes}: where its footprint * is, how high it floats, how its top, underside and walls are shaped, and which objects, decorators and water it - * gets. Noise and options are IrisApi types; the object placements and palette layers the island hosts are - * Iris's own classes, which the host describes itself, so this class leaves the pack module jar only when those - * become settings of modules. + * gets. */ @Snippet("floating-child-biome") @Desc("Declares a floating biome layer above this biome's terrain. A 2D footprint noise decides which columns are part of the island (threshold + style control blankets, swirls, scattered blobs). The top profile is driven by the target biome's own terrain generators (so a mountains biome produces real peaks, desert produces real dunes). The bottom tail hanging below is a separately configurable noise (pick VASCULAR for drippy roots, FRACTAL_RM_SIMPLEX for crystalline spikes, PERLIN for smooth rounded bowls).") @@ -195,11 +193,11 @@ public final class FloatingChildBiome { @MinItems(1) @Desc("Additional object placements anchored to the island top.") - private List extraObjects = List.of(); + private List extraObjects = List.of(); @MinItems(1) @Desc("Additional object placements that float freely in air, independent of the island. Forced to ObjectPlaceMode.FLOATING.") - private List floatingObjects = List.of(); + private List floatingObjects = List.of(); @Desc("Visualization color for this floating child in Iris Studio.") private String color = null; @@ -212,11 +210,11 @@ public final class FloatingChildBiome { @MinItems(1) @Desc("Object placements that override or supplement the inherited surface objects on the island TOP. Behaviour depends on topObjectMode. INHERIT_ONLY = this list is ignored. MERGE = appended after inherited. REPLACE = used instead of inherited.") - private List topObjectOverrides = List.of(); + private List topObjectOverrides = List.of(); @MinItems(1) @Desc("Object placements anchored to the island BOTTOM face. Each entry is auto-inverted 180 degrees around the X axis and placed flush against the lowest solid face of the island, so objects appear to hang upside-down from the underside. WARNING: directional blocks (stairs, doors, slabs) will not render correctly when flipped — use non-directional content (logs, leaves, stone, mycelium, ice, glass) for bottom placements.") - private List bottomObjectOverrides = List.of(); + private List bottomObjectOverrides = List.of(); public FloatingChildBiome() { } @@ -366,11 +364,11 @@ public final class FloatingChildBiome { return objectShrinkFactor; } - public List extraObjects() { + public List extraObjects() { return extraObjects == null ? List.of() : Collections.unmodifiableList(extraObjects); } - public List floatingObjects() { + public List floatingObjects() { return floatingObjects == null ? List.of() : Collections.unmodifiableList(floatingObjects); } @@ -386,11 +384,11 @@ public final class FloatingChildBiome { return bottomObjectMode == null ? OverrideMode.INHERIT_ONLY : bottomObjectMode; } - public List topObjectOverrides() { + public List topObjectOverrides() { return topObjectOverrides == null ? List.of() : Collections.unmodifiableList(topObjectOverrides); } - public List bottomObjectOverrides() { + public List bottomObjectOverrides() { return bottomObjectOverrides == null ? List.of() : Collections.unmodifiableList(bottomObjectOverrides); } } diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java new file mode 100644 index 000000000..e862eb7bd --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java @@ -0,0 +1,93 @@ +/* + * 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.builtin.floating; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.PackSettings; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * What {@code iris:floating} asks of Iris beyond the API: the biome of any column, a biome's own terrain height, the sky + * biome an island paints, and placing Iris objects against an island. Iris's worlds implement it; a module reaches it + * with {@link #of}. + */ +public interface FloatingHost { + /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ + static FloatingHost of(PackSettings settings) { + if (settings instanceof Source source) { + return source.floating(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); + } + + /** The host of {@code world}, which must be a world Iris generates. */ + static FloatingHost of(PackWorld world) { + if (world instanceof Source source) { + return source.floating(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** The biome of the column's surface, the biome an island grows from; any column, not only the chunk's. */ + ResourceId surfaceBiome(int worldX, int worldZ); + + /** The biome {@code key} names in the pack; empty when the pack has none. */ + Optional biome(String key); + + /** The height the terrain generators of {@code biome} give the column, as Iris shapes the biome's terrain with {@code seed}. */ + double biomeHeight(ResourceId biome, int worldX, int worldZ, long seed); + + /** + * Paints the sky biome {@code biome} stands for at the column into the blocks {@code ys} of the mantle, where the biome + * pass finds it. {@code random} seeds the biome's generator the first time the biome is asked. + */ + void paintSkyBiome(ResourceId biome, int worldX, int worldZ, int[] ys, RNG random); + + /** Where {@code object} stands: its solid columns, its tallest column and that column's lowest solid block. */ + IslandFootprint footprint(PlaceableObject object); + + /** {@code object} shrunk by {@code factor} (below 1), the variant picked with {@code random}. */ + Optional shrink(PlaceableObject object, double factor, RNG random); + + /** Places {@code object} floating free at the column, into the chunk the mantle is generating. */ + void placeFloating(PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, RNG random); + + /** + * Places {@code object} on an island's top, its lowest block at {@code y}, into the chunk the mantle is generating; nothing + * is written unless every block it writes is one {@code anchor} lets it write. + */ + void placeOnTop(PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement, IslandAnchor anchor, RNG random); + + /** + * Places {@code object} upside down under an island, turned {@code yRotation} degrees about Y, as {@link #placeOnTop} does + * on top. + */ + void placeUnder(PlaceableObject object, int worldX, int y, int worldZ, int yRotation, ObjectPlacement placement, + IslandAnchor anchor, RNG random); + + /** A world that hands out its {@link FloatingHost}. */ + interface Source { + FloatingHost floating(); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java b/src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java new file mode 100644 index 000000000..90c8d2086 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java @@ -0,0 +1,37 @@ +/* + * 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.builtin.floating; + +/** + * The face of one island an object is placed against, as {@code iris:floating} samples it: how high the face is, which + * blocks of the island are solid, and where the object may write without hanging in the air beside the island. + */ +public interface IslandAnchor { + /** The height of the face at the column; the anchor's own height where the island does not reach. */ + int faceY(int worldX, int worldZ); + + /** Whether an island lies in the column; where none does, the world's blocks say what is solid. */ + boolean hasIsland(int worldX, int worldZ); + + /** Whether the island of the column fills the block. */ + boolean islandSolid(int worldX, int y, int worldZ); + + /** Whether the object may write the block. */ + boolean writes(int worldX, int y, int worldZ); +} diff --git a/src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java b/src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java new file mode 100644 index 000000000..3f25bebc8 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java @@ -0,0 +1,38 @@ +/* + * 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.builtin.floating; + +/** + * Where an object stands, in its own block positions: the columns holding a solid block ({@link #column} packs each), the + * tallest of them (most solid blocks, the lowest bottom on a tie) and the lowest solid block of that column. + */ +public record IslandFootprint(int tallestX, int tallestZ, int lowestSolidY, long[] columns) { + /** The column {@code x}, {@code z} packed as {@link #columns} holds it. */ + public static long column(int x, int z) { + return ((long) x << 32) | (z & 0xFFFFFFFFL); + } + + public static int columnX(long column) { + return (int) (column >> 32); + } + + public static int columnZ(long column) { + return (int) (column & 0xFFFFFFFFL); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java index 825ef326e..8560fcea7 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver.java @@ -1,5 +1,5 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers + * 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 @@ -18,61 +18,51 @@ 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.mantle.EngineMantle; -import art.arcane.iris.engine.modifier.FloatingIslands; -import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; +import art.arcane.iris.engine.object.terrain.floating.Column; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; -import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import org.jetbrains.annotations.Nullable; +import com.volmit.resource.ResourceId; -final class FloatingIslandSampleResolver implements IslandObjectPlacer.SampleProvider { - private final IrisData data; - private final Engine engine; - private final int chunkHeight; - private final long baseSeed; +import java.util.HashMap; +import java.util.Map; + +/** The island samples of the columns one chunk's floating objects ask about, each sampled once; null where no island is. */ +final class FloatingIslandSampleResolver implements IslandFace.SampleProvider { + private final FloatingWorld world; + private final int worldHeight; private final FloatingIslandBoundarySampler boundarySampler; - private final Long2ObjectOpenHashMap sampleCache; - private final LongOpenHashSet resolvedSamples; + private final Map samples = new HashMap<>(); private final ModuleLog log; - FloatingIslandSampleResolver(EngineMantle engineMantle, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { - this.data = engineMantle.getData(); - this.engine = engineMantle.getEngine(); - this.chunkHeight = engine.getHeight(); - this.baseSeed = engine.getSeedManager().getTerrain() ^ FloatingIslands.FLOATING_BASE_SEED_SALT; + FloatingIslandSampleResolver(FloatingWorld world, int worldHeight, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + this.world = world; + this.worldHeight = worldHeight; this.boundarySampler = boundarySampler; this.log = log; - this.sampleCache = new Long2ObjectOpenHashMap<>(); - this.resolvedSamples = new LongOpenHashSet(); } @Override - public @Nullable FloatingIslandSample sample(int x, int z) { - long key = CacheKey.key(x, z); - if (resolvedSamples.contains(key)) { - return sampleCache.get(key); - } - IrisBiome parent = parent(x, z); - if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { - resolvedSamples.add(key); - return null; - } - FloatingIslandSample sample = FloatingIslandSample.sample(parent, x, z, chunkHeight, baseSeed, data, engine, boundarySampler, log); - resolvedSamples.add(key); - if (sample != null) { - sampleCache.put(key, sample); + public FloatingIslandSample sample(int x, int z) { + Column key = new Column(x, z); + if (samples.containsKey(key)) { + return samples.get(key); } + FloatingIslandSample sample = resolve(x, z); + samples.put(key, sample); return sample; } - @Nullable IrisBiome parent(int x, int z) { + private FloatingIslandSample resolve(int x, int z) { + ResourceId parent = parent(x, z); + if (parent == null || world.declaredBy(parent).isEmpty()) { + return null; + } + return FloatingIslandSample.sample(parent, x, z, worldHeight, world, boundarySampler, log); + } + + ResourceId parent(int x, int z) { return boundarySampler.parent(x, 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 index b956544bd..c88f54e1c 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java @@ -30,19 +30,19 @@ import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; -final class FloatingObjectPlacementTransaction implements IObjectPlacer { - private final IslandObjectPlacer delegate; +public final class FloatingObjectPlacementTransaction implements IObjectPlacer { + private final IslandAnchorPlacer delegate; private final KList mutations; private final Map bufferedBlocks; private int blockWrites; - FloatingObjectPlacementTransaction(IslandObjectPlacer delegate) { + public FloatingObjectPlacementTransaction(IslandAnchorPlacer delegate) { this.delegate = delegate; this.mutations = new KList<>(); this.bufferedBlocks = new HashMap<>(); } - CommitResult commit() { + public CommitResult commit() { if (blockWrites == 0) { discard(); return CommitResult.EMPTY; @@ -60,7 +60,7 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer { return CommitResult.COMMITTED; } - void discard() { + public void discard() { mutations.clear(); bufferedBlocks.clear(); blockWrites = 0; @@ -167,7 +167,7 @@ final class FloatingObjectPlacementTransaction implements IObjectPlacer { return delegate.getEngine(); } - enum CommitResult { + public enum CommitResult { COMMITTED, EMPTY, REJECTED_SUPPORT diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index aa5359c4a..df128ed41 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -18,413 +18,311 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; +import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.builtin.floating.FloatingHost; +import art.arcane.iris.builtin.floating.IslandFootprint; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSize; +import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; -import art.arcane.iris.engine.object.placement.FloatingObjectFootprint; -import art.arcane.iris.engine.object.placement.IrisObjectVacuum; -import art.arcane.iris.engine.object.placement.IObjectPlacer; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.IrisObjectRotation; -import art.arcane.iris.engine.object.prefab.IrisObjectTranslate; -import art.arcane.iris.engine.object.prefab.IrisObjectShaping; -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.context.ChunkContext; +import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; import art.arcane.volmlib.util.math.RNG; - +import com.volmit.FeatureAttachment.Target; import com.volmit.ModuleLog; -import java.io.File; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.BlockPosition; +import com.volmit.world.PackWorld; + import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; /** * Places the objects of floating child biomes on and under their islands into the mantle for - * {@link art.arcane.iris.engine.modifier.FloatingModule}. One per engine runtime. Its reach is the - * largest placement reach of any floating object the dimension's biomes can place, at least 16 blocks. + * {@link art.arcane.iris.engine.modifier.FloatingModule}. One per world. Its reach is the largest placement reach of any + * floating object the dimension's biomes can place, at least 16 blocks. */ -public class FloatingObjectPlacing { +public final class FloatingObjectPlacing { private static final int INVERTED_PICK_ATTEMPTS = 8; - private static final IrisObjectRotation ROTATION_NONE = IrisObjectRotation.of(0, 0, 0); + private static final long CHUNK_RANDOM_SALT = 0x0FA710BEL; + private static final int CHUNK_SHIFT = 4; + private static final int CHUNK_COLUMNS = 256; + private static final int MIN_REACH_BLOCKS = 16; + private static final int LARGE_REACH_WARNING_BLOCKS = 128; + private static final int FLAT_TOLERANCE_BLOCKS = 2; + private static final int LOOSE_FLAT_TOLERANCE_BLOCKS = 4; + private static final int QUARTER_TURN_DEGREES = 90; + private static final int QUARTER_TURNS = 4; + private static final double CHANCE_JITTER = 0.005; + private static final String BIOME_PATH_PREFIX = "biome/"; - private final Engine engine; + private final FloatingWorld world; + private final FloatingHost host; + private final ObjectHost objects; + private final long mantleSeed; private final ModuleLog log; - public FloatingObjectPlacing(Engine engine, ModuleLog log) { - this.engine = engine; + FloatingObjectPlacing(FloatingWorld world, long mantleSeed, ModuleLog log) { + this.world = world; + this.host = world.host(); + this.objects = world.objects(); + this.mantleSeed = mantleSeed; this.log = log; } - /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ - public void place(MantleWriter writer, int x, int z, ChunkContext context) { - IrisComplex complex = context.getComplex(); - IrisData data = engine.getData(); - int minX = x << 4; - int minZ = z << 4; - RNG chunkRng = new RNG(CacheKey.key(x, z) + engine.getSeedManager().getMantle() + 0x0FA710BEL); - FloatingIslandSampleResolver sampleResolver = new FloatingIslandSampleResolver(engine.getMantle(), context.getFloatingIslandBoundarySampler(), log); + /** The floating object placing of {@code world}. */ + public static FloatingObjectPlacing of(PackWorld world, ModuleLog log) { + return world.state(FloatingObjectPlacing.class, + generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), IrisSeed.MANTLE.of(generating), log)); + } + + /** Places what originates in the chunk of {@code context} into the mantle. */ + public void place(MantleStageContext context) { + int minX = context.originX(); + int minZ = context.originZ(); + BlockBox bounds = context.terrain().bounds(); + int worldHeight = bounds.maxY() - bounds.minY(); + RNG chunkRng = new RNG(CacheKey.key(minX >> CHUNK_SHIFT, minZ >> CHUNK_SHIFT) + mantleSeed + CHUNK_RANDOM_SALT); + FloatingIslandSampleResolver samples = new FloatingIslandSampleResolver(world, worldHeight, + new FloatingIslandBoundarySampler(host::surfaceBiome), log); FloatingIslandSample.clearChunkMemo(); + Chunk chunk = new Chunk(minX, minZ, worldHeight, chunkRng, samples, sampleColumns(samples, minX, minZ)); - FloatingIslandSample[] samples = new FloatingIslandSample[256]; - for (int xf = 0; xf < 16; xf++) { - for (int zf = 0; zf < 16; zf++) { - int wx = minX + xf; - int wz = minZ + zf; - FloatingIslandSample sample = sampleResolver.sample(wx, wz); - if (sample != null) { - samples[(zf << 4) | xf] = sample; - } - } - } - - // The IdentityHashMaps are lookup indices only. Iteration MUST follow the encounter - // order of the deterministic 0..255 column scan: identity-hash order changes per JVM - // run, and the shared chunkRng makes placement output depend on iteration order. - IdentityHashMap> entryColumns = new IdentityHashMap<>(); - IdentityHashMap> bottomEntryColumns = new IdentityHashMap<>(); + // The maps are lookup indices only. Iteration MUST follow the encounter order of the deterministic 0..255 column + // scan: identity-hash order changes per JVM run, and the shared chunk random makes placement output depend on order. + Map> entryColumns = new IdentityHashMap<>(); + Map> bottomEntryColumns = new IdentityHashMap<>(); KList entryOrder = new KList<>(); KList bottomEntryOrder = new KList<>(); - for (int i = 0; i < 256; i++) { - FloatingIslandSample s = samples[i]; - if (s == null || s.entry == null) { + for (int i = 0; i < CHUNK_COLUMNS; i++) { + FloatingIslandSample sample = chunk.samples[i]; + if (sample == null || sample.entry == null) { continue; } - entryColumns.computeIfAbsent(s.entry, e -> { - entryOrder.add(e); + int column = i; + entryColumns.computeIfAbsent(sample.entry, entry -> { + entryOrder.add(entry); return new KList<>(); - }).add(i); - ResolvedFloatingChild bottomEntry = s.bottomEntry(); + }).add(column); + ResolvedFloatingChild bottomEntry = sample.bottomEntry(); if (bottomEntry != null) { - bottomEntryColumns.computeIfAbsent(bottomEntry, e -> { - bottomEntryOrder.add(e); + bottomEntryColumns.computeIfAbsent(bottomEntry, entry -> { + bottomEntryOrder.add(entry); return new KList<>(); - }).add(i); + }).add(column); } } for (ResolvedFloatingChild entry : entryOrder) { - KList columns = entryColumns.get(entry); - if (columns.isEmpty()) { - continue; - } - - int firstKey = columns.get(0); - IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4)); - IrisBiome target = entry.getRealBiome(parent, data); - - KList floating = new KList<>(entry.settings().floatingObjects()); - if (floating != null && !floating.isEmpty()) { - for (IrisObjectPlacement placement : floating) { - tryPlaceFloatingChunk(writer, complex, chunkRng, data, placement, columns, minX, minZ, entry); - } - } - - KList surface = target != null ? entry.resolveTopObjects(target) : null; - KList extras = new KList<>(entry.settings().extraObjects()); - boolean hasSurface = surface != null && !surface.isEmpty(); - boolean hasExtras = extras != null && !extras.isEmpty(); - KList interior = null; - if (hasSurface || hasExtras) { - interior = interiorColumns(sampleResolver, columns, minX, minZ, entry, IslandObjectPlacer.AnchorFace.TOP); - if (hasSurface) { - for (IrisObjectPlacement placement : surface) { - tryPlaceAnchoredChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry); - } - } - if (hasExtras) { - for (IrisObjectPlacement placement : extras) { - tryPlaceAnchoredChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry); - } - } - } + placeOnTop(chunk, entry, entryColumns.get(entry)); } - for (ResolvedFloatingChild entry : bottomEntryOrder) { - KList columns = bottomEntryColumns.get(entry); - if (columns.isEmpty()) { - continue; - } - - int firstKey = columns.get(0); - IrisBiome parent = sampleResolver.parent(minX + (firstKey & 15), minZ + (firstKey >> 4)); - IrisBiome target = entry.getRealBiome(parent, data); - KList bottom = target != null ? entry.resolveBottomObjects(target) : null; - if (bottom != null && !bottom.isEmpty()) { - KList interior = interiorColumns(sampleResolver, columns, minX, minZ, entry, IslandObjectPlacer.AnchorFace.BOTTOM); - for (IrisObjectPlacement placement : bottom) { - tryPlaceInvertedChunk(writer, complex, chunkRng, data, placement, samples, sampleResolver, columns, interior, minX, minZ, entry); - } - } + placeUnder(chunk, entry, bottomEntryColumns.get(entry)); } } - @ChunkCoordinates - private void tryPlaceFloatingChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, KList columns, int minX, int minZ, ResolvedFloatingChild entry) { - if (placement == null || columns == null || columns.isEmpty()) { + private static FloatingIslandSample[] sampleColumns(FloatingIslandSampleResolver samples, int minX, int minZ) { + FloatingIslandSample[] sampled = new FloatingIslandSample[CHUNK_COLUMNS]; + for (int xf = 0; xf < 16; xf++) { + for (int zf = 0; zf < 16; zf++) { + sampled[(zf << 4) | xf] = samples.sample(minX + xf, minZ + zf); + } + } + return sampled; + } + + private void placeOnTop(Chunk chunk, ResolvedFloatingChild entry, KList columns) { + if (columns.isEmpty()) { return; } - int density = placement.getDensity(rng, minX, minZ, data); - double perAttempt = placement.getChance(); - for (int i = 0; i < density; i++) { - if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { - continue; - } - IrisObject raw = placement.getObject(complex, rng); - if (raw == null) { - continue; - } - IrisObject obj0 = placement.getScale().get(rng, raw, engine); - if (obj0 == null) { - continue; - } - if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0, engine); - if (obj0 == null) { - continue; - } - } - final IrisObject obj = obj0; + ResourceId target = targetOf(chunk, entry, columns); + for (ObjectPlacement placement : entry.settings().floatingObjects()) { + placeFloating(chunk, placement, columns, entry); + } + + KList surface = target != null ? entry.resolveTopObjects(target) : null; + List extras = entry.settings().extraObjects(); + boolean hasSurface = surface != null && !surface.isEmpty(); + if (!hasSurface && extras.isEmpty()) { + return; + } + KList interior = interiorColumns(chunk, columns, entry, IslandFace.Side.TOP); + if (hasSurface) { + for (ObjectPlacement placement : surface) { + placeAnchored(chunk, placement, columns, interior, entry); + } + } + for (ObjectPlacement placement : extras) { + placeAnchored(chunk, placement, columns, interior, entry); + } + } + + private void placeUnder(Chunk chunk, ResolvedFloatingChild entry, KList columns) { + if (columns.isEmpty()) { + return; + } + ResourceId target = targetOf(chunk, entry, columns); + KList bottom = target != null ? entry.resolveBottomObjects() : null; + if (bottom == null || bottom.isEmpty()) { + return; + } + KList interior = interiorColumns(chunk, columns, entry, IslandFace.Side.BOTTOM); + for (ObjectPlacement placement : bottom) { + placeInverted(chunk, placement, columns, interior, entry); + } + } + + /** The biome the child's objects come from, its parent taken at the first of its columns. */ + private ResourceId targetOf(Chunk chunk, ResolvedFloatingChild entry, KList columns) { + int firstKey = columns.get(0); + ResourceId parent = chunk.resolver.parent(chunk.minX + (firstKey & 15), chunk.minZ + (firstKey >> 4)); + return entry.realBiome(parent); + } + + private void placeFloating(Chunk chunk, ObjectPlacement placement, KList columns, ResolvedFloatingChild entry) { + RNG rng = chunk.rng; + int density = objects.density(placement, rng, chunk.minX, chunk.minZ); + for (int i = 0; i < density; i++) { + Optional picked = pick(placement, entry, rng); + if (picked.isEmpty()) { + continue; + } int key = columns.get(rng.i(columns.size())); - int xx = minX + (key & 15); - int zz = minZ + (key >> 4); - IrisObjectPlacement floatingPlacement = placement.toPlacement(obj.getLoadKey()); - int id = rng.i(0, Integer.MAX_VALUE); - - try { - obj.place(xx, -1, zz, writer, floatingPlacement, rng, (b, bd) -> { - String marker = placementMarker(obj, id); - if (marker != null && shouldWritePlacementMarker(writer, bd, b.getX(), b.getY(), b.getZ())) { - writer.setData(b.getX(), b.getY(), b.getZ(), marker); - } - }, null, data); - } catch (Throwable e) { - log.error("Failed to place a floating object", e); - } + host.placeFloating(picked.get(), chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng); } } - @ChunkCoordinates - private void tryPlaceAnchoredChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, ResolvedFloatingChild entry) { - if (placement == null || columns.isEmpty()) { - return; - } - int density = placement.getDensity(rng, minX, minZ, data); - double perAttempt = placement.getChance(); - + private void placeAnchored(Chunk chunk, ObjectPlacement placement, KList columns, KList interior, + ResolvedFloatingChild entry) { + RNG rng = chunk.rng; + int density = objects.density(placement, rng, chunk.minX, chunk.minZ); for (int i = 0; i < density; i++) { - if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { + Optional picked = pick(placement, entry, rng); + if (picked.isEmpty()) { continue; } - - IrisObject raw = placement.getObject(complex, rng); - if (raw == null) { - continue; - } - IrisObject obj0 = placement.getScale().get(rng, raw, engine); - if (obj0 == null) { - continue; - } - if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0, engine); - if (obj0 == null) { - continue; - } - } - final IrisObject obj = obj0; - - FloatingObjectFootprint fp = FloatingObjectFootprint.compute(obj); + PlaceableObject object = picked.get(); + IslandFootprint footprint = host.footprint(object); KList pool = interior.isEmpty() ? columns : interior; - int pickedKey = pool.get(rng.i(pool.size())); int pickedXf = pickedKey & 15; int pickedZf = pickedKey >> 4; - FloatingIslandSample pickedSample = samples[(pickedZf << 4) | pickedXf]; + FloatingIslandSample pickedSample = chunk.samples[(pickedZf << 4) | pickedXf]; if (pickedSample == null) { continue; } int pickTopY = pickedSample.topY(); - - int pickedX = minX + pickedXf; - int pickedZ = minZ + pickedZf; - if (!isFootprintFlat(fp, pickedX, pickedZ, pickTopY, sampleProvider, entry, 2)) { - if (!isFootprintFlat(fp, pickedX, pickedZ, pickTopY, sampleProvider, entry, 4)) { - continue; - } + int pickedX = chunk.minX + pickedXf; + int pickedZ = chunk.minZ + pickedZf; + if (!isFootprintFlat(footprint, pickedX, pickedZ, pickTopY, chunk.resolver, entry, FLAT_TOLERANCE_BLOCKS) + && !isFootprintFlat(footprint, pickedX, pickedZ, pickTopY, chunk.resolver, entry, LOOSE_FLAT_TOLERANCE_BLOCKS)) { + continue; } - int wx = minX + pickedXf - fp.getTallestKx(); - int wz = minZ + pickedZf - fp.getTallestKz(); - - IrisObjectPlacement anchored = placement.toPlacement(obj.getLoadKey()); - anchored.setMode(anchored.getMode().onFloatingIsland()); - anchored.setTranslate(new IrisObjectTranslate()); - anchored.setRotation(ROTATION_NONE); - anchored.setForcePlace(true); - anchored.setBottom(false); - - int yv = pickTopY + 1 - fp.getLowestSolidKeyY(); - - IslandObjectPlacer islandPlacer = IslandObjectPlacer.top(writer, sampleProvider, entry, pickTopY); - FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(islandPlacer); - int id = rng.i(0, Integer.MAX_VALUE); - - try { - int resultY = obj.place(wx, yv, wz, transaction, anchored, rng, (b, bd) -> { - String marker = placementMarker(obj, id); - if (marker != null && shouldWritePlacementMarker(transaction, bd, b.getX(), b.getY(), b.getZ())) { - transaction.setData(b.getX(), b.getY(), b.getZ(), marker); - } - }, null, data); - if (resultY < 0) { - transaction.discard(); - } else { - transaction.commit(); - } - } catch (Throwable e) { - transaction.discard(); - log.error("Failed to place an anchored floating object", e); - } + int x = pickedX - footprint.tallestX(); + int z = pickedZ - footprint.tallestZ(); + int y = pickTopY + 1 - footprint.lowestSolidY(); + host.placeOnTop(object, x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng); } } - @ChunkCoordinates - private void tryPlaceInvertedChunk(MantleWriter writer, IrisComplex complex, RNG rng, IrisData data, IrisObjectPlacement placement, FloatingIslandSample[] samples, IslandObjectPlacer.SampleProvider sampleProvider, KList columns, KList interior, int minX, int minZ, ResolvedFloatingChild entry) { - if (placement == null || columns.isEmpty()) { - return; - } - int density = placement.getDensity(rng, minX, minZ, data); - double perAttempt = placement.getChance(); - + private void placeInverted(Chunk chunk, ObjectPlacement placement, KList columns, KList interior, + ResolvedFloatingChild entry) { + RNG rng = chunk.rng; + int density = objects.density(placement, rng, chunk.minX, chunk.minZ); for (int i = 0; i < density; i++) { - if (!rng.chance(perAttempt + rng.d(-0.005, 0.005))) { + Optional picked = pick(placement, entry, rng); + if (picked.isEmpty()) { continue; } + PlaceableObject object = picked.get(); + IslandFootprint footprint = host.footprint(object); + UndersideTurn turn = new UndersideTurn(rng.i(QUARTER_TURNS) * QUARTER_TURN_DEGREES); - IrisObject raw = placement.getObject(complex, rng); - if (raw == null) { + Optional anchor = pickBottomAnchor(chunk, footprint, turn, interior.isEmpty() ? columns : interior, entry); + if (anchor.isEmpty()) { continue; } - IrisObject obj0 = placement.getScale().get(rng, raw, engine); - if (obj0 == null) { - continue; - } - if (entry != null && entry.hasObjectShrink()) { - obj0 = entry.getShrinkScale().get(rng, obj0, engine); - if (obj0 == null) { - continue; - } - } - final IrisObject obj = obj0; - - FloatingObjectFootprint fp = FloatingObjectFootprint.compute(obj); - int invertedYRotation = rng.i(4) * 90; - IrisObjectRotation invertedRotation = IrisObjectRotation.xFlip180WithY(invertedYRotation); - - KList pool = interior.isEmpty() ? columns : interior; - - int pickedXf = -1; - int pickedZf = -1; - int pickBottomY = -1; - boolean foundBottomAnchor = false; - for (int attempt = 0; attempt < INVERTED_PICK_ATTEMPTS; attempt++) { - int pickedKey = pool.get(rng.i(pool.size())); - int candidateXf = pickedKey & 15; - int candidateZf = pickedKey >> 4; - FloatingIslandSample candidateSample = samples[(candidateZf << 4) | candidateXf]; - if (candidateSample == null) { - continue; - } - int candidateBottomY = candidateSample.bottomY(); - if (candidateBottomY < 0) { - continue; - } - int candidateX = minX + candidateXf; - int candidateZ = minZ + candidateZf; - if (!isFootprintFlatBottom(fp, invertedRotation, candidateX, candidateZ, candidateBottomY, sampleProvider, entry, 2) - && !isFootprintFlatBottom(fp, invertedRotation, candidateX, candidateZ, candidateBottomY, sampleProvider, entry, 4)) { - continue; - } - pickedXf = candidateXf; - pickedZf = candidateZf; - pickBottomY = candidateBottomY; - foundBottomAnchor = true; - break; - } - if (!foundBottomAnchor) { - continue; - } - - int wx = invertedBaseX(minX, pickedXf, fp, invertedRotation); - int wz = invertedBaseZ(minZ, pickedZf, fp, invertedRotation); - - IrisObjectPlacement inverted = placement.toPlacement(obj.getLoadKey()); - inverted.setMode(inverted.getMode().onFloatingIsland()); - inverted.setTranslate(new IrisObjectTranslate()); - inverted.setRotation(invertedRotation); - inverted.setForcePlace(true); - inverted.setBottom(false); - - int yv = invertedBaseY(pickBottomY, fp, invertedRotation); - - IslandObjectPlacer islandPlacer = IslandObjectPlacer.bottom(writer, sampleProvider, entry, pickBottomY); - FloatingObjectPlacementTransaction transaction = new FloatingObjectPlacementTransaction(islandPlacer); - int id = rng.i(0, Integer.MAX_VALUE); - - try { - int resultY = obj.place(wx, yv, wz, transaction, inverted, rng, (b, bd) -> { - String marker = placementMarker(obj, id); - if (marker != null && shouldWritePlacementMarker(transaction, bd, b.getX(), b.getY(), b.getZ())) { - transaction.setData(b.getX(), b.getY(), b.getZ(), marker); - } - }, null, data); - if (resultY < 0) { - transaction.discard(); - } else { - transaction.commit(); - } - } catch (Throwable e) { - transaction.discard(); - log.error("Failed to place an inverted floating object", e); - } + int pickedXf = anchor.get().xf(); + int pickedZf = anchor.get().zf(); + int pickBottomY = anchor.get().bottomY(); + int x = invertedBaseX(chunk.minX, pickedXf, footprint, turn); + int z = invertedBaseZ(chunk.minZ, pickedZf, footprint, turn); + int y = invertedBaseY(pickBottomY, footprint, turn); + host.placeUnder(object, x, y, z, turn.yRotation(), placement, + IslandFace.bottom(chunk.resolver, entry, pickBottomY, chunk.worldHeight), rng); } } - static boolean isFootprintFlatBottom(FloatingObjectFootprint fp, IrisObjectRotation rotation, - int pickedX, int pickedZ, int pickBottomY, - IslandObjectPlacer.SampleProvider samples, - ResolvedFloatingChild entry, int tolerance) { - IrisBlockVector anchor = invertedFootprintAnchor(fp, rotation); - long[] cells = fp.footprintXZ(); + private Optional pickBottomAnchor(Chunk chunk, IslandFootprint footprint, UndersideTurn turn, KList pool, + ResolvedFloatingChild entry) { + for (int attempt = 0; attempt < INVERTED_PICK_ATTEMPTS; attempt++) { + int pickedKey = pool.get(chunk.rng.i(pool.size())); + int candidateXf = pickedKey & 15; + int candidateZf = pickedKey >> 4; + FloatingIslandSample candidate = chunk.samples[(candidateZf << 4) | candidateXf]; + if (candidate == null) { + continue; + } + int candidateBottomY = candidate.bottomY(); + if (candidateBottomY < 0) { + continue; + } + int candidateX = chunk.minX + candidateXf; + int candidateZ = chunk.minZ + candidateZf; + if (!isFootprintFlatBottom(footprint, turn, candidateX, candidateZ, candidateBottomY, chunk.resolver, entry, FLAT_TOLERANCE_BLOCKS) + && !isFootprintFlatBottom(footprint, turn, candidateX, candidateZ, candidateBottomY, chunk.resolver, entry, + LOOSE_FLAT_TOLERANCE_BLOCKS)) { + continue; + } + return Optional.of(new BottomAnchor(candidateXf, candidateZf, candidateBottomY)); + } + return Optional.empty(); + } + + /** One draw of the chance, then the object the placement picks, scaled, and shrunk as the island shrinks its objects. */ + private Optional pick(ObjectPlacement placement, ResolvedFloatingChild entry, RNG rng) { + if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + return Optional.empty(); + } + Optional scaled = objects.pickScaled(placement, rng); + if (scaled.isEmpty() || !entry.hasObjectShrink()) { + return scaled; + } + return host.shrink(scaled.get(), entry.shrinkFactor(), rng); + } + + static boolean isFootprintFlatBottom(IslandFootprint footprint, UndersideTurn turn, int pickedX, int pickedZ, int pickBottomY, + IslandFace.SampleProvider samples, ResolvedFloatingChild entry, int tolerance) { + BlockPosition anchor = invertedFootprintAnchor(footprint, turn); + long[] cells = footprint.columns(); if (cells.length == 0) { return false; } - for (int i = 0, n = cells.length; i < n; i++) { - long encoded = cells[i]; - int kx = (int) (encoded >> 32); - int kz = (int) (encoded & 0xFFFFFFFFL); - IrisBlockVector cell = rotation.rotate(new IrisBlockVector(kx, 0, kz), 0, 0, 0); - int columnX = pickedX + cell.getBlockX() - anchor.getBlockX(); - int columnZ = pickedZ + cell.getBlockZ() - anchor.getBlockZ(); + for (long encoded : cells) { + BlockPosition cell = turn.turn(IslandFootprint.columnX(encoded), 0, IslandFootprint.columnZ(encoded)); + int columnX = pickedX + cell.x() - anchor.x(); + int columnZ = pickedZ + cell.z() - anchor.z(); FloatingIslandSample sample = samples.sample(columnX, columnZ); - if (!IslandObjectPlacer.matchesAnchor(sample, entry, IslandObjectPlacer.AnchorFace.BOTTOM)) { + if (!IslandFace.matchesAnchor(sample, entry, IslandFace.Side.BOTTOM)) { return false; } int bottomY = sample.bottomY(); @@ -435,135 +333,70 @@ public class FloatingObjectPlacing { return true; } - static int invertedBaseX(int minX, int pickedXf, FloatingObjectFootprint fp) { - return invertedBaseX(minX, pickedXf, fp, IrisObjectRotation.xFlip180()); + static int invertedBaseX(int minX, int pickedXf, IslandFootprint footprint, UndersideTurn turn) { + return minX + pickedXf - invertedFootprintAnchor(footprint, turn).x(); } - static int invertedBaseY(int pickBottomY, FloatingObjectFootprint fp) { - return invertedBaseY(pickBottomY, fp, IrisObjectRotation.xFlip180()); + static int invertedBaseY(int pickBottomY, IslandFootprint footprint, UndersideTurn turn) { + return pickBottomY - 1 - invertedSolidAnchor(footprint, turn).y(); } - static int invertedBaseZ(int minZ, int pickedZf, FloatingObjectFootprint fp) { - return invertedBaseZ(minZ, pickedZf, fp, IrisObjectRotation.xFlip180()); + static int invertedBaseZ(int minZ, int pickedZf, IslandFootprint footprint, UndersideTurn turn) { + return minZ + pickedZf - invertedFootprintAnchor(footprint, turn).z(); } - static int invertedBaseX(int minX, int pickedXf, FloatingObjectFootprint fp, IrisObjectRotation rotation) { - return minX + pickedXf - invertedFootprintAnchor(fp, rotation).getBlockX(); + private static BlockPosition invertedFootprintAnchor(IslandFootprint footprint, UndersideTurn turn) { + return turn.turn(footprint.tallestX(), 0, footprint.tallestZ()); } - static int invertedBaseY(int pickBottomY, FloatingObjectFootprint fp, IrisObjectRotation rotation) { - return pickBottomY - 1 - invertedSolidAnchor(fp, rotation).getBlockY(); + private static BlockPosition invertedSolidAnchor(IslandFootprint footprint, UndersideTurn turn) { + return turn.turn(footprint.tallestX(), footprint.lowestSolidY(), footprint.tallestZ()); } - static int invertedBaseZ(int minZ, int pickedZf, FloatingObjectFootprint fp, IrisObjectRotation rotation) { - return minZ + pickedZf - invertedFootprintAnchor(fp, rotation).getBlockZ(); - } - - private static IrisBlockVector invertedFootprintAnchor(FloatingObjectFootprint fp, IrisObjectRotation rotation) { - return rotation.rotate(new IrisBlockVector(fp.getTallestKx(), 0, fp.getTallestKz()), 0, 0, 0); - } - - private static IrisBlockVector invertedSolidAnchor(FloatingObjectFootprint fp, IrisObjectRotation rotation) { - return rotation.rotate(new IrisBlockVector(fp.getTallestKx(), fp.getLowestSolidKeyY(), fp.getTallestKz()), 0, 0, 0); - } - - private static boolean shouldWritePlacementMarker(IObjectPlacer placer, PlatformBlockState state, int x, int y, int z) { - if (state == null) { - return false; - } - PlatformBlockState existingState = placer.get(x, y, z); - boolean wouldReplace = B.isSolid(existingState) && B.isVineBlock(state); - String material = IrisObjectShaping.materialKey(state); - boolean placesBlock = !material.equals("minecraft:air") && !material.equals("minecraft:cave_air") && !wouldReplace; - return state.isCustom() || placesBlock; - } - - static boolean isFootprintFlat(FloatingObjectFootprint fp, int pickedX, int pickedZ, int pickTopY, - IslandObjectPlacer.SampleProvider samples, - ResolvedFloatingChild entry, int tolerance) { - int tallestKx = fp.getTallestKx(); - int tallestKz = fp.getTallestKz(); - long[] cells = fp.footprintXZ(); + static boolean isFootprintFlat(IslandFootprint footprint, int pickedX, int pickedZ, int pickTopY, + IslandFace.SampleProvider samples, ResolvedFloatingChild entry, int tolerance) { + long[] cells = footprint.columns(); if (cells.length == 0) { return false; } - for (int i = 0, n = cells.length; i < n; i++) { - long encoded = cells[i]; - int kx = (int) (encoded >> 32); - int kz = (int) (encoded & 0xFFFFFFFFL); - int columnX = pickedX + (kx - tallestKx); - int columnZ = pickedZ + (kz - tallestKz); + for (long encoded : cells) { + int columnX = pickedX + (IslandFootprint.columnX(encoded) - footprint.tallestX()); + int columnZ = pickedZ + (IslandFootprint.columnZ(encoded) - footprint.tallestZ()); FloatingIslandSample sample = samples.sample(columnX, columnZ); - if (!IslandObjectPlacer.matchesAnchor(sample, entry, IslandObjectPlacer.AnchorFace.TOP) - || Math.abs(sample.topY() - pickTopY) > tolerance) { + if (!IslandFace.matchesAnchor(sample, entry, IslandFace.Side.TOP) || Math.abs(sample.topY() - pickTopY) > tolerance) { return false; } } return true; } - private static KList interiorColumns(IslandObjectPlacer.SampleProvider samples, - KList columns, int minX, int minZ, - ResolvedFloatingChild entry, - IslandObjectPlacer.AnchorFace face) { + private static KList interiorColumns(Chunk chunk, KList columns, ResolvedFloatingChild entry, IslandFace.Side side) { KList interior = new KList<>(); for (int key : columns) { - int x = minX + (key & 15); - int z = minZ + (key >> 4); - if (!IslandObjectPlacer.matchesAnchor(samples.sample(x + 1, z), entry, face)) { - continue; + int x = chunk.minX + (key & 15); + int z = chunk.minZ + (key >> 4); + if (IslandFace.matchesAnchor(chunk.resolver.sample(x + 1, z), entry, side) + && IslandFace.matchesAnchor(chunk.resolver.sample(x - 1, z), entry, side) + && IslandFace.matchesAnchor(chunk.resolver.sample(x, z + 1), entry, side) + && IslandFace.matchesAnchor(chunk.resolver.sample(x, z - 1), entry, side)) { + interior.add(key); } - if (!IslandObjectPlacer.matchesAnchor(samples.sample(x - 1, z), entry, face)) { - continue; - } - if (!IslandObjectPlacer.matchesAnchor(samples.sample(x, z + 1), entry, face)) { - continue; - } - if (!IslandObjectPlacer.matchesAnchor(samples.sample(x, z - 1), entry, face)) { - continue; - } - interior.add(key); } return interior; } - private static String placementMarker(IrisObject object, int id) { - if (object == null) { - return null; - } - String key = object.getLoadKey(); - if (key == null || key.isEmpty() || key.equals("null")) { - return null; - } - return key + "@" + id; - } - - /** How far, in blocks along X and Z, placements may write beyond their chunk. */ - public int reach() { - int maxObjectExtent = 16; - Map sizeCache = new HashMap<>(); - Set warnedLargeObjects = new HashSet<>(); + /** How far, in blocks along X and Z, the floating objects of the pack {@code settings} describe may write beyond their chunk. */ + public static int reach(PackSettings settings, ModuleLog log) { + Reach reach = new Reach(FloatingHost.of(settings), ObjectHost.of(settings), log); + int maxObjectExtent = MIN_REACH_BLOCKS; try { - IrisData data = engine.getData(); - for (IrisBiome biome : engine.getDimension().getReachableBiomes(engine)) { - List settings = FloatingChildren.declaredBy(biome); - if (settings.isEmpty()) { + for (Entry declared : settings.declared(FloatingChildSettings.class)) { + if (declared.level() != Target.BIOME) { continue; } - for (ResolvedFloatingChild entry : FloatingChildren.of(engine).of(settings)) { - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().floatingObjects()), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().extraObjects()), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().topObjectOverrides()), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(new KList<>(entry.settings().bottomObjectOverrides()), data, sizeCache, warnedLargeObjects)); - try { - IrisBiome target = entry.getRealBiome(biome, data); - if (target != null) { - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveTopObjects(target), data, sizeCache, warnedLargeObjects)); - maxObjectExtent = Math.max(maxObjectExtent, computePlacementRadius(entry.resolveBottomObjects(target), data, sizeCache, warnedLargeObjects)); - } - } catch (Throwable e) { - log.error("Failed to work out the reach of a floating biome's objects", e); - } + ResourceId biome = biomeIdOf(declared.source()); + for (FloatingChildBiome child : declared.value().children()) { + maxObjectExtent = Math.max(maxObjectExtent, reach.of(child, biome)); } } } catch (Throwable e) { @@ -572,87 +405,79 @@ public class FloatingObjectPlacing { return maxObjectExtent; } - private int computePlacementRadius(KList placements, IrisData data, - Map sizeCache, - Set warnedLargeObjects) { - int radius = 0; - if (placements == null) { - return radius; + /** A settings entry's source names a biome as {@code biome/}; the pack's resources name it by the key alone. */ + private static ResourceId biomeIdOf(ResourceId source) { + String path = source.path(); + return path.startsWith(BIOME_PATH_PREFIX) ? new ResourceId(source.namespace(), path.substring(BIOME_PATH_PREFIX.length())) : source; + } + + /** The reach of floating children's objects, each object sized once. */ + private static final class Reach { + private final FloatingHost host; + private final ObjectHost objects; + private final ModuleLog log; + private final Map> sizes = new HashMap<>(); + private final Set warnedLargeObjects = new HashSet<>(); + + private Reach(FloatingHost host, ObjectHost objects, ModuleLog log) { + this.host = host; + this.objects = objects; + this.log = log; } - for (IrisObjectPlacement placement : placements) { - if (placement == null || placement.getPlace() == null) { - continue; + + int of(FloatingChildBiome child, ResourceId parent) { + int reach = 0; + reach = Math.max(reach, placementRadius(child.floatingObjects())); + reach = Math.max(reach, placementRadius(child.extraObjects())); + reach = Math.max(reach, placementRadius(child.topObjectOverrides())); + reach = Math.max(reach, placementRadius(child.bottomObjectOverrides())); + try { + ResourceId target = child.biome().isBlank() ? parent : host.biome(child.biome()).orElse(parent); + List surface = child.inheritObjects() ? FloatingWorld.surfaceObjects(objects, target) : List.of(); + reach = Math.max(reach, placementRadius(ResolvedFloatingChild.topObjects(child, surface))); + reach = Math.max(reach, placementRadius(ResolvedFloatingChild.bottomObjects(child))); + } catch (Throwable e) { + log.error("Failed to work out the reach of a floating biome's objects", e); } - for (String objectKey : placement.getPlace()) { - try { - IrisBlockVector size = sizeCache.get(objectKey); - if (size == null) { - File file = data.getObjectLoader().findFile(objectKey); - if (file == null) { - continue; - } - size = IrisObject.sampleSize(file); - sizeCache.put(objectKey, size); - } - int reach = calculatePlacementReach(size, placement); - if (reach > 128 && warnedLargeObjects.add(objectKey)) { - log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); - } - radius = Math.max(radius, reach); - } catch (Throwable e) { - log.error("Failed to size a floating object", e); + return reach; + } + + private int placementRadius(List placements) { + int radius = 0; + for (ObjectPlacement placement : placements) { + if (placement == null) { + continue; + } + for (String objectKey : placement.place()) { + radius = Math.max(radius, objectReach(objectKey, placement)); } } + return radius; + } + + private int objectReach(String objectKey, ObjectPlacement placement) { + try { + Optional size = sizes.computeIfAbsent(objectKey, objects::sizeOf); + if (size.isEmpty()) { + return 0; + } + int reach = PlacementReach.of(size.get(), placement); + if (reach > LARGE_REACH_WARNING_BLOCKS && warnedLargeObjects.add(objectKey)) { + log.warn("Floating object " + objectKey + " has a large placement reach (" + reach + " blocks) and may increase memory usage!"); + } + return reach; + } catch (Throwable e) { + log.error("Failed to size a floating object", e); + return 0; + } } - return radius; } - static int calculatePlacementReach(IrisBlockVector size, IrisObjectPlacement placement) { - if (size == null) { - return 0; - } - if (placement == null) { - return Math.max(Math.abs(size.getBlockX()), Math.abs(size.getBlockZ())); - } - - double scale = placement.getScale() != null ? Math.max(1D, placement.getScale().getMaxScale()) : 1D; - int width = scaledDimension(size.getBlockX(), scale); - int height = scaledDimension(size.getBlockY(), scale); - int depth = scaledDimension(size.getBlockZ(), scale); - IrisObjectRotation rotation = placement.getRotation(); - boolean rotateX = rotation != null && rotation.isEnabled() && rotation.getXAxis() != null && rotation.getXAxis().enabled(); - boolean rotateZ = rotation != null && rotation.isEnabled() && rotation.getZAxis() != null && rotation.getZAxis().enabled(); - int footprint = rotateX || rotateZ ? Math.max(width, Math.max(height, depth)) : Math.max(width, depth); - int translation = calculateTranslationReach(placement.getTranslate(), rotation, rotateX || rotateZ); - int warp = placement.getWarp() != null && !placement.getWarp().isFlat() - ? (int) Math.ceil(Math.abs(placement.getWarp().getMultiplier()) / 2D) - : 0; - int vacuum = placement.getMode().placeMode().bendsTerrain() - ? 2 * IrisObjectVacuum.resolveRadius(placement.getMode().placeMode().vacuum(), placement.getVacuumSettings()) - : 0; - long reach = (long) footprint + translation + warp + vacuum; - return reach > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) reach; + private record BottomAnchor(int xf, int zf, int bottomY) { } - private static int scaledDimension(int dimension, double scale) { - int absoluteDimension = Math.abs(dimension); - if (scale <= 1D) { - return absoluteDimension; - } - return (int) Math.ceil((absoluteDimension * scale) + (scale * 2D)); - } - - private static int calculateTranslationReach(IrisObjectTranslate translate, IrisObjectRotation rotation, boolean rotateVertically) { - if (translate == null || !translate.canTranslate()) { - return 0; - } - double x = translate.getX(); - double y = translate.getY(); - double z = translate.getZ(); - if (rotateVertically) { - return (int) Math.ceil(Math.sqrt((x * x) + (y * y) + (z * z))); - } - boolean rotateY = rotation != null && rotation.isEnabled() && rotation.getYAxis() != null && rotation.getYAxis().enabled(); - return rotateY ? (int) Math.ceil(Math.hypot(x, z)) : (int) Math.max(Math.abs(x), Math.abs(z)); + /** What one chunk's placements share: where it is, its random, and its columns' island samples. */ + private record Chunk(int minX, int minZ, int worldHeight, RNG rng, FloatingIslandSampleResolver resolver, + FloatingIslandSample[] samples) { } } 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 new file mode 100644 index 000000000..9be265fe0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IslandAnchorPlacer.java @@ -0,0 +1,128 @@ +/* + * 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/IslandFace.java b/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java new file mode 100644 index 000000000..316de43d9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java @@ -0,0 +1,141 @@ +/* + * 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.engine.object.terrain.floating.FloatingIslandSample; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; + +/** + * The top or bottom face of one floating child's island, at the height an object is anchored: what Iris's placer asks + * about the island while it places the object, and which blocks the object may write. An object may overhang its anchor + * only where the same child's face lies near the anchor height within {@value #OVERHANG_RADIUS} blocks. + */ +final class IslandFace implements IslandAnchor { + private static final int OVERHANG_RADIUS = 2; + private static final int OVERHANG_HEIGHT_TOLERANCE = 4; + + private final SampleProvider samples; + private final ResolvedFloatingChild entry; + private final int anchorY; + private final Side side; + private final int worldHeight; + + private IslandFace(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, Side side, int worldHeight) { + this.samples = samples; + this.entry = entry; + this.anchorY = anchorY; + this.side = side; + this.worldHeight = worldHeight; + } + + static IslandFace top(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, int worldHeight) { + return new IslandFace(samples, entry, anchorY, Side.TOP, worldHeight); + } + + static IslandFace bottom(SampleProvider samples, ResolvedFloatingChild entry, int anchorY, int worldHeight) { + return new IslandFace(samples, entry, anchorY, Side.BOTTOM, worldHeight); + } + + @Override + public int faceY(int x, int z) { + FloatingIslandSample sample = samples.sample(x, z); + if (sample == null) { + return anchorY; + } + if (side == Side.TOP) { + return sample.topY(); + } + int bottomY = sample.bottomY(); + return bottomY < 0 ? anchorY : bottomY; + } + + @Override + public boolean hasIsland(int x, int z) { + return samples.sample(x, z) != null; + } + + @Override + public boolean islandSolid(int x, int y, int z) { + FloatingIslandSample sample = samples.sample(x, z); + if (sample == null) { + return false; + } + int index = y - sample.islandBaseY; + return index >= 0 && index < sample.solidMask.length && sample.solidMask[index]; + } + + @Override + public boolean writes(int x, int y, int z) { + return !skipsAirColumn(x, y, z); + } + + /** Whether {@code sample} is this face's child's island, by the face this anchor is on. */ + static boolean matchesAnchor(FloatingIslandSample sample, ResolvedFloatingChild entry, Side side) { + if (sample == null) { + return false; + } + return side == Side.TOP ? sample.entry == entry : sample.bottomEntry() == entry; + } + + private boolean skipsAirColumn(int x, int y, int z) { + if (y < 0 || y >= worldHeight) { + return true; + } + + FloatingIslandSample sample = samples.sample(x, z); + if (matchesAnchor(sample, entry, side) && isNearAnchorHeight(sample)) { + return side == Side.BOTTOM && y >= anchorY; + } + if (side == Side.TOP && y <= anchorY) { + return true; + } + if (side == Side.BOTTOM && y >= anchorY) { + return true; + } + return !hasNearbySupport(x, z); + } + + private boolean hasNearbySupport(int x, int z) { + for (int dz = -OVERHANG_RADIUS; dz <= OVERHANG_RADIUS; dz++) { + for (int dx = -OVERHANG_RADIUS; dx <= OVERHANG_RADIUS; dx++) { + FloatingIslandSample sample = samples.sample(x + dx, z + dz); + if (matchesAnchor(sample, entry, side) && isNearAnchorHeight(sample)) { + return true; + } + } + } + return false; + } + + private boolean isNearAnchorHeight(FloatingIslandSample sample) { + int faceY = side == Side.TOP ? sample.topY() : sample.bottomY(); + return faceY >= 0 && Math.abs(faceY - anchorY) <= OVERHANG_HEIGHT_TOLERANCE; + } + + enum Side { + TOP, + BOTTOM + } + + @FunctionalInterface + interface SampleProvider { + FloatingIslandSample sample(int x, int z); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java deleted file mode 100644 index 6462a1af3..000000000 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IslandObjectPlacer.java +++ /dev/null @@ -1,220 +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.engine.object.terrain.floating.ResolvedFloatingChild; -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.terrain.floating.FloatingIslandSample; -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; - -public final class IslandObjectPlacer implements IObjectPlacer { - private static final int OVERHANG_RADIUS = 2; - private static final int OVERHANG_HEIGHT_TOLERANCE = 4; - - private final MantleWriter wrapped; - private final SampleProvider samples; - private final ResolvedFloatingChild entry; - private final int anchorY; - private final AnchorFace face; - - private IslandObjectPlacer(MantleWriter wrapped, AnchorSettings settings) { - this.wrapped = wrapped; - this.samples = settings.samples(); - this.entry = settings.entry(); - this.anchorY = settings.anchorY(); - this.face = settings.face(); - } - - public static IslandObjectPlacer top(MantleWriter wrapped, SampleProvider samples, - ResolvedFloatingChild entry, int anchorY) { - return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.TOP)); - } - - public static IslandObjectPlacer bottom(MantleWriter wrapped, SampleProvider samples, - ResolvedFloatingChild entry, int anchorY) { - return new IslandObjectPlacer(wrapped, new AnchorSettings(samples, entry, anchorY, AnchorFace.BOTTOM)); - } - - public boolean canWriteObjectBlock(int x, int y, int z) { - return !shouldSkipAirColumn(x, y, z); - } - - @Override - public int getHighest(int x, int z, IrisData data) { - FloatingIslandSample sample = samples.sample(x, z); - if (face == AnchorFace.TOP) { - return sample == null ? anchorY : sample.topY(); - } - if (sample == null) { - return anchorY; - } - int bottomY = sample.bottomY(); - return bottomY < 0 ? anchorY : bottomY; - } - - @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) { - FloatingIslandSample sample = samples.sample(x, z); - if (sample != null) { - int index = y - sample.islandBaseY; - if (index >= 0 && index < sample.solidMask.length) { - return sample.solidMask[index]; - } - return false; - } - return 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 (!shouldSkipAirColumn(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 (!shouldSkipAirColumn(x, y, z)) { - wrapped.setTile(x, y, z, tile); - } - } - - @Override - public void setData(int x, int y, int z, T data) { - if (!shouldSkipAirColumn(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(); - } - - static boolean matchesAnchor(FloatingIslandSample sample, ResolvedFloatingChild entry, AnchorFace face) { - if (sample == null) { - return false; - } - return face == AnchorFace.TOP ? sample.entry == entry : sample.bottomEntry() == entry; - } - - private boolean shouldSkipAirColumn(int x, int y, int z) { - Engine engine = getEngine(); - if (engine != null && (y < 0 || y >= engine.getHeight())) { - return true; - } - - FloatingIslandSample sample = samples.sample(x, z); - if (matchesAnchor(sample, entry, face) && isNearAnchorHeight(sample)) { - return face == AnchorFace.BOTTOM && y >= anchorY; - } - if (face == AnchorFace.TOP && y <= anchorY) { - return true; - } - if (face == AnchorFace.BOTTOM && y >= anchorY) { - return true; - } - return !hasNearbySupport(x, z); - } - - private boolean hasNearbySupport(int x, int z) { - for (int dz = -OVERHANG_RADIUS; dz <= OVERHANG_RADIUS; dz++) { - for (int dx = -OVERHANG_RADIUS; dx <= OVERHANG_RADIUS; dx++) { - FloatingIslandSample sample = samples.sample(x + dx, z + dz); - if (matchesAnchor(sample, entry, face) && isNearAnchorHeight(sample)) { - return true; - } - } - } - return false; - } - - private boolean isNearAnchorHeight(FloatingIslandSample sample) { - int faceY = face == AnchorFace.TOP ? sample.topY() : sample.bottomY(); - return faceY >= 0 && Math.abs(faceY - anchorY) <= OVERHANG_HEIGHT_TOLERANCE; - } - - public enum AnchorFace { - TOP, - BOTTOM - } - - @FunctionalInterface - public interface SampleProvider { - @Nullable FloatingIslandSample sample(int x, int z); - } - - private record AnchorSettings( - SampleProvider samples, - ResolvedFloatingChild entry, - int anchorY, - AnchorFace face - ) { - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java b/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java new file mode 100644 index 000000000..5900dfb9f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java @@ -0,0 +1,40 @@ +/* + * 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 com.volmit.world.BlockPosition; + +/** + * How Iris turns an object it hangs under an island: upside down about X, then a quarter turn about Y of {@code yRotation} + * degrees (0, 90, 180 or 270), in the object's own block positions. + */ +record UndersideTurn(int yRotation) { + private static final int FULL_TURN_DEGREES = 360; + + BlockPosition turn(int x, int y, int z) { + int flippedY = -y; + int flippedZ = -z; + return switch (Math.floorMod(yRotation, FULL_TURN_DEGREES)) { + case 90 -> new BlockPosition(flippedZ, flippedY, -x); + case 180 -> new BlockPosition(-x, flippedY, -flippedZ); + case 270 -> new BlockPosition(-flippedZ, flippedY, x); + default -> new BlockPosition(x, flippedY, flippedZ); + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 575d6c8ec..28af360d0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -18,75 +18,296 @@ package art.arcane.iris.engine.modifier; - -import art.arcane.iris.engine.object.terrain.floating.FloatingChildren; -import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.decorant.DecorantSettings; +import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.BiomeLayers; +import art.arcane.iris.builtin.terrain.ColumnSlope; +import art.arcane.iris.builtin.terrain.LayerNoise; +import art.arcane.iris.builtin.terrain.PaletteExplosion; import art.arcane.iris.builtin.terrain.PaletteLayer; -import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.builtin.terrain.ExplodeBiomePaletteSizeSettings; -import art.arcane.iris.builtin.terrain.ExplodeBiomePalettesSettings; +import art.arcane.iris.builtin.terrain.ResolvedLayer; +import art.arcane.iris.engine.decorator.BiomeDecorators; +import art.arcane.iris.engine.decorator.DecoratedBiome; import art.arcane.iris.engine.decorator.DecorationScene; import art.arcane.iris.engine.decorator.FloatingDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.builtin.terrain.BiomeLayers; -import art.arcane.iris.builtin.terrain.LayerNoise; -import art.arcane.iris.builtin.terrain.ResolvedLayer; -import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.iris.util.project.hunk.Hunk; +import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; +import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterBiomeInject; -import art.arcane.volmlib.util.matter.slices.BiomeInjectMatter; -import art.arcane.volmlib.util.scheduling.PrecisionStopwatch; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; - import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.hunk.Hunk; +import com.volmit.resource.ResourceId; +import com.volmit.stage.ChunkStageContext; import com.volmit.world.BiomeKind; -import java.util.IdentityHashMap; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; -import static art.arcane.iris.engine.mantle.EngineMantle.AIR; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; /** * Fills and decorates the floating islands of the dimension's floating child biomes for {@link FloatingModule}: * the islands' solids (top layers, bottom palette, sea surface) and, later, the decoration on their tops. One - * per engine runtime, holding the islands' random. + * per world, holding the islands' random. */ -public class FloatingIslands { - public static final long FLOATING_BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; +final class FloatingIslands { + private static final long ISLAND_RANDOM_SALT = 0x7EB0A73F1DCE514DL; + private static final int BOTTOM_PALETTE_SALT = 0xB0770B; + private static final int LAYER_RANDOM_SALT = 0x7A4E; + private static final int FIRST_LAYER_GENERATOR_SEED = 7235; + private static final int MIN_PALETTE_DEPTH = 4; + private static final int CHUNK_WIDTH = 16; + private static final int CHUNK_CENTRE = 7; + private static final BlockState BARRIER = new BlockState("minecraft:barrier"); + private static final BlockState FALLBACK_SOLID = new BlockState("minecraft:stone"); + private static final String DEFAULT_FLUID = "minecraft:water"; private static final Runnable NOOP_DECORATION_MISS = () -> { }; - private final Engine engine; + + private final FloatingWorld world; private final RNG rng; private final BiomeLayers biomeLayers; - private final IrisLayers glue; private final ModuleLog log; - private KList generateBottomPaletteLayers(ResolvedFloatingChild entry, IrisDimension dimension, double wx, double wz, RNG random, int paletteDepth, IrisData data, IrisComplex complex) { - if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette() == null || entry.settings().bottomPalette().isEmpty()) { - return null; - } - return generatePaletteLayers(dimension, new KList<>(entry.settings().bottomPalette()), wx, wz, random.nextParallelRNG(0xB0770B), paletteDepth, data, complex); + FloatingIslands(PackWorld world, ModuleLog log) { + this.world = FloatingWorld.of(world); + this.rng = new RNG(IrisSeed.TERRAIN.of(world) ^ ISLAND_RANDOM_SALT); + this.biomeLayers = BiomeLayers.of(world); + this.log = log; } - private KList generatePaletteLayers(IrisDimension dimension, KList layers, double wx, double wz, RNG random, int maxDepth, IrisData data, IrisComplex complex) { - KList generated = new KList<>(); - if (layers == null || layers.isEmpty() || maxDepth <= 0) { + /** The islands of {@code world}. */ + static FloatingIslands of(PackWorld world, ModuleLog log) { + return world.state(FloatingIslands.class, generating -> new FloatingIslands(generating, log)); + } + + /** Fills the islands' solids into the chunk of {@code context}. */ + void fillSolids(ChunkStageContext context) { + Chunk chunk = new Chunk(context); + FloatingIslandSample.clearChunkMemo(); + + for (int xf = 0; xf < CHUNK_WIDTH; xf++) { + for (int zf = 0; zf < CHUNK_WIDTH; zf++) { + fillColumn(chunk, xf, zf); + } + } + } + + private void fillColumn(Chunk chunk, int xf, int zf) { + int wx = chunk.originX + xf; + int wz = chunk.originZ + zf; + ResourceId parent = chunk.boundarySampler.parent(wx, wz); + if (parent == null || world.declaredBy(parent).isEmpty()) { + return; + } + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunk.height, world, chunk.boundarySampler, log); + if (sample == null) { + return; + } + + long colSeed = FloatingIslandSample.columnSeed(world.baseSeed(), wx, wz); + int paletteDepth = Math.max(MIN_PALETTE_DEPTH, sample.solidCount + MIN_PALETTE_DEPTH); + Map paletteContexts = new IdentityHashMap<>(); + Map topDepthByEntry = new IdentityHashMap<>(); + int[] bottomDepths = bottomDepths(sample, chunk.height); + for (int k = sample.topIdx; k >= 0; k--) { + if (!sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + ResolvedFloatingChild entry = sample.entryAt(k); + PaletteContext paletteContext = paletteContexts.computeIfAbsent(entry, + ignored -> createPaletteContext(chunk, parent, entry, wx, wz, colSeed, paletteDepth)); + int depth = topDepthByEntry.getOrDefault(entry, 0); + int bottomDepth = bottomDepths[k] < 0 ? depth : bottomDepths[k]; + BlockState block = selectPaletteBlock(entry, paletteContext.topBlocks(), paletteContext.bottomBlocks(), depth, bottomDepth); + if (block != null) { + chunk.output.set(xf, y, zf, block); + } + topDepthByEntry.put(entry, depth + 1); + } + + fillLocalFluid(chunk, sample, xf, zf); + paintSkyBiomes(parent, wx, wz, sample, chunk.height); + } + + private void fillLocalFluid(Chunk chunk, FloatingIslandSample sample, int xf, int zf) { + int localFluidHeight = sample.entry.settings().localFluidHeight().orElse(0); + if (localFluidHeight <= 0) { + return; + } + BlockState fluid = fluidOf(chunk.blocks, sample.entry.settings().fluidBlock()); + int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); + for (int k = 1; k <= fluidCap; k++) { + if (sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + if (hasSolidBelow(sample, k)) { + chunk.output.set(xf, y, zf, fluid); + } + } + } + + private static BlockState fluidOf(BlockRegistry blocks, String key) { + try { + return blocks.resolve(key); + } catch (IllegalArgumentException unknown) { + return blocks.resolve(DEFAULT_FLUID); + } + } + + private static boolean hasSolidBelow(FloatingIslandSample sample, int k) { + for (int kb = k - 1; kb >= 0; kb--) { + if (sample.solidMask[kb]) { + return true; + } + } + return false; + } + + /** Decorates the tops of the islands in the chunk of {@code context}. */ + void decorateColumns(ChunkStageContext context) { + Chunk chunk = new Chunk(context); + DecorationScene scene = DecorationScene.of(context); + + for (int xf = 0; xf < CHUNK_WIDTH; xf++) { + for (int zf = 0; zf < CHUNK_WIDTH; zf++) { + decorateColumn(chunk, scene, xf, zf); + } + } + } + + private void decorateColumn(Chunk chunk, DecorationScene scene, int xf, int zf) { + int wx = chunk.originX + xf; + int wz = chunk.originZ + zf; + ResourceId parent = chunk.boundarySampler.parent(wx, wz); + if (parent == null || world.declaredBy(parent).isEmpty()) { + return; + } + FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunk.height, world, chunk.boundarySampler, log); + if (sample == null) { + return; + } + ResolvedFloatingChild entry = sample.entry; + ResourceId target = entry.realBiome(parent); + if (!entry.settings().inheritDecorators() || target == null) { + return; + } + + DecoratedBiome decorated = decoratedBiome(chunk.settings, target); + decorateTop(chunk, scene, sample, decorated, xf, zf, wx, wz); + decorateLocalFluid(chunk, scene, sample, decorated, xf, zf, wx, wz); + } + + private void decorateTop(Chunk chunk, DecorationScene scene, FloatingIslandSample sample, DecoratedBiome decorated, + int xf, int zf, int wx, int wz) { + int topY = sample.topY(); + if (topY + 1 >= chunk.height) { + return; + } + BlockState above = chunk.output.get(xf, topY + 1, zf); + if (above != null && !scene.isAir(above)) { + return; + } + int max = Math.max(1, chunk.height - topY); + try { + RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(world.baseSeed(), wx, wz)); + FloatingDecorator.decorateColumn(scene, decorated, DecorationPart.NONE, xf, zf, wx, wz, topY, max, colRng, NOOP_DECORATION_MISS); + } catch (Throwable e) { + log.error("Failed to decorate the top of a floating island", e); + } + } + + private void decorateLocalFluid(Chunk chunk, DecorationScene scene, FloatingIslandSample sample, DecoratedBiome decorated, + int xf, int zf, int wx, int wz) { + int localFluidHeight = sample.entry.settings().localFluidHeight().orElse(0); + if (localFluidHeight <= 0) { + return; + } + int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); + int fluidTopY = -1; + for (int k = 1; k <= fluidCap; k++) { + if (sample.solidMask[k]) { + continue; + } + int y = sample.islandBaseY + k; + if (y < 0 || y >= chunk.height) { + continue; + } + if (hasSolidBelow(sample, k) && y > fluidTopY) { + fluidTopY = y; + } + } + if (fluidTopY <= 0 || fluidTopY + 1 >= chunk.height) { + return; + } + BlockState above = chunk.output.get(xf, fluidTopY + 1, zf); + if (above != null && !scene.isAir(above)) { + return; + } + try { + new IrisSeaSurfaceDecorator(scene).decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, decorated, fluidTopY, chunk.height); + } catch (Throwable e) { + log.error("Failed to decorate the sea surface of a floating island", e); + } + } + + /** The decorators' view of the island's biome, which always decorates as land. */ + private static DecoratedBiome decoratedBiome(FeatureSettings settings, ResourceId biome) { + return new DecoratedBiome(BiomeDecorators.biomeKey(biome), settings.declaredBy(biome, DecorantSettings.class).orElse(null), BiomeKind.LAND); + } + + private PaletteContext createPaletteContext(Chunk chunk, ResourceId parent, ResolvedFloatingChild entry, int wx, int wz, long colSeed, + int paletteDepth) { + ResourceId target = entry == null ? parent : entry.realBiome(parent); + int entrySeed = entry == null ? 0 : entry.settings().biome().hashCode(); + RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ LAYER_RANDOM_SALT ^ entrySeed)); + KList topBlocks = target == null ? null : surfaceLayers(chunk, target, wx, wz, layerRng, paletteDepth); + if (topBlocks == null || topBlocks.isEmpty()) { + topBlocks = surfaceLayers(chunk, parent, wx, wz, layerRng, paletteDepth); + } + List bottomBlocks = generateBottomPaletteLayers(chunk, entry, wx, wz, layerRng, paletteDepth); + return new PaletteContext(topBlocks, bottomBlocks); + } + + private KList surfaceLayers(Chunk chunk, ResourceId biome, int wx, int wz, RNG layerRng, int paletteDepth) { + return biomeLayers.generateLayers(biomeLayers.biome(biome, chunk.settings), chunk.explosion, wx, wz, layerRng, paletteDepth, + paletteDepth, chunk.slope); + } + + private List generateBottomPaletteLayers(Chunk chunk, ResolvedFloatingChild entry, double wx, double wz, RNG random, + int paletteDepth) { + if (entry == null || entry.settings().bottomPaletteMode() != FloatingBottomPaletteMode.CUSTOM || entry.settings().bottomPalette().isEmpty()) { + return null; + } + return generatePaletteLayers(chunk, entry.settings().bottomPalette(), wx, wz, random.nextParallelRNG(BOTTOM_PALETTE_SALT), paletteDepth); + } + + private List generatePaletteLayers(Chunk chunk, List layers, double wx, double wz, RNG random, int maxDepth) { + List generated = new ArrayList<>(); + if (layers.isEmpty() || maxDepth <= 0) { return generated; } - int generatorSeed = 7235; + int generatorSeed = FIRST_LAYER_GENERATOR_SEED; for (int i = 0; i < layers.size(); i++) { ResolvedLayer layer = biomeLayers.resolve(layers.get(i)); LayerNoise heightGenerator = layer.heightNoise(random.nextParallelRNG((generatorSeed++) * generatorSeed * generatorSeed * generatorSeed)); @@ -96,7 +317,7 @@ public class FloatingIslands { double layerDepth = heightGenerator.fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); SlopeClip slopeClip = layer.slopeCondition(); - if (slopeClip != null && !slopeClip.isDefault() && complex != null && !slopeClip.isValid(complex.getSlopeStream().get(wx, wz))) { + if (slopeClip != null && !slopeClip.isDefault() && !slopeClip.isValid(chunk.slope.at(wx, wz))) { layerDepth = 0; } @@ -110,7 +331,7 @@ public class FloatingIslands { } try { - generated.add(glue.platform(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom()))); + generated.add(layer.get(random.nextParallelRNG(i + j), (wx + j) / layer.zoom(), j, (wz - j) / layer.zoom())); } catch (Throwable e) { log.error("Failed to pick a block of a floating island's palette", e); } @@ -120,12 +341,9 @@ public class FloatingIslands { break; } - if (dimension != null && dimension.getModuleSettings().find(ExplodeBiomePalettesSettings.class).map(ExplodeBiomePalettesSettings::explode).orElse(false)) { - PlatformBlockState barrier = B.getState("minecraft:barrier"); - int gap = dimension.getModuleSettings().find(ExplodeBiomePaletteSizeSettings.class).map(ExplodeBiomePaletteSizeSettings::size) - .orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); - for (int j = 0; j < gap; j++) { - generated.add(barrier); + if (chunk.explosion.exploded()) { + for (int j = 0; j < chunk.explosion.size(); j++) { + generated.add(BARRIER); if (generated.size() >= maxDepth) { break; @@ -137,18 +355,11 @@ public class FloatingIslands { return generated; } - private static boolean usesBottomPalette(ResolvedFloatingChild entry) { - FloatingBottomPaletteMode mode = entry == null || entry.settings().bottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode(); - return mode != FloatingBottomPaletteMode.DEPTH; - } - private static int[] bottomDepths(FloatingIslandSample sample, int chunkHeight) { int[] bottomDepths = new int[sample.solidMask.length]; - for (int i = 0; i < bottomDepths.length; i++) { - bottomDepths[i] = -1; - } + java.util.Arrays.fill(bottomDepths, -1); - IdentityHashMap depthByEntry = new IdentityHashMap<>(); + Map depthByEntry = new IdentityHashMap<>(); int max = Math.min(sample.topIdx, sample.solidMask.length - 1); for (int k = 0; k <= max; k++) { if (!sample.solidMask[k]) { @@ -167,227 +378,33 @@ public class FloatingIslands { return bottomDepths; } - private static PlatformBlockState selectPaletteBlock(ResolvedFloatingChild entry, KList topBlocks, KList bottomBlocks, int topDepth, int bottomDepth, PlatformBlockState fallbackSolid) { - FloatingBottomPaletteMode mode = entry == null || entry.settings().bottomPaletteMode() == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode(); + private static BlockState selectPaletteBlock(ResolvedFloatingChild entry, List topBlocks, List bottomBlocks, + int topDepth, int bottomDepth) { + FloatingBottomPaletteMode mode = entry == null ? FloatingBottomPaletteMode.DEPTH : entry.settings().bottomPaletteMode(); if (mode == FloatingBottomPaletteMode.MIRROR_TOP) { - return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth), fallbackSolid); + return paletteBlock(topBlocks, Math.min(topDepth, bottomDepth)); } if (mode == FloatingBottomPaletteMode.CUSTOM && bottomDepth < topDepth) { if (bottomBlocks != null && !bottomBlocks.isEmpty()) { - return paletteBlock(bottomBlocks, bottomDepth, fallbackSolid); + return paletteBlock(bottomBlocks, bottomDepth); } - return paletteBlock(topBlocks, bottomDepth, fallbackSolid); + return paletteBlock(topBlocks, bottomDepth); } - return paletteBlock(topBlocks, topDepth, fallbackSolid); + return paletteBlock(topBlocks, topDepth); } - private static PlatformBlockState paletteBlock(KList blocks, int depth, PlatformBlockState fallbackSolid) { + private static BlockState paletteBlock(List blocks, int depth) { if (blocks == null || blocks.isEmpty()) { - return fallbackSolid; + return FALLBACK_SOLID; } - PlatformBlockState block = blocks.hasIndex(depth) ? blocks.get(depth) : blocks.getLast(); - return block == null ? fallbackSolid : block; + BlockState block = depth >= 0 && depth < blocks.size() ? blocks.get(depth) : blocks.getLast(); + return block == null ? FALLBACK_SOLID : block; } - private PaletteContext createPaletteContext(IrisBiome parent, ResolvedFloatingChild entry, IrisDimension dimension, int wx, int wz, long colSeed, int paletteDepth, IrisData data, IrisComplex complex) { - IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); - int entrySeed = entry == null || entry.settings().biome() == null ? 0 : entry.settings().biome().hashCode(); - RNG layerRng = rng.nextParallelRNG((int) (colSeed ^ 0x7A4E ^ entrySeed)); - KList topBlocks = target == null ? null : glue.platform(biomeLayers.generateLayers(glue.biome(target), IrisLayers.explosionOf(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, glue.slope())); - if (topBlocks == null || topBlocks.isEmpty()) { - topBlocks = glue.platform(biomeLayers.generateLayers(glue.biome(parent), IrisLayers.explosionOf(dimension), wx, wz, layerRng, paletteDepth, paletteDepth, glue.slope())); - } - KList bottomBlocks = generateBottomPaletteLayers(entry, dimension, wx, wz, layerRng, paletteDepth, data, complex); - return new PaletteContext(topBlocks, bottomBlocks, B.getState("minecraft:stone")); - } - - private static final class PaletteContext { - private final KList topBlocks; - private final KList bottomBlocks; - private final PlatformBlockState fallbackSolid; - - private PaletteContext(KList topBlocks, KList bottomBlocks, PlatformBlockState fallbackSolid) { - this.topBlocks = topBlocks; - this.bottomBlocks = bottomBlocks; - this.fallbackSolid = fallbackSolid; - } - } - - public FloatingIslands(Engine engine, ModuleLog log) { - this.engine = engine; - this.log = log; - rng = new RNG(engine.getSeedManager().getTerrain() ^ 0x7EB0A73F1DCE514DL); - biomeLayers = BiomeLayers.of(engine.getGeneration().world()); - glue = new IrisLayers(engine); - } - - /** Fills the islands' solids into the chunk whose first block is {@code x}, {@code z}. */ - public void fillSolids(int x, int z, Hunk output, boolean multicore, ChunkContext context) { - PrecisionStopwatch p = PrecisionStopwatch.start(); - int chunkHeight = output.getHeight(); - IrisData data = engine.getData(); - IrisDimension dimension = engine.getDimension(); - IrisComplex complex = engine.getComplex(); - long baseSeed = engine.getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; - FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); - FloatingIslandSample.clearChunkMemo(); - - for (int xf = 0; xf < 16; xf++) { - for (int zf = 0; zf < 16; zf++) { - int wx = x + xf; - int wz = z + zf; - IrisBiome parent = boundarySampler.parent(wx, wz); - if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { - continue; - } - FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); - if (sample == null) { - continue; - } - - long colSeed = FloatingIslandSample.columnSeed(baseSeed, wx, wz); - int paletteDepth = Math.max(4, sample.solidCount + 4); - IdentityHashMap paletteContexts = new IdentityHashMap<>(); - IdentityHashMap topDepthByEntry = new IdentityHashMap<>(); - int[] bottomDepths = bottomDepths(sample, chunkHeight); - for (int k = sample.topIdx; k >= 0; k--) { - if (!sample.solidMask[k]) { - continue; - } - int y = sample.islandBaseY + k; - if (y < 0 || y >= chunkHeight) { - continue; - } - ResolvedFloatingChild entry = sample.entryAt(k); - PaletteContext paletteContext = paletteContexts.get(entry); - if (paletteContext == null) { - paletteContext = createPaletteContext(parent, entry, dimension, wx, wz, colSeed, paletteDepth, data, complex); - paletteContexts.put(entry, paletteContext); - } - int depth = topDepthByEntry.getOrDefault(entry, 0); - int bottomDepth = bottomDepths == null || bottomDepths[k] < 0 ? depth : bottomDepths[k]; - PlatformBlockState block = selectPaletteBlock(entry, paletteContext.topBlocks, paletteContext.bottomBlocks, depth, bottomDepth, paletteContext.fallbackSolid); - if (block != null) { - output.set(xf, y, zf, block); - } - topDepthByEntry.put(entry, depth + 1); - } - - ResolvedFloatingChild entry = sample.entry; - int localFluidHeight = entry.settings().localFluidHeight().orElse(0); - if (localFluidHeight > 0) { - PlatformBlockState fluid = B.getStateOrNull(entry.settings().fluidBlock()); - if (fluid == null) { - fluid = B.getState("minecraft:water"); - } - int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); - for (int k = 1; k <= fluidCap; k++) { - if (sample.solidMask[k]) { - continue; - } - int y = sample.islandBaseY + k; - if (y < 0 || y >= chunkHeight) { - continue; - } - boolean hasSolidBelow = false; - for (int kb = k - 1; kb >= 0; kb--) { - if (sample.solidMask[kb]) { - hasSolidBelow = true; - break; - } - } - if (hasSolidBelow) { - output.set(xf, y, zf, fluid); - } - } - } - - writeIslandSkyBiomes(parent, wx, wz, sample, chunkHeight, data); - } - } - - engine.getMetrics().getTerrain().put(p.getMilliseconds()); - } - - /** Decorates the tops of the islands in the chunk whose first block is {@code x}, {@code z}. */ - public void decorateColumns(int x, int z, Hunk output, boolean multicore, ChunkContext context, DecorationScene scene) { - int chunkHeight = output.getHeight(); - IrisData data = engine.getData(); - IrisComplex complex = engine.getComplex(); - long baseSeed = engine.getSeedManager().getTerrain() ^ FLOATING_BASE_SEED_SALT; - FloatingIslandBoundarySampler boundarySampler = context.getFloatingIslandBoundarySampler(); - - for (int xf = 0; xf < 16; xf++) { - for (int zf = 0; zf < 16; zf++) { - int wx = x + xf; - int wz = z + zf; - IrisBiome parent = boundarySampler.parent(wx, wz); - if (parent == null || FloatingChildren.declaredBy(parent).isEmpty()) { - continue; - } - FloatingIslandSample sample = FloatingIslandSample.sampleMemoized(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); - if (sample == null) { - continue; - } - ResolvedFloatingChild entry = sample.entry; - IrisBiome target = entry.getRealBiome(parent, data); - - if (!entry.settings().inheritDecorators() || target == null) { - continue; - } - - int topY = sample.topY(); - int max = Math.max(1, chunkHeight - topY); - if (topY + 1 < chunkHeight) { - PlatformBlockState above = output.get(xf, topY + 1, zf); - if (above == null || above.isAir()) { - try { - RNG colRng = rng.nextParallelRNG((int) FloatingIslandSample.columnSeed(baseSeed, wx, wz)); - FloatingDecorator.decorateColumn(scene, IrisDecoratedBiomes.of(target, BiomeKind.LAND), DecorationPart.NONE, xf, zf, wx, wz, topY, max, colRng, NOOP_DECORATION_MISS); - } catch (Throwable e) { - log.error("Failed to decorate the top of a floating island", e); - } - } - } - - int localFluidHeight = entry.settings().localFluidHeight().orElse(0); - if (localFluidHeight > 0) { - int fluidCap = Math.min(sample.thickness - 1, localFluidHeight); - int fluidTopY = -1; - for (int k = 1; k <= fluidCap; k++) { - if (sample.solidMask[k]) { - continue; - } - int y = sample.islandBaseY + k; - if (y < 0 || y >= chunkHeight) { - continue; - } - boolean hasSolidBelow = false; - for (int kb = k - 1; kb >= 0; kb--) { - if (sample.solidMask[kb]) { - hasSolidBelow = true; - break; - } - } - if (hasSolidBelow && y > fluidTopY) { - fluidTopY = y; - } - } - if (fluidTopY > 0 && fluidTopY + 1 < chunkHeight && B.isAir(output.get(xf, fluidTopY + 1, zf))) { - try { - new IrisSeaSurfaceDecorator(scene).decorate(xf, zf, wx, wx + 1, wx - 1, wz, wz + 1, wz - 1, IrisDecoratedBiomes.of(target, BiomeKind.LAND), fluidTopY, chunkHeight); - } catch (Throwable e) { - log.error("Failed to decorate the sea surface of a floating island", e); - } - } - } - } - } - } - - private void writeIslandSkyBiomes(IrisBiome parent, int wx, int wz, FloatingIslandSample sample, int chunkHeight, IrisData data) { + /** Paints, for each child the column's island is made of, its biome's sky biome into the child's solid blocks. */ + private void paintSkyBiomes(ResourceId parent, int wx, int wz, FloatingIslandSample sample, int chunkHeight) { try { - IdentityHashMap matterByEntry = new IdentityHashMap<>(); + Map> solidYsByEntry = new IdentityHashMap<>(); for (int k = 0; k <= sample.topIdx; k++) { if (!sample.solidMask[k]) { continue; @@ -396,29 +413,48 @@ public class FloatingIslands { if (y < 0 || y >= chunkHeight) { continue; } - ResolvedFloatingChild entry = sample.entryAt(k); - MatterBiomeInject matter = matterByEntry.get(entry); - if (matter == null) { - IrisBiome target = entry == null ? parent : entry.getRealBiome(parent, data); - if (target == null) { - continue; - } - matter = createSkyBiomeMatter(target, wx, wz); - matterByEntry.put(entry, matter); + solidYsByEntry.computeIfAbsent(sample.entryAt(k), ignored -> new ArrayList<>()).add(y); + } + for (Map.Entry> solid : solidYsByEntry.entrySet()) { + ResolvedFloatingChild entry = solid.getKey(); + ResourceId target = entry == null ? parent : entry.realBiome(parent); + if (target == null) { + continue; } - engine.getMantle().getMantle().set(wx, y, wz, matter); + int[] ys = solid.getValue().stream().mapToInt(Integer::intValue).toArray(); + world.host().paintSkyBiome(target, wx, wz, ys, rng); } } catch (Throwable e) { log.error("Failed to write the sky biomes of a floating island", e); } } - private MatterBiomeInject createSkyBiomeMatter(IrisBiome target, int wx, int wz) { - if (target.isCustom()) { - IrisBiomeCustom custom = target.getCustomBiome(rng, engine, wx, 0, wz); - return BiomeInjectMatter.get(IrisPlatforms.get().biomeWriter().biomeIdFor(engine.getDimension().getLoadKey() + ":" + custom.getId())); - } + private record PaletteContext(List topBlocks, List bottomBlocks) { + } - return BiomeInjectMatter.get(IrisPlatforms.get().biomeWriter().biomeIdFor(target.getSkyBiomeKey(rng, engine, wx, 0, wz))); + /** What one chunk's columns share: its views of the blocks, terrain and settings, and its island fields. */ + private final class Chunk { + final int originX; + final int originZ; + final Hunk output; + final int height; + final BlockRegistry blocks; + final FeatureSettings settings; + final PaletteExplosion explosion; + final ColumnSlope slope; + final FloatingIslandBoundarySampler boundarySampler; + + Chunk(ChunkStageContext context) { + this.originX = context.originX(); + this.originZ = context.originZ(); + this.output = context.hunk(BlockState.class); + this.height = output.getHeight(); + this.blocks = context.resources().blocks(); + this.settings = context.settings(); + this.explosion = PaletteExplosion.of(settings, originX + CHUNK_CENTRE, originZ + CHUNK_CENTRE); + TerrainSampler terrain = context.terrain(); + this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); + this.boundarySampler = new FloatingIslandBoundarySampler(world.host()::surfaceBiome); + } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 3603640aa..7a2fd6cbf 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -18,16 +18,11 @@ package art.arcane.iris.engine.modifier; +import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; -import com.volmit.FeatureRegistry; -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.core.modules.IrisChunk; -import art.arcane.iris.engine.decorator.DecorationScene; -import art.arcane.iris.core.modules.IrisMantleChunk; -import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; @@ -39,9 +34,8 @@ import com.volmit.stage.StageGraph; /** * Module {@code iris:floating}: the islands of floating child biomes, their objects in the mantle after the * dimension's other objects, their solids after smoothing and their decoration after the chunk's own. The - * mantle stage is a port of what was Iris's floating object mantle component, its work done by - * {@link FloatingObjectPlacing}, whose reach is the pack's largest floating object placement. The chunk - * stages' work is done by {@link FloatingIslands}. + * mantle stage's work is done by {@link FloatingObjectPlacing}, whose reach is the pack's largest floating object + * placement. The chunk stages' work is done by {@link FloatingIslands}. */ public final class FloatingModule implements IrisModule { private static final String VERSION = "built-in"; @@ -71,30 +65,18 @@ public final class FloatingModule implements IrisModule { } private static void objects(MantleStageContext context) { - IrisMantleChunk chunk = IrisMantleChunk.current(); - objectPlacing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + FloatingObjectPlacing.of(context.world(), context.log()).place(context); } private int objectReach(PackSettings settings) { - return objectPlacing(IrisPackSettings.of(settings).engine(), log).reach(); + return FloatingObjectPlacing.reach(settings, log); } private static void solids(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - islands(chunk, context.log()).fillSolids(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context()); + FloatingIslands.of(context.world(), context.log()).fillSolids(context); } private static void decorate(ChunkStageContext context) { - IrisChunk chunk = IrisChunk.current(); - islands(chunk, context.log()).decorateColumns(chunk.originX(), chunk.originZ(), chunk.blocks(), chunk.multicore(), chunk.context(), - DecorationScene.of(context)); - } - - private static FloatingObjectPlacing objectPlacing(Engine engine, ModuleLog log) { - return engine.getGeneration().state(FloatingObjectPlacing.class, generating -> new FloatingObjectPlacing(generating, log)); - } - - private static FloatingIslands islands(IrisChunk chunk, ModuleLog log) { - return chunk.state(FloatingIslands.class, generating -> new FloatingIslands(generating, log)); + FloatingIslands.of(context.world(), context.log()).decorateColumns(context); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java b/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java deleted file mode 100644 index 7427ad2fb..000000000 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisLayers.java +++ /dev/null @@ -1,111 +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.modifier; - -import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; -import art.arcane.iris.builtin.terrain.ExplodeBiomePaletteSizeSettings; -import art.arcane.iris.builtin.terrain.ExplodeBiomePalettesSettings; -import art.arcane.iris.builtin.terrain.LayersSettings; -import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; -import art.arcane.iris.builtin.terrain.LockLayersSettings; -import art.arcane.iris.builtin.terrain.SeaLayersSettings; -import art.arcane.iris.builtin.terrain.WallSettings; -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.builtin.terrain.ColumnSlope; -import art.arcane.iris.builtin.terrain.LayeredBiome; -import art.arcane.iris.builtin.terrain.PaletteExplosion; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.collection.KList; -import com.volmit.block.BlockState; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Map; - -/** - * What Iris's carving and floating islands, which hold Iris's own types, hand the terrain's layers and palettes, and take back as the - * platform's blocks. One per engine: what a biome declares about its layers is read once for each biome. - */ -final class IrisLayers { - private final Engine engine; - private final Map biomes = Collections.synchronizedMap(new IdentityHashMap<>()); - private final Map platformStates = Collections.synchronizedMap(new IdentityHashMap<>()); - private final ColumnSlope slope; - private volatile PaletteExplosion explosion; - - IrisLayers(Engine engine) { - this.engine = engine; - this.slope = (x, z) -> engine.getComplex().getSlopeStream().get(x, z); - } - - /** What the biome declares about its layers. */ - LayeredBiome biome(IrisBiome biome) { - return biomes.computeIfAbsent(biome, declared -> new LayeredBiome( - declared.getModuleSettings().find(LayersSettings.class).orElse(null), - declared.getModuleSettings().find(SeaLayersSettings.class).orElse(null), - declared.getModuleSettings().find(CaveCeilingLayersSettings.class).orElse(null), - declared.getModuleSettings().find(LockLayersSettings.class).orElse(null), - declared.getModuleSettings().find(LockLayersMaxSettings.class).orElse(null), - declared.getModuleSettings().find(WallSettings.class).orElse(null))); - } - - /** The biome with only its wall, for a caller that asks for nothing else. */ - static LayeredBiome wallOf(IrisBiome biome) { - return new LayeredBiome(null, null, null, null, null, biome.getModuleSettings().find(WallSettings.class).orElse(null)); - } - - /** What the engine's dimension declares about separating layers with barriers. */ - PaletteExplosion explosion() { - PaletteExplosion known = explosion; - if (known == null) { - known = explosionOf(engine.getDimension()); - explosion = known; - } - return known; - } - - static PaletteExplosion explosionOf(IrisDimension dimension) { - if (dimension == null) { - return PaletteExplosion.NONE; - } - return new PaletteExplosion( - dimension.getModuleSettings().find(ExplodeBiomePalettesSettings.class).map(ExplodeBiomePalettesSettings::explode).orElse(false), - dimension.getModuleSettings().find(ExplodeBiomePaletteSizeSettings.class).map(ExplodeBiomePaletteSizeSettings::size) - .orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE)); - } - - ColumnSlope slope() { - return slope; - } - - /** The platform's block for {@code block}, worked out once for each block instance, since a world's layers hold few. */ - PlatformBlockState platform(BlockState block) { - return block == null ? null : platformStates.computeIfAbsent(block, known -> B.getState(known.key())); - } - - KList platform(KList blocks) { - KList converted = new KList<>(blocks.size()); - for (BlockState block : blocks) { - converted.add(platform(block)); - } - return converted; - } -} diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/Column.java similarity index 54% rename from src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java rename to src/main/java/art/arcane/iris/engine/object/terrain/floating/Column.java index 48bcd0c1d..94cd6f352 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisDecoratedBiomes.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/Column.java @@ -15,19 +15,11 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.engine.modifier; +package art.arcane.iris.engine.object.terrain.floating; -import art.arcane.iris.builtin.decorant.DecorantSettings; -import art.arcane.iris.engine.decorator.DecoratedBiome; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import com.volmit.world.BiomeKind; - -/** The decorators' view of a biome Iris's carving and floating islands hold as an {@link IrisBiome}. */ -final class IrisDecoratedBiomes { - private IrisDecoratedBiomes() { - } - - static DecoratedBiome of(IrisBiome biome, BiomeKind kind) { - return new DecoratedBiome(biome.getLoadKey(), biome.getModuleSettings().find(DecorantSettings.class).orElse(null), kind); - } +/** + * A world column as a hash key. A long packing both coordinates would hash to {@code x ^ z} as a {@code Long}, which + * puts every diagonal of a chunk into one bucket. + */ +public record Column(int x, int z) { } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java deleted file mode 100644 index dd2ad533e..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingChildren.java +++ /dev/null @@ -1,69 +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.terrain.floating; - -import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.builtin.floating.FloatingChildSettings; -import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.world.biome.IrisBiome; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** The {@link ResolvedFloatingChild} of every {@link FloatingChildBiome} an engine runtime has met, one per decoded entry. */ -public final class FloatingChildren { - private final Map resolved = new ConcurrentHashMap<>(); - - public FloatingChildren(Engine engine) { - } - - FloatingChildren() { - } - - /** The children of the engine {@code data} serves, or of {@code data} alone when no engine runs it. */ - public static FloatingChildren of(IrisData data) { - Engine engine = data.getEngine(); - return engine == null ? new FloatingChildren() : of(engine); - } - - public static FloatingChildren of(Engine engine) { - return engine.getGeneration().state(FloatingChildren.class, FloatingChildren::new); - } - - /** The floating children {@code biome} declares, in the order it lists them; none when it declares none. */ - public static List declaredBy(IrisBiome biome) { - return biome.getModuleSettings().find(FloatingChildSettings.class).map(FloatingChildSettings::children).orElse(List.of()); - } - - /** Whether {@code biome} samples every floating child on its own and unions their islands instead of picking one per column. */ - public static boolean merges(IrisBiome biome) { - return biome.getModuleSettings().find(MergeFloatingChildrenSettings.class).map(MergeFloatingChildrenSettings::merge).orElse(false); - } - - public ResolvedFloatingChild of(FloatingChildBiome settings) { - return resolved.computeIfAbsent(settings, ResolvedFloatingChild::new); - } - - public List of(List settings) { - return settings.stream().map(this::of).toList(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java index 6b9719e15..02f5d9234 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandBoundarySampler.java @@ -18,14 +18,13 @@ package art.arcane.iris.engine.object.terrain.floating; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; -import org.jetbrains.annotations.Nullable; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.ResourceId; import java.util.IdentityHashMap; +import java.util.List; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @@ -47,20 +46,20 @@ public final class FloatingIslandBoundarySampler { this.ownershipFields = new ConcurrentHashMap<>(); } - public @Nullable IrisBiome parent(int x, int z) { + public ResourceId parent(int x, int z) { return parentField(x, z, EDGE_TAPER_WIDTH).parent(x, z); } - public double edgeFade(IrisBiome parent, int x, int z) { + public double edgeFade(ResourceId parent, int x, int z) { return edgeFade(parent, x, z, EDGE_TAPER_WIDTH); } - public double edgeFade(IrisBiome parent, int x, int z, int taperWidth) { + public double edgeFade(ResourceId parent, int x, int z, int taperWidth) { int boundaryDistance = edgeDistance(parent, x, z, taperWidth); return edgeFadeForDistance(boundaryDistance, taperWidth); } - public int edgeDistance(IrisBiome parent, int x, int z, int taperWidth) { + public int edgeDistance(ResourceId parent, int x, int z, int taperWidth) { if (parent == null) { return 0; } @@ -68,11 +67,11 @@ public final class FloatingIslandBoundarySampler { return parentField(x, z, taperWidth).edgeDistance(parent, x, z); } - public FootprintSample footprint(CNG footprint, int x, int z, double signedCut) { + public FootprintSample footprint(NoiseSampler footprint, int x, int z, double signedCut) { return footprint(footprint, x, z, signedCut, EDGE_TAPER_WIDTH); } - public FootprintSample footprint(CNG footprint, int x, int z, double signedCut, int taperWidth) { + public FootprintSample footprint(NoiseSampler footprint, int x, int z, double signedCut, int taperWidth) { int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); int chunkX = Math.floorDiv(x, CHUNK_SIZE); int chunkZ = Math.floorDiv(z, CHUNK_SIZE); @@ -83,11 +82,11 @@ public final class FloatingIslandBoundarySampler { return field.sample(x, z); } - public OwnershipSample ownership(KList entries, CNG picker, int x, int z) { + public OwnershipSample ownership(KList entries, NoiseSampler picker, int x, int z) { return ownership(entries, picker, x, z, EDGE_TAPER_WIDTH); } - public OwnershipSample ownership(KList entries, CNG picker, int x, int z, + public OwnershipSample ownership(KList entries, NoiseSampler picker, int x, int z, int taperWidth) { int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); int chunkX = Math.floorDiv(x, CHUNK_SIZE); @@ -117,14 +116,14 @@ public final class FloatingIslandBoundarySampler { ignored -> new ParentBoundaryField(source, chunkX, chunkZ, width)); } - private static boolean sameBiome(@Nullable IrisBiome expected, @Nullable IrisBiome actual) { + private static boolean sameBiome(ResourceId expected, ResourceId actual) { if (actual == expected) { return true; } - if (expected == null || actual == null || expected.getLoadKey() == null) { + if (expected == null || actual == null) { return false; } - return expected.getLoadKey().equals(actual.getLoadKey()); + return expected.equals(actual); } public record FootprintSample(double signed, int cardinalSupport, int diagonalSupport, boolean accepted, @@ -138,13 +137,13 @@ public final class FloatingIslandBoundarySampler { } private static final class FootprintFieldKey { - private final CNG footprint; + private final NoiseSampler footprint; private final int chunkX; private final int chunkZ; private final long signedCutBits; private final int taperWidth; - private FootprintFieldKey(CNG footprint, int chunkX, int chunkZ, long signedCutBits, int taperWidth) { + private FootprintFieldKey(NoiseSampler footprint, int chunkX, int chunkZ, long signedCutBits, int taperWidth) { this.footprint = footprint; this.chunkX = chunkX; this.chunkZ = chunkZ; @@ -176,12 +175,12 @@ public final class FloatingIslandBoundarySampler { private static final class OwnershipFieldKey { private final KList entries; - private final CNG picker; + private final NoiseSampler picker; private final int chunkX; private final int chunkZ; private final int taperWidth; - private OwnershipFieldKey(KList entries, CNG picker, int chunkX, int chunkZ, + private OwnershipFieldKey(KList entries, NoiseSampler picker, int chunkX, int chunkZ, int taperWidth) { this.entries = entries; this.picker = picker; @@ -216,7 +215,7 @@ public final class FloatingIslandBoundarySampler { private final FieldGeometry geometry; private final int minX; private final int minZ; - private final IrisBiome[] parents; + private final ResourceId[] parents; private final byte[] distance; private final boolean[] viable; @@ -224,17 +223,17 @@ public final class FloatingIslandBoundarySampler { this.geometry = FieldGeometry.forWidth(taperWidth); this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); this.minZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); - this.parents = new IrisBiome[geometry.area()]; + this.parents = new ResourceId[geometry.area()]; this.distance = new byte[geometry.area()]; this.viable = new boolean[geometry.area()]; build(source); } - private @Nullable IrisBiome parent(int x, int z) { + private ResourceId parent(int x, int z) { return parents[geometry.index(x - minX, z - minZ)]; } - private int edgeDistance(IrisBiome expected, int x, int z) { + private int edgeDistance(ResourceId expected, int x, int z) { int index = geometry.index(x - minX, z - minZ); if (!sameBiome(expected, parents[index]) || !viable[index]) { return 0; @@ -244,7 +243,7 @@ public final class FloatingIslandBoundarySampler { private void build(BiomeSampler source) { int rawSize = geometry.fieldSize() + 2; - IrisBiome[] raw = new IrisBiome[rawSize * rawSize]; + ResourceId[] raw = new ResourceId[rawSize * rawSize]; int rawMinX = minX - 1; int rawMinZ = minZ - 1; for (int z = 0; z < rawSize; z++) { @@ -255,7 +254,7 @@ public final class FloatingIslandBoundarySampler { for (int z = 0; z < geometry.fieldSize(); z++) { for (int x = 0; x < geometry.fieldSize(); x++) { int index = geometry.index(x, z); - IrisBiome parent = raw[rawIndex(x + 1, z + 1, rawSize)]; + ResourceId parent = raw[rawIndex(x + 1, z + 1, rawSize)]; parents[index] = parent; distance[index] = (byte) (touchesDifferentBiome(raw, parent, x, z, rawSize) ? 1 @@ -266,7 +265,7 @@ public final class FloatingIslandBoundarySampler { markLabelCoreSupported(parents, distance, viable, geometry); } - private static boolean touchesDifferentBiome(IrisBiome[] raw, @Nullable IrisBiome parent, int x, int z, + private static boolean touchesDifferentBiome(ResourceId[] raw, ResourceId parent, int x, int z, int rawSize) { for (int dz = -1; dz <= 1; dz++) { for (int dx = -1; dx <= 1; dx++) { @@ -297,7 +296,7 @@ public final class FloatingIslandBoundarySampler { private final byte[] distance; private final boolean[] viable; - private FootprintField(CNG footprint, int chunkX, int chunkZ, double signedCut, int taperWidth) { + private FootprintField(NoiseSampler footprint, int chunkX, int chunkZ, double signedCut, int taperWidth) { this.geometry = FieldGeometry.forWidth(taperWidth); this.occupancyMinX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); this.occupancyMinZ = (chunkZ * CHUNK_SIZE) - geometry.fadeRadius(); @@ -322,20 +321,20 @@ public final class FloatingIslandBoundarySampler { Byte.toUnsignedInt(diagonalSupport[index]), renderable, boundaryDistance, fade); } - private void build(CNG footprint, double signedCut) { + private void build(NoiseSampler footprint, double signedCut) { double[] rawSigned = sampleRawFootprint(footprint); buildOccupancy(rawSigned, signedCut); buildDistanceField(); } - private double[] sampleRawFootprint(CNG footprint) { + private double[] sampleRawFootprint(NoiseSampler footprint) { int rawSize = geometry.fieldSize() + 2; double[] rawSigned = new double[rawSize * rawSize]; int rawMinX = occupancyMinX - 1; int rawMinZ = occupancyMinZ - 1; for (int z = 0; z < rawSize; z++) { for (int x = 0; x < rawSize; x++) { - rawSigned[rawIndex(x, z, rawSize)] = signedFromUnit(footprint.noise(rawMinX + x, rawMinZ + z)); + rawSigned[rawIndex(x, z, rawSize)] = signedFromUnit(footprint.sample(rawMinX + x, rawMinZ + z)); } } return rawSigned; @@ -397,7 +396,7 @@ public final class FloatingIslandBoundarySampler { private final ResolvedFloatingChild[] owners; private final IdentityHashMap distances; - private OwnershipField(KList entries, CNG picker, int chunkX, int chunkZ, + private OwnershipField(KList entries, NoiseSampler picker, int chunkX, int chunkZ, int taperWidth) { this.geometry = FieldGeometry.forWidth(taperWidth); this.minX = (chunkX * CHUNK_SIZE) - geometry.fadeRadius(); @@ -406,8 +405,8 @@ public final class FloatingIslandBoundarySampler { this.distances = new IdentityHashMap<>(); for (int z = 0; z < geometry.fieldSize(); z++) { for (int x = 0; x < geometry.fieldSize(); x++) { - double value = Math.max(0.0D, Math.min(1.0D, picker.noise(minX + x, minZ + z))); - owners[geometry.index(x, z)] = IRare.pick(entries, value); + double value = Math.max(0.0D, Math.min(1.0D, picker.sample(minX + x, minZ + z))); + owners[geometry.index(x, z)] = pickByRarity(entries, value); } } for (ResolvedFloatingChild entry : entries) { @@ -451,6 +450,35 @@ public final class FloatingIslandBoundarySampler { private record ComponentDistanceField(byte[] distance, boolean[] viable) { } + /** The entry {@code noiseValue} (0..1) lands on when each entry takes a share of the range inverse to its rarity. */ + static ResolvedFloatingChild pickByRarity(List entries, double noiseValue) { + if (entries.isEmpty()) { + return null; + } + if (entries.size() == 1) { + return entries.getFirst(); + } + + double total = 0; + for (ResolvedFloatingChild entry : entries) { + total += 1d / rarityOf(entry); + } + + double threshold = total * noiseValue; + double buffer = 0; + for (ResolvedFloatingChild entry : entries) { + buffer += 1d / rarityOf(entry); + if (buffer >= threshold) { + return entry; + } + } + return entries.getLast(); + } + + private static int rarityOf(ResolvedFloatingChild entry) { + return Math.max(1, entry.rarity()); + } + private record FieldGeometry(int taperWidth, int fadeRadius, int fieldSize, int maxDistance) { private static FieldGeometry forWidth(int taperWidth) { int width = FloatingIslandEdgeProfile.clampWidth(taperWidth); @@ -546,7 +574,7 @@ public final class FloatingIslandBoundarySampler { } } - private static void markLabelCoreSupported(IrisBiome[] labels, byte[] distance, boolean[] viable, + private static void markLabelCoreSupported(ResourceId[] labels, byte[] distance, boolean[] viable, FieldGeometry geometry) { for (int z = 0; z < geometry.fieldSize(); z++) { for (int x = 0; x < geometry.fieldSize(); x++) { @@ -559,8 +587,8 @@ public final class FloatingIslandBoundarySampler { } } - private static boolean hasCoreNeighbor(@Nullable boolean[] inside, byte[] distance, - @Nullable IrisBiome[] labels, int x, int z, FieldGeometry geometry) { + private static boolean hasCoreNeighbor(boolean[] inside, byte[] distance, + ResourceId[] labels, int x, int z, FieldGeometry geometry) { int index = geometry.index(x, z); for (int dz = -1; dz <= 1; dz++) { for (int dx = -1; dx <= 1; dx++) { @@ -591,6 +619,6 @@ public final class FloatingIslandBoundarySampler { @FunctionalInterface public interface BiomeSampler { - @Nullable IrisBiome sample(int x, int z); + ResourceId sample(int x, int z); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java index 62e8ccdca..3f7e69776 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandEdgeProfile.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.terrain.floating; -import art.arcane.iris.util.project.noise.CNG; +import com.volmit.noise.NoiseSampler; public final class FloatingIslandEdgeProfile { public static final int DEFAULT_WIDTH = 10; @@ -34,9 +34,9 @@ public final class FloatingIslandEdgeProfile { private final int width; private final double exponent; private final double variationAmplitude; - private final CNG variation; + private final NoiseSampler variation; - public FloatingIslandEdgeProfile(int width, double exponent, double variationAmplitude, CNG variation) { + public FloatingIslandEdgeProfile(int width, double exponent, double variationAmplitude, NoiseSampler variation) { this.width = clampWidth(width); this.exponent = clampExponent(exponent); this.variationAmplitude = clampVariationAmplitude(variationAmplitude, this.width); @@ -65,7 +65,7 @@ public final class FloatingIslandEdgeProfile { } double localWidth = width; if (variation != null && variationAmplitude > 0.0D) { - double noise = Math.max(0.0D, Math.min(1.0D, variation.noise(x, z))); + double noise = Math.max(0.0D, Math.min(1.0D, variation.sample(x, z))); double signedNoise = (noise * 2.0D) - 1.0D; localWidth += signedNoise * variationAmplitude; } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 82e2d9d63..8c864d072 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -20,13 +20,10 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.util.project.noise.CNG; import art.arcane.volmlib.util.collection.KList; import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; +import com.volmit.noise.NoiseSampler; +import com.volmit.resource.ResourceId; import java.util.Arrays; import java.util.List; @@ -54,8 +51,9 @@ public final class FloatingIslandSample { private static final double CARVE_MAX_VERTICAL_RUN_FRACTION = 0.18D; private static final ThreadLocal LAST_REJECT = ThreadLocal.withInitial(() -> new int[1]); private static final ThreadLocal LAST_DENSITY = ThreadLocal.withInitial(() -> new double[2]); - private static final ThreadLocal> CHUNK_MEMO = ThreadLocal.withInitial(HashMap::new); - private static final ThreadLocal> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new); + private static final ThreadLocal> CHUNK_MEMO = ThreadLocal.withInitial(HashMap::new); + private static final ThreadLocal>> FOOTPRINT_MEMO = ThreadLocal.withInitial(IdentityHashMap::new); + private static final int FOOTPRINT_MEMO_CAPACITY = 512; private static final AtomicBoolean NULL_CNG_WARNED = new AtomicBoolean(false); public static int getLastReject() { @@ -78,13 +76,13 @@ public final class FloatingIslandSample { FOOTPRINT_MEMO.get().clear(); } - public static FloatingIslandSample sampleMemoized(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { - long key = (((long) wx) << 32) ^ (wz & 0xFFFFFFFFL); - HashMap memo = CHUNK_MEMO.get(); + public static FloatingIslandSample sampleMemoized(ResourceId parent, int wx, int wz, int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + Column key = new Column(wx, wz); + HashMap memo = CHUNK_MEMO.get(); if (memo.containsKey(key)) { return memo.get(key); } - FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); + FloatingIslandSample result = sample(parent, wx, wz, chunkHeight, world, boundarySampler, log); memo.put(key, result); return result; } @@ -94,11 +92,11 @@ public final class FloatingIslandSample { return null; } - private static void warnNullCng(String styleField, IrisBiome parent, ModuleLog log) { + private static void warnNullCng(String styleField, ResourceId parent, ModuleLog log) { if (NULL_CNG_WARNED.compareAndSet(false, true)) { - String biomeKey = parent == null ? "" : parent.getLoadKey(); - log.warn("Floating child biome on " + biomeKey + " has a null CNG for " + styleField - + " (style factory returned null or AtomicCache swallowed an exception); skipping floating sampling until pack is fixed"); + String biomeKey = parent == null ? "" : parent.toString(); + log.warn("Floating child biome on " + biomeKey + " has no noise for " + styleField + + " (the noise factory failed or AtomicCache swallowed an exception); skipping floating sampling until pack is fixed"); } } @@ -175,19 +173,17 @@ public final class FloatingIslandSample { return baseSeed ^ ((long) wx * 341873128712L) ^ ((long) wz * 132897987541L); } - private static int maximumEdgeFieldWidth(KList entries, long baseSeed, - IrisData data, IrisBiome parent, ModuleLog log) { + private static int maximumEdgeFieldWidth(KList entries, ResourceId parent, ModuleLog log) { int maximumWidth = FloatingIslandEdgeProfile.MIN_WIDTH; for (ResolvedFloatingChild entry : entries) { - FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, baseSeed, data, parent, log); + FloatingIslandEdgeProfile profile = resolveEdgeProfile(entry, parent, log); maximumWidth = Math.max(maximumWidth, profile.fieldWidth()); } return maximumWidth; } - private static FloatingIslandEdgeProfile resolveEdgeProfile(ResolvedFloatingChild entry, long baseSeed, - IrisData data, IrisBiome parent, ModuleLog log) { - FloatingIslandEdgeProfile profile = entry.getEdgeTaperProfile(baseSeed, data); + private static FloatingIslandEdgeProfile resolveEdgeProfile(ResolvedFloatingChild entry, ResourceId parent, ModuleLog log) { + FloatingIslandEdgeProfile profile = entry.edgeTaperProfile(); if (profile != null) { return profile; } @@ -195,21 +191,21 @@ public final class FloatingIslandSample { return FloatingIslandEdgeProfile.DEFAULT; } - public static FloatingIslandSample sample(IrisBiome parent, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { - List settings = FloatingChildren.declaredBy(parent); + public static FloatingIslandSample sample(ResourceId parent, int wx, int wz, int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + List settings = world.declaredBy(parent); if (settings.isEmpty()) { return reject(REJECT_NO_ENTRIES); } - KList entries = new KList<>(FloatingChildren.of(data).of(settings)); - return sample(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, log); + KList entries = new KList<>(world.resolve(settings)); + return sample(parent, entries, wx, wz, chunkHeight, world, boundarySampler, log); } - static FloatingIslandSample sample(IrisBiome parent, KList entries, int wx, int wz, int chunkHeight, long baseSeed, IrisData data, Engine engine, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { - int boundaryFieldWidth = maximumEdgeFieldWidth(entries, baseSeed, data, parent, log); + static FloatingIslandSample sample(ResourceId parent, KList entries, int wx, int wz, int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, ModuleLog log) { + int boundaryFieldWidth = maximumEdgeFieldWidth(entries, parent, log); int parentBoundaryDistance = boundarySampler.edgeDistance(parent, wx, wz, boundaryFieldWidth); - if (FloatingChildren.merges(parent)) { - return sampleMerged(parent, entries, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, + if (world.merges(parent)) { + return sampleMerged(parent, entries, wx, wz, chunkHeight, world, boundarySampler, parentBoundaryDistance, boundaryFieldWidth, log); } @@ -219,7 +215,7 @@ public final class FloatingIslandSample { entry = entries.getFirst(); } else { ResolvedFloatingChild reference = entries.getFirst(); - CNG picker = reference.getPickerCng(baseSeed, data); + NoiseSampler picker = reference.pickerNoise(); if (picker == null) { warnNullCng("pickerStyle", parent, log); return reject(REJECT_NO_PICK); @@ -233,20 +229,20 @@ public final class FloatingIslandSample { ownershipBoundaryDistance = ownership.boundaryDistance(); } - return sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, boundarySampler, + return sampleEntry(parent, entry, wx, wz, chunkHeight, world, boundarySampler, parentBoundaryDistance, ownershipBoundaryDistance, log); } - private static FloatingIslandSample sampleMerged(IrisBiome parent, KList entries, - int wx, int wz, int chunkHeight, long baseSeed, IrisData data, - Engine engine, FloatingIslandBoundarySampler boundarySampler, + private static FloatingIslandSample sampleMerged(ResourceId parent, KList entries, + int wx, int wz, int chunkHeight, FloatingWorld world, + FloatingIslandBoundarySampler boundarySampler, int parentBoundaryDistance, int boundaryFieldWidth, ModuleLog log) { KList samples = new KList<>(); int minY = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; for (ResolvedFloatingChild entry : entries) { - FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, baseSeed, data, engine, + FloatingIslandSample sample = sampleEntry(parent, entry, wx, wz, chunkHeight, world, boundarySampler, parentBoundaryDistance, boundaryFieldWidth + 1, log); if (sample == null) { continue; @@ -308,12 +304,12 @@ public final class FloatingIslandSample { return new FloatingIslandSample(topEntry, minY, thickness, topIdx, solidCount, solidMask, entryMask); } - private static FloatingIslandSample sampleEntry(IrisBiome parent, ResolvedFloatingChild entry, int wx, int wz, - int chunkHeight, long baseSeed, IrisData data, Engine engine, + private static FloatingIslandSample sampleEntry(ResourceId parent, ResolvedFloatingChild entry, int wx, int wz, + int chunkHeight, FloatingWorld world, FloatingIslandBoundarySampler boundarySampler, int parentBoundaryDistance, int ownershipBoundaryDistance, ModuleLog log) { - FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, baseSeed, data, parent, log); - CNG footprintCng = entry.getFootprintCng(baseSeed, data); + FloatingIslandEdgeProfile edgeProfile = resolveEdgeProfile(entry, parent, log); + NoiseSampler footprintCng = entry.footprintNoise(); if (footprintCng == null) { warnNullCng("footprintStyle", parent, log); return reject(REJECT_NO_SEED); @@ -339,28 +335,28 @@ public final class FloatingIslandSample { return reject(REJECT_NO_THICKNESS); } - CNG altitudeCng = entry.getAltitudeCng(baseSeed, data); + NoiseSampler altitudeCng = entry.altitudeNoise(); if (altitudeCng == null) { warnNullCng("altitudeStyle", parent, log); return reject(REJECT_NO_SEED); } - double altNoise = altitudeCng.noise(wx, wz); + double altNoise = altitudeCng.sample(wx, wz); double altClamped = Math.max(0, Math.min(1, altNoise)); - int worldMin = engine.getWorld().minHeight(); + int worldMin = world.minHeight(); int minAlt = Math.max(0, entry.settings().minHeightAboveSurface() - worldMin); int maxAlt = Math.max(minAlt, entry.settings().maxHeightAboveSurface() - worldMin); int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); - IrisBiome target = entry.getRealBiome(parent, data); - int fullTopHeight = computeTopHeight(entry, target, engine, baseSeed, wx, wz, data, log); + ResourceId target = entry.realBiome(parent); + int fullTopHeight = computeTopHeight(entry, target, world, wx, wz, log); int topH = roundedEdgeHeight(fullTopHeight, edgeFade); - CNG bottomCng = entry.getBottomCng(baseSeed, data); + NoiseSampler bottomCng = entry.bottomNoise(); if (bottomCng == null) { warnNullCng("bottomStyle", parent, log); return reject(REJECT_NO_SEED); } - double bottomNoise = bottomCng.noise(wx, wz); + double bottomNoise = bottomCng.sample(wx, wz); double bottomClamped = Math.max(0, Math.min(1, bottomNoise)); double bottomShaped = Math.pow(bottomClamped, Math.max(0.1, entry.settings().bottomExponent())); int minDepth = Math.max(0, entry.settings().bottomDepthMin()); @@ -412,11 +408,11 @@ public final class FloatingIslandSample { } boolean[] solidMask = new boolean[thickness]; - CNG wallWarp = entry.getWallWarpCng(baseSeed, data); + NoiseSampler wallWarp = entry.wallWarpNoise(); double warpAmp = Math.max(0, entry.settings().wallWarpAmplitude()); double effectiveWarpAmp = effectiveWallWarpAmplitude(warpAmp, edgeFade); - CaveProfileSampler carvingProfileSampler = entry.getCarvingProfileSampler(engine, data); - CNG carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.getCarveCng(baseSeed, data) : null; + CaveProfileSampler carvingProfileSampler = entry.carvingProfileSampler(); + NoiseSampler carve = carvingProfileSampler == null && !entry.hasCarvingReference() ? entry.carveNoise() : null; double carveThreshold = entry.settings().carveThreshold(); boolean useWarp = wallWarp != null && effectiveWarpAmp > 0; boolean useProfileCarve = carvingProfileSampler != null; @@ -484,7 +480,7 @@ public final class FloatingIslandSample { return amplitude * fade; } - static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, CNG carve, double carveThreshold) { + static boolean directCarveEnabled(ResolvedFloatingChild entry, CaveProfileSampler carvingProfileSampler, NoiseSampler carve, double carveThreshold) { return carvingProfileSampler == null && (entry == null || !entry.hasCarvingReference()) && carve != null && carveThreshold < 1.0; } @@ -492,9 +488,9 @@ public final class FloatingIslandSample { return edgeFade >= 1.0 && support.isFullySurrounded(); } - static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, CNG carve, double carveThreshold) { + static int carveSolidInterior(boolean[] solidMask, boolean[] lateralCarveMask, int botY, int wx, int wz, NoiseSampler carve, double carveThreshold) { return carveSolidInterior(solidMask, lateralCarveMask, botY, wx, wz, (x, y, z) -> { - double carveNoise = carve.noise(x, y, z); + double carveNoise = carve.sample(x, y, z); double carveClamped = Math.max(0, Math.min(1, carveNoise)); return carveClamped > carveThreshold; }); @@ -612,7 +608,7 @@ public final class FloatingIslandSample { return cardinal >= CARVE_CARDINAL_SUPPORT && cardinal + diagonal >= CARVE_TOTAL_SUPPORT; } - static boolean hasFootprintNeighborSupport(CNG footprintCng, int wx, int wz, double signedCut) { + static boolean hasFootprintNeighborSupport(NoiseSampler footprintCng, int wx, int wz, double signedCut) { return footprintNeighborSupport(footprintCng, wx, wz, signedCut).hasSolidSupport(); } @@ -620,7 +616,7 @@ public final class FloatingIslandSample { return support.canFillPinhole(); } - static NeighborSupport footprintNeighborSupport(CNG footprintCng, int wx, int wz, double signedCut) { + static NeighborSupport footprintNeighborSupport(NoiseSampler footprintCng, int wx, int wz, double signedCut) { int cardinal = 0; int diagonal = 0; for (int dx = -1; dx <= 1; dx++) { @@ -642,7 +638,7 @@ public final class FloatingIslandSample { return new NeighborSupport(cardinal, diagonal); } - static NeighborSupport layerNeighborSupport(CNG footprintCng, CNG wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { + static NeighborSupport layerNeighborSupport(NoiseSampler footprintCng, NoiseSampler wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { int cardinal = 0; int diagonal = 0; for (int dx = -1; dx <= 1; dx++) { @@ -663,45 +659,34 @@ public final class FloatingIslandSample { return new NeighborSupport(cardinal, diagonal); } - static boolean layerFootprintSolid(CNG footprintCng, CNG wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { + static boolean layerFootprintSolid(NoiseSampler footprintCng, NoiseSampler wallWarp, boolean useWarp, double warpAmp, int wx, int wy, int wz, double signedCut) { double sx = wx; double sz = wz; if (useWarp) { - double wnX = wallWarp.noise(wx, wy, wz); + double wnX = wallWarp.sample(wx, wy, wz); double signedWarpX = signedFromUnit(wnX); sx = wx + signedWarpX * warpAmp; - double wnZ = wallWarp.noise(wx + 1987.3, wy, wz + 2341.1); + double wnZ = wallWarp.sample(wx + 1987.3, wy, wz + 2341.1); double signedWarpZ = signedFromUnit(wnZ); sz = wz + signedWarpZ * warpAmp; } - double layerFoot = footprintCng.noise(sx, sz); + double layerFoot = footprintCng.sample(sx, sz); return signedFromUnit(layerFoot) > signedCut; } - private static double footprintSigned(CNG footprintCng, int wx, int wz) { - IdentityHashMap memoByCng = FOOTPRINT_MEMO.get(); - Long2DoubleOpenHashMap memo = memoByCng.get(footprintCng); - if (memo == null) { - memo = new Long2DoubleOpenHashMap(512); - memo.defaultReturnValue(Double.NaN); - memoByCng.put(footprintCng, memo); - } - - long key = columnKey(wx, wz); - double cached = memo.get(key); - if (!Double.isNaN(cached)) { + private static double footprintSigned(NoiseSampler footprintCng, int wx, int wz) { + HashMap memo = FOOTPRINT_MEMO.get().computeIfAbsent(footprintCng, ignored -> new HashMap<>(FOOTPRINT_MEMO_CAPACITY)); + Column key = new Column(wx, wz); + Double cached = memo.get(key); + if (cached != null) { return cached; } - double signed = signedFromUnit(footprintCng.noise(wx, wz)); + double signed = signedFromUnit(footprintCng.sample(wx, wz)); memo.put(key, signed); return signed; } - private static long columnKey(int wx, int wz) { - return ((long) wx << 32) ^ (wz & 0xFFFFFFFFL); - } - private static double signedFromUnit(double value) { return (Math.max(0, Math.min(1, value)) * 2.0) - 1.0; } @@ -775,7 +760,7 @@ public final class FloatingIslandSample { } } - private static int computeTopHeight(ResolvedFloatingChild entry, IrisBiome target, Engine engine, long baseSeed, int wx, int wz, IrisData data, ModuleLog log) { + private static int computeTopHeight(ResolvedFloatingChild entry, ResourceId target, FloatingWorld world, int wx, int wz, ModuleLog log) { int maxTopHeight = Math.max(0, entry.settings().maxTopHeight()); if (maxTopHeight == 0) { return 0; @@ -783,12 +768,12 @@ public final class FloatingIslandSample { return switch (entry.settings().topShapeMode()) { case FLAT -> maxTopHeight; case NOISE -> { - CNG topCng = entry.getTopShapeCng(baseSeed, data); + NoiseSampler topCng = entry.topShapeNoise(); if (topCng == null) { warnNullCng("topShapeStyle", null, log); yield maxTopHeight / 2; } - double n = topCng.noise(wx, wz); + double n = topCng.sample(wx, wz); double clamped = Math.max(0, Math.min(1, n)); double amp = Math.max(0, Math.min(1, entry.settings().topShapeAmp())); yield (int) Math.round(clamped * amp * maxTopHeight); @@ -797,7 +782,7 @@ public final class FloatingIslandSample { if (target == null) { yield maxTopHeight / 2; } - double h = target.getHeight(engine, wx, wz, baseSeed); + double h = world.host().biomeHeight(target, wx, wz, world.baseSeed()); int rounded = (int) Math.round(h); if (rounded < 0) { yield 0; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java new file mode 100644 index 000000000..ef8108107 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -0,0 +1,155 @@ +/* + * 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.terrain.floating; + +import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.builtin.floating.FloatingHost; +import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import com.volmit.FeatureAttachment.Target; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.noise.NoiseFactory; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * What the floating islands of one world are made from: the world's hosts, noise and seeds, the floating children each + * biome declares, and the {@link ResolvedFloatingChild} of every child met, one per decoded entry. One per world ({@link #of}). + */ +public final class FloatingWorld { + private static final long BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; + + private final FloatingHost host; + private final ObjectHost objects; + private final NoiseFactory noise; + private final long baseSeed; + private final long carveSeed; + private final int minHeight; + private final List dimensionCarving; + private final Map resolved = new ConcurrentHashMap<>(); + + FloatingWorld(FloatingHost host, ObjectHost objects, NoiseFactory noise, long terrainSeed, long carveSeed, int minHeight, + List dimensionCarving) { + this.host = host; + this.objects = objects; + this.noise = noise; + this.baseSeed = terrainSeed ^ BASE_SEED_SALT; + this.carveSeed = carveSeed; + this.minHeight = minHeight; + this.dimensionCarving = List.copyOf(dimensionCarving); + } + + /** The floating islands of {@code world}. */ + public static FloatingWorld of(PackWorld world) { + return world.state(FloatingWorld.class, FloatingWorld::create); + } + + private static FloatingWorld create(PackWorld world) { + return new FloatingWorld(FloatingHost.of(world), ObjectHost.of(world), world.resources().noise(), IrisSeed.TERRAIN.of(world), + IrisSeed.CARVE.of(world), world.minHeight(), dimensionCarvingOf(world)); + } + + private static List dimensionCarvingOf(PackWorld world) { + return world.settings().declared(CarvingSettings.class).stream() + .filter(entry -> entry.level() == Target.DIMENSION) + .map(Entry::value) + .findFirst() + .map(CarvingSettings::entries) + .orElse(List.of()); + } + + public FloatingHost host() { + return host; + } + + public ObjectHost objects() { + return objects; + } + + public NoiseFactory noise() { + return noise; + } + + /** The seed every island's noise and column random derive from. */ + public long baseSeed() { + return baseSeed; + } + + long carveSeed() { + return carveSeed; + } + + /** The platform's Y of the dimension's bottom. */ + public int minHeight() { + return minHeight; + } + + /** The floating children {@code biome} declares, in the order it lists them; none when it declares none. */ + public List declaredBy(ResourceId biome) { + return objects.biomeDeclaration(biome, FloatingChildSettings.class).map(FloatingChildSettings::children).orElse(List.of()); + } + + /** Whether {@code biome} samples every floating child on its own and unions their islands instead of picking one per column. */ + public boolean merges(ResourceId biome) { + return objects.biomeDeclaration(biome, MergeFloatingChildrenSettings.class).map(MergeFloatingChildrenSettings::merge).orElse(false); + } + + public ResolvedFloatingChild resolve(FloatingChildBiome settings) { + return resolved.computeIfAbsent(settings, declared -> new ResolvedFloatingChild(declared, this)); + } + + public List resolve(List settings) { + return settings.stream().map(this::resolve).toList(); + } + + /** The surface object placements {@code biome} declares. */ + public static List surfaceObjects(ObjectHost objects, ResourceId biome) { + return objects.biomeDeclaration(biome, ObjectSettings.class).map(ObjectSettings::objects).orElse(List.of()).stream() + .filter(placement -> placement.carvingSupport().supportsSurface()) + .toList(); + } + + /** The dimension's carving entry with this id (the last of several with one id); empty when it declares none. */ + Optional dimensionCarving(String id) { + CarvingEntry found = null; + for (CarvingEntry entry : dimensionCarving) { + if (entry != null && !entry.id().isBlank() && entry.id().trim().equals(id)) { + found = entry; + } + } + return Optional.ofNullable(found); + } + + /** The cave profile {@code biome} declares; null when it declares none. */ + CaveProfile caveProfile(ResourceId biome) { + return objects.biomeDeclaration(biome, CaveProfile.class).orElse(null); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index a5a38ed86..15dc2147e 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -19,190 +19,159 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.builtin.carve.CarvingSettings; -import art.arcane.iris.engine.object.placement.ObjectPlacements; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.IrisValues; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.terrain.carving.CaveProfiles; -import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; -import art.arcane.iris.engine.object.placement.IrisObjectPlacement; -import art.arcane.iris.engine.object.prefab.IrisObjectScale; +import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; -import art.arcane.iris.engine.object.value.IRare; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.util.project.noise.CNG; +import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.resource.ResourceId; import java.util.List; +import java.util.Optional; /** - * A {@link FloatingChildBiome} made ready for one engine: the noise its styles build (each from the world seed it is first - * asked with), the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. The - * settings class held these on itself; the engine now keeps one of these per decoded entry ({@link FloatingChildren}). + * A {@link FloatingChildBiome} made ready for one world: the noise its styles build (each from the world's floating seed), + * the edge taper profile, the biome it targets, the carving profile sampler and the objects it hosts. One per decoded entry + * ({@link FloatingWorld#resolve}). */ -public final class ResolvedFloatingChild implements IRare { - private final FloatingChildBiome settings; - private final IrisGeneratorStyle footprintStyle; - private final IrisGeneratorStyle edgeTaperVariationStyle; - private final IrisGeneratorStyle pickerStyle; - private final IrisGeneratorStyle altitudeStyle; - private final IrisGeneratorStyle topShapeStyle; - private final IrisGeneratorStyle bottomStyle; - private final IrisGeneratorStyle wallWarpStyle; - private final IrisGeneratorStyle carveStyle; - private final AtomicCache resolvedBiome = new AtomicCache<>(); - private final AtomicCache footprintCache = new AtomicCache<>(); - private final AtomicCache edgeTaperProfileCache = new AtomicCache<>(); - private final AtomicCache pickerCache = new AtomicCache<>(); - private final AtomicCache altitudeCache = new AtomicCache<>(); - private final AtomicCache topShapeCache = new AtomicCache<>(); - private final AtomicCache bottomCache = new AtomicCache<>(); - private final AtomicCache wallWarpCache = new AtomicCache<>(); - private final AtomicCache carveCache = new AtomicCache<>(); - private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); - private final AtomicCache shrinkScaleCache = new AtomicCache<>(); +public final class ResolvedFloatingChild { + private static final long FOOTPRINT_SALT = 0xF007B17DL; + private static final long EDGE_VARIATION_SALT = 0xED6E7A9E5L; + private static final long PICKER_SALT = 0x91C4E72DL; + private static final long ALTITUDE_SALT = 0xA17DEBBL; + private static final long TOP_SHAPE_SALT = 0x70970601DEFL; + private static final long BOTTOM_SALT = 0xB0770075CAFEL; + private static final long WALL_WARP_SALT = 0xA117BA17E0FL; + private static final long CARVE_SALT = 0xCA5EC1EE5EL; + private static final double MIN_SHRINK_FACTOR = 0.01; - public ResolvedFloatingChild(FloatingChildBiome settings) { + private final FloatingChildBiome settings; + private final FloatingWorld world; + private final AtomicCache> namedBiome = new AtomicCache<>(); + private final AtomicCache footprintCache = new AtomicCache<>(); + private final AtomicCache edgeTaperProfileCache = new AtomicCache<>(); + private final AtomicCache pickerCache = new AtomicCache<>(); + private final AtomicCache altitudeCache = new AtomicCache<>(); + private final AtomicCache topShapeCache = new AtomicCache<>(); + private final AtomicCache bottomCache = new AtomicCache<>(); + private final AtomicCache wallWarpCache = new AtomicCache<>(); + private final AtomicCache carveCache = new AtomicCache<>(); + private final AtomicCache carvingProfileSamplerCache = new AtomicCache<>(true); + + ResolvedFloatingChild(FloatingChildBiome settings, FloatingWorld world) { this.settings = settings; - this.footprintStyle = IrisValues.generatorStyle(settings.footprintStyle()); - this.edgeTaperVariationStyle = IrisValues.generatorStyle(settings.edgeTaperVariationStyle()); - this.pickerStyle = IrisValues.generatorStyle(settings.pickerStyle()); - this.altitudeStyle = IrisValues.generatorStyle(settings.altitudeStyle()); - this.topShapeStyle = IrisValues.generatorStyle(settings.topShapeStyle()); - this.bottomStyle = IrisValues.generatorStyle(settings.bottomStyle()); - this.wallWarpStyle = settings.wallWarpStyle().map(IrisValues::generatorStyle).orElse(null); - this.carveStyle = settings.carveStyle().map(IrisValues::generatorStyle).orElse(null); + this.world = world; } public FloatingChildBiome settings() { return settings; } - @Override - public int getRarity() { + public int rarity() { return settings.rarity(); } - public CNG getFootprintCng(long baseSeed, IrisData data) { - return footprintCache.aquire(() -> footprintStyle.create(new RNG(baseSeed ^ 0xF007B17DL), data)); + public NoiseSampler footprintNoise() { + return footprintCache.aquire(() -> noise(settings.footprintStyle(), FOOTPRINT_SALT)); } - public FloatingIslandEdgeProfile getEdgeTaperProfile(long baseSeed, IrisData data) { + public FloatingIslandEdgeProfile edgeTaperProfile() { return edgeTaperProfileCache.aquire(() -> { int width = FloatingIslandEdgeProfile.clampWidth(settings.edgeTaperWidth()); - double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude( - settings.edgeTaperVariationAmplitude(), width); - CNG variation = amplitude > 0.0D - ? edgeTaperVariationStyle.create(new RNG(baseSeed ^ 0xED6E7A9E5L), data) - : null; + double amplitude = FloatingIslandEdgeProfile.clampVariationAmplitude(settings.edgeTaperVariationAmplitude(), width); + NoiseSampler variation = amplitude > 0.0D ? noise(settings.edgeTaperVariationStyle(), EDGE_VARIATION_SALT) : null; return new FloatingIslandEdgeProfile(width, settings.edgeTaperExponent(), amplitude, variation); }); } - public CNG getPickerCng(long baseSeed, IrisData data) { - return pickerCache.aquire(() -> pickerStyle.create(new RNG(baseSeed ^ 0x91C4E72DL), data)); + public NoiseSampler pickerNoise() { + return pickerCache.aquire(() -> noise(settings.pickerStyle(), PICKER_SALT)); } - public CNG getAltitudeCng(long baseSeed, IrisData data) { - return altitudeCache.aquire(() -> altitudeStyle.create(new RNG(baseSeed ^ 0xA17DEBBL), data)); + public NoiseSampler altitudeNoise() { + return altitudeCache.aquire(() -> noise(settings.altitudeStyle(), ALTITUDE_SALT)); } - public CNG getTopShapeCng(long baseSeed, IrisData data) { - return topShapeCache.aquire(() -> topShapeStyle.create(new RNG(baseSeed ^ 0x70970601DEFL), data)); + public NoiseSampler topShapeNoise() { + return topShapeCache.aquire(() -> noise(settings.topShapeStyle(), TOP_SHAPE_SALT)); } - public CNG getBottomCng(long baseSeed, IrisData data) { - return bottomCache.aquire(() -> bottomStyle.create(new RNG(baseSeed ^ 0xB0770075CAFEL), data)); + public NoiseSampler bottomNoise() { + return bottomCache.aquire(() -> noise(settings.bottomStyle(), BOTTOM_SALT)); } - public CNG getWallWarpCng(long baseSeed, IrisData data) { - if (wallWarpStyle == null) { - return null; - } - return wallWarpCache.aquire(() -> wallWarpStyle.create(new RNG(baseSeed ^ 0xA117BA17E0FL), data)); + public NoiseSampler wallWarpNoise() { + Optional style = settings.wallWarpStyle(); + return style.isEmpty() ? null : wallWarpCache.aquire(() -> noise(style.get(), WALL_WARP_SALT)); } - public CNG getCarveCng(long baseSeed, IrisData data) { - if (carveStyle == null) { - return null; - } - return carveCache.aquire(() -> carveStyle.create(new RNG(baseSeed ^ 0xCA5EC1EE5EL), data)); + public NoiseSampler carveNoise() { + Optional style = settings.carveStyle(); + return style.isEmpty() ? null : carveCache.aquire(() -> noise(style.get(), CARVE_SALT)); } - public CaveProfileSampler getCarvingProfileSampler(Engine engine, IrisData data) { + private NoiseSampler noise(NoiseStyle style, long salt) { + return world.noise().sampler(style, world.baseSeed() ^ salt); + } + + public CaveProfileSampler carvingProfileSampler() { if (!hasCarvingReference()) { return null; } return carvingProfileSamplerCache.aquire(() -> { - IrisBiome resolved = resolveCarvingBiome(settings.carving(), engine, data); - CaveProfile profile = resolved == null ? null : CaveProfiles.declaredBy(resolved); + CaveProfile profile = carvingBiome().map(world::caveProfile).orElse(null); if (profile == null || !profile.enabled()) { return null; } - return new CaveProfileSampler(data.getPackResources().noise(), engine.getSeedManager().getCarve(), profile); + return new CaveProfileSampler(world.noise(), world.carveSeed(), profile); }); } public boolean hasCarvingReference() { + return !settings.carving().isBlank(); + } + + /** The biome whose cave profile carves the island: the biome of the dimension's carving entry the id names, or the biome the id names. */ + Optional carvingBiome() { String carving = settings.carving(); - return !carving.isBlank(); + Optional entry = world.dimensionCarving(carving); + if (entry.isEmpty()) { + return world.host().biome(carving); + } + String biomeKey = entry.get().biome().trim(); + return biomeKey.isEmpty() ? Optional.empty() : world.host().biome(biomeKey); } - static IrisBiome resolveCarvingBiome(String carving, Engine engine, IrisData data) { - if (carving == null || carving.isBlank() || engine == null || data == null) { - return null; - } - - CarvingEntry entry = dimensionCarvingEntry(carving, engine); - if (entry != null) { - String biomeKey = entry.biome().trim(); - return biomeKey.isEmpty() || data.getBiomeLoader() == null ? null : data.getBiomeLoader().load(biomeKey); - } - - if (data.getBiomeLoader() == null) { - return null; - } - - return data.getBiomeLoader().load(carving); + public KList resolveTopObjects(ResourceId target) { + List surface = settings.inheritObjects() && target != null ? FloatingWorld.surfaceObjects(world.objects(), target) : List.of(); + return topObjects(settings, surface); } - /** The dimension's carving entry with this id (the last of several with one id); null when it declares none. */ - private static CarvingEntry dimensionCarvingEntry(String id, Engine engine) { - CarvingEntry found = null; - for (CarvingEntry entry : engine.getDimension().getModuleSettings().find(CarvingSettings.class).map(CarvingSettings::entries).orElse(List.of())) { - if (entry != null && !entry.id().isBlank() && entry.id().trim().equals(id)) { - found = entry; - } - } - return found; - } - - public KList resolveTopObjects(IrisBiome target) { - KList surfaceObjects = (settings.inheritObjects() && target != null) ? ObjectPlacements.surface(target) : new KList<>(); - return resolveTopObjectsFromSurface(surfaceObjects); - } - - KList resolveTopObjectsFromSurface(KList surfaceObjects) { + /** The placements on the island's top: the inherited {@code surfaceObjects}, the child's overrides, or both, as its mode says. */ + public static KList topObjects(FloatingChildBiome settings, List surfaceObjects) { return switch (settings.topObjectMode()) { case REPLACE -> new KList<>(settings.topObjectOverrides()); case MERGE -> { - KList merged = new KList<>(); + KList merged = new KList<>(); merged.addAll(surfaceObjects); merged.addAll(settings.topObjectOverrides()); yield merged; } - case INHERIT_ONLY -> surfaceObjects; + case INHERIT_ONLY -> new KList<>(surfaceObjects); }; } - public KList resolveBottomObjects(IrisBiome target) { + public KList resolveBottomObjects() { + return bottomObjects(settings); + } + + /** The placements hung under the island: the child's overrides, unless its mode only inherits, which hangs nothing. */ + public static KList bottomObjects(FloatingChildBiome settings) { return switch (settings.bottomObjectMode()) { case INHERIT_ONLY -> new KList<>(); case MERGE, REPLACE -> new KList<>(settings.bottomObjectOverrides()); @@ -214,27 +183,16 @@ public final class ResolvedFloatingChild implements IRare { return shrink > 0 && shrink < 1.0; } - public IrisObjectScale getShrinkScale() { - return shrinkScaleCache.aquire(() -> { - IrisObjectScale s = new IrisObjectScale(); - s.setSize(Math.max(0.01, Math.min(1.0, settings.objectShrinkFactor()))); - return s; - }); + /** How much the island shrinks the objects it hosts. */ + public double shrinkFactor() { + return Math.max(MIN_SHRINK_FACTOR, Math.min(1.0, settings.objectShrinkFactor())); } - public IrisBiome getRealBiome(IrisBiome parent, IrisData data) { - return resolvedBiome.aquire(() -> { - String biome = settings.biome(); - if (biome.isBlank() || biome.equals(parent.getLoadKey())) { - return parent; - } - - IrisBiome loaded = data.getBiomeLoader().load(biome); - if (loaded == null) { - return parent; - } - - return loaded; - }); + /** The biome the island's palette, decorators and objects come from: the biome the child names, or {@code parent}. */ + public ResourceId realBiome(ResourceId parent) { + if (settings.biome().isBlank()) { + return parent; + } + return namedBiome.aquire(() -> world.host().biome(settings.biome())).orElse(parent); } } From c9058e0892a237842b4536e12528847349f0ecbc Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 13:03:42 +0200 Subject: [PATCH 090/139] Structures generate from the built-ins jar iris:structure moves into the jar as a thin module: it declares the structure placement settings and the mantle stage, and Iris places the structures through a StructureHost facade. The structure model, assembler, locator, fitting and placing stay host. The resource kinds become iris:structure-model/*, owned by Iris's own module. StructurePlacement names its structures with @Ref(Reference.PACK_STRUCTURE), so the exposed package names no host class. CaveProfiles had no users and is removed. --- builtin-modules.txt | 1 + .../iris/builtin/structure/StructureHost.java | 56 +++++++++++++++++++ .../builtin/structure/StructurePlacement.java | 7 +-- .../structure/StructureResources.java | 10 ++-- .../mantle/components/StructureModule.java | 50 +++-------------- .../object/terrain/carving/CaveProfiles.java | 33 ----------- 6 files changed, 73 insertions(+), 84 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructureHost.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java diff --git a/builtin-modules.txt b/builtin-modules.txt index 83c2e59b2..344628e87 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -91,3 +91,4 @@ include art/arcane/iris/engine/mantle/components/FloatingObjectPlacing*.class include art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver*.class include art/arcane/iris/engine/mantle/components/IslandFace*.class include art/arcane/iris/engine/mantle/components/UndersideTurn*.class +module art.arcane.iris.engine.mantle.components.StructureModule diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java new file mode 100644 index 000000000..3455b23f6 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java @@ -0,0 +1,56 @@ +/* + * 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.builtin.structure; + +import com.volmit.config.PackSettings; +import com.volmit.world.PackWorld; + +/** + * What {@code iris:structure} asks of Iris: Iris places its jigsaw structures itself. The structure model (structures, + * pools, pieces), the assembler that builds a structure from them and the locator that spreads them over the world are + * Iris's, shared with the jigsaw studio and the structure importers and exporters. Iris's worlds implement it; a module + * reaches it with {@link #of}. + */ +public interface StructureHost { + /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ + static StructureHost of(PackSettings settings) { + if (settings instanceof Source source) { + return source.structures(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); + } + + /** The host of {@code world}, which must be a world Iris generates. */ + static StructureHost of(PackWorld world) { + if (world instanceof Source source) { + return source.structures(); + } + throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); + } + + /** Places the structures that start in the chunk whose mantle this thread is generating. */ + void placeChunk(); + + /** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */ + int reach(); + + /** Iris's worlds answer for their structures. */ + interface Source { + StructureHost structures(); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java index 465b30ceb..1f8f7f5a4 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java @@ -18,14 +18,12 @@ package art.arcane.iris.builtin.structure; -import art.arcane.iris.engine.object.structure.IrisStructure; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; -import com.volmit.config.ResourceRef; import java.util.Collections; import java.util.List; @@ -34,13 +32,12 @@ import java.util.Optional; /** * Where and how often the structures of a dimension, region or biome start, written as one entry of its * {@code "structures": [...]}: the pack's own structures to assemble or the platform's to start natively, the - * distribution of the starts, the height they anchor at, and how they meet the terrain. IrisApi types only, besides - * the structure resource kind the {@code structures} keys name. + * distribution of the starts, the height they anchor at, and how they meet the terrain. IrisApi types only. */ @Desc("Attaches structures to a biome, region or dimension and controls where and how often they generate. This is independent of a structure's own native generation, so you can add custom placements in tandem with native generation or instead of it.") public final class StructurePlacement { @MinItems(1) - @ResourceRef(IrisStructure.class) + @Ref(Reference.PACK_STRUCTURE) @Desc("Editable Iris assembly resources offered by this placement. Leave empty when nativeStructures supplies the source.") private List structures = List.of(); 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 index 1ed3beebf..bb302a93a 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -30,7 +30,7 @@ import com.volmit.resource.ResourceKind; import java.util.List; /** - * The resource kinds of module {@code iris:structure}, which keep the folders and files Iris packs have always used, + * 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. @@ -40,16 +40,16 @@ import java.util.List; */ public final class StructureResources { /** Jigsaw structures, in {@code structures/}. */ - public static final ResourceKind STRUCTURES = ResourceKind.of("iris:structure/structure", "structures", IrisStructure.class); + 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/pool", "jigsaw-pools", IrisJigsawPool.class); + 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/piece", "jigsaw-pieces", IrisJigsawPiece.class); + public static final ResourceKind PIECES = ResourceKind.of("iris:structure-model/piece", "jigsaw-pieces", IrisJigsawPiece.class); private StructureResources() { } - /** Every resource kind of the structure module. */ + /** Every resource kind of the structure model. */ public static List> kinds() { return List.of(STRUCTURES, POOLS, PIECES); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 674340ffa..68eb8d1d5 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -19,47 +19,25 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.structure.StructureHost; import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureSettings; -import art.arcane.iris.core.modules.IrisMantleChunk; -import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.structure.StructureLocating; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.engine.framework.structure.StructureValidator; -import art.arcane.iris.engine.framework.structure.StructureVanillaStructures; import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; -import com.volmit.ModuleLog; import com.volmit.config.PackSettings; -import com.volmit.service.StructureLocator; -import com.volmit.service.VanillaStructures; import com.volmit.stage.MantleStageContext; import com.volmit.stage.StageGraph; /** - * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear - * where they intersect, and after floating objects. A port of what was Iris's structure mantle component, its - * work done by {@link StructurePlacing}, one per engine runtime. Its reach is the pack's largest structure. - *

- * The module owns the pack's structures, jigsaw pools and jigsaw pieces as resource kinds - * ({@link StructureResources}), read from the folders packs have always used, and checks them with - * {@link StructureValidator} wherever Iris validates a pack. It lets Iris find its structures through - * {@link StructureLocating}; a world's structure index lives in the world's state, so a reload of the pack's structure - * files, which starts a new world, builds it again. - *

- * It decides over the platform's own structures through its {@link VanillaStructures} provider - * ({@link StructureVanillaStructures}): the dimension's {@code importedStructures} settings disable, move, fit and set - * them up, and the pack's structure placements replace them, place them alongside, start them where their - * {@code nativeStructures} grids say and fit them into the terrain. The pack's structure placements are its - * {@code "structures"} settings ({@link StructurePlacementSettings}) of the dimension, its regions and biomes. + * Module {@code iris:structure}: the structure placements a pack declares, and the mantle stage that places the jigsaw + * structures starting in each chunk. Iris builds and places the structures ({@link StructureHost}); the structure + * resources, their validation, the locator and the platform structure answers are Iris's own module + * {@code iris:structure-model}. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; - private ModuleLog log; - @Override public ModuleInfo info() { return ModuleInfo.of("iris:structure", "Structures", VERSION); @@ -68,30 +46,20 @@ public final class StructureModule implements IrisModule { @Override public void install(StageGraph graph) { graph.define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE.ref(), IrisStages.Floating.OBJECTS.ref()) - .reach(this::reach).run(StructureModule::place); + .reach(StructureModule::reach).run(StructureModule::place); } @Override public void register(FeatureRegistry registry) { - log = registry.log(); registry.registerSettings(StructureSettings.class); registry.registerSettings(StructurePlacementSettings.class); - StructureResources.kinds().forEach(registry::registerResourceKind); - registry.registerValidator(new StructureValidator()); - registry.registerService(StructureLocator.class, new StructureLocating()); - registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); } private static void place(MantleStageContext context) { - IrisMantleChunk chunk = IrisMantleChunk.current(); - placing(chunk.engine(), context.log()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + StructureHost.of(context.world()).placeChunk(); } - private int reach(PackSettings settings) { - return placing(IrisPackSettings.of(settings).engine(), log).reach(); - } - - private static StructurePlacing placing(Engine engine, ModuleLog log) { - return engine.getGeneration().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log)); + private static int reach(PackSettings settings) { + return StructureHost.of(settings).reach(); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java deleted file mode 100644 index 55628bb16..000000000 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfiles.java +++ /dev/null @@ -1,33 +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.terrain.carving; - -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.core.loader.IrisRegistrant; - -/** The cave profiles dimensions, regions and biomes declare ({@code caveProfile}). */ -public final class CaveProfiles { - private CaveProfiles() { - } - - /** The profile {@code owner}, a dimension, region or biome, declares; null when it declares none, which is as good as one that is not enabled. */ - public static CaveProfile declaredBy(IrisRegistrant owner) { - return owner.getModuleSettings().find(CaveProfile.class).orElse(null); - } -} From bd7c1a226a1259e4e7d55990ef08b92cfb2ee3fe Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 15 Oct 2026 13:11:49 +0200 Subject: [PATCH 091/139] README: structure model is Iris's, iris:floating and iris:structure ship in the jar --- README.md | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8b46e8ea4..a48b7b5c9 100644 --- a/README.md +++ b/README.md @@ -26,18 +26,22 @@ service or hook, `registry.log()` while registering), which labels each line wit use `IrisLogging`. Classes of the host's object model (the host-classes list) and code that only has an engine or pack data still log as Iris itself. -Built-in modules also own pack resources and checks of their own. `iris:structure` reads structures, jigsaw -pools and jigsaw pieces as resource kinds (`StructureResources`), from the folders and files packs have always -used, and checks them with its validator (`StructureValidator`: assembly samples and vanilla structure -replacement) wherever Iris validates a pack; Iris core has no loader or validator of its own for them any more. +Modules also own pack resources and checks of their own. Iris's own module `iris:structure-model` (core +`StructureModelModule`) reads structures, jigsaw pools and jigsaw pieces as resource kinds (`StructureResources`, +`iris:structure-model/structure`, `/pool`, `/piece`), from the folders and files packs have always used, and checks +them with its validator (`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris +validates a pack. The structure model, assembler, locator, fitting and placing are host: the jigsaw studio, the +structure importers and exporters read them too. `iris:structure` in the built-ins jar declares the structure +placement settings and the mantle stage, and places through the `StructureHost` facade +(`art.arcane.iris.builtin.structure`). Built-in modules answer Iris through IrisApi services instead of Iris reading their features: `iris:objects` -provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure` +provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure-model` provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a world places, and their nearest start for the find commands). A world's structure index lives in the world's state (`engine.getGeneration().state(...)`), so every reload of the pack's structure files, which starts a new world, builds it again. -`iris:structure` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: +`iris:structure-model` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: which ones its placements replace or the dimension's `importedStructures` disables, the starts its `nativeStructures` placements make (`startedStructures`, `locatableStarts`, `locateStart`), the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, PRESERVE, VACUUM, ENCASE, BORE, FORCE_CARVE, stilts) in `engine/framework/structure/fit`, written against IrisApi's @@ -125,6 +129,10 @@ workers: `ResolvedOre`/`ResolvedOres` (blocks and chance noise per world, `Terra (`carvingBiome`, a band's biome, a floating child's target and carving) implement `LinkedBiomes`, which is how Iris's biome tree and the biomes a dimension reaches learn of them without reading the settings classes; and `iris:carve` provides the `CaveBiomes` service (`CaveBiomeBands`), which Iris asks for the dimension's carving band at a position and for a biome's minimum cave depth. +`iris:floating` ships in the built-ins jar: `FloatingWorld` holds a world's floating children, noise and seeds, and what a jar +cannot do Iris does through `FloatingHost` (`art.arcane.iris.builtin.floating`): the surface biome of a column, a biome's +height for the `BIOME` top shape, painting the sky biome, an object's footprint and shrinking, and placing an object +floating, on an island's top or hung under it, where the jar's `IslandAnchor` says where the island face is. Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` (biome; a list), `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest) and `structures` From 74d83b5be156d8850df251a91390e3080dca69af Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 19 Oct 2026 15:29:32 +0200 Subject: [PATCH 092/139] Loot validation names why a table cannot be read The validator reports the load's reason (such as a field of the wrong type) instead of pointing at the log. --- src/main/java/art/arcane/iris/engine/loot/LootValidator.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java index bebef35dd..1ffb66a50 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -41,7 +41,7 @@ import java.util.function.BiFunction; /** * Module {@code iris:loot}'s check of a pack: every loot table has sane picks, tries and entries, and every loot * reference of a dimension, region or biome names a table the pack has. It checks the tables and settings as they - * decoded; a file that is not valid JSON, or holds a value of the wrong type, is reported by the load that reads it. + * decoded; a file that is not valid JSON, or holds a value of the wrong type, fails to load, and the check reports why. */ public final class LootValidator implements Validator { private static final String JSON_EXTENSION = ".json"; @@ -95,7 +95,7 @@ public final class LootValidator implements Validator { try { return resources.find(LootResources.TABLES.key(id)).orElse(null); } catch (IllegalStateException failedToLoad) { - errors.add("Loot table '" + key + "' cannot be read; the log says what is wrong with the file."); + errors.add("Loot table '" + key + "' cannot be read: " + failedToLoad.getMessage()); return null; } } From f06908a20f1e2512d3e64a5ab07c473bf863467e Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 19 Oct 2026 15:29:32 +0200 Subject: [PATCH 093/139] Placement stages register the held types Iris's IrisObjectPlacement holds iris:prepare (slope clip, rotation clamp), iris:validate (limit), iris:stilt, iris:vacuum and iris:blocks (replace) describe their own classes; the host module iris:placement-settings is no longer needed. --- README.md | 9 +++++---- .../iris/engine/object/placement/BlocksModule.java | 7 +++++++ .../iris/engine/object/placement/PrepareModule.java | 8 ++++++++ .../arcane/iris/engine/object/placement/StiltModule.java | 6 ++++++ .../iris/engine/object/placement/VacuumModule.java | 6 ++++++ .../iris/engine/object/placement/ValidateModule.java | 7 +++++++ 6 files changed, 39 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a48b7b5c9..be4f41b16 100644 --- a/README.md +++ b/README.md @@ -89,10 +89,11 @@ with a random of its own; they used to spread over threads on a multicore pregen Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, -`.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). A module compiled into Iris registers each with -`registry.registerHeldType(...)` so studio describes it from the module's own annotations; only such a module may, so the classes -Iris's `IrisObjectPlacement` holds are described by the host module `iris:placement-settings` (the placement stages ship in the -built-ins jar). Packs write the same JSON as before. Behaviour +`.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). A module registers each with +`registry.registerHeldType(...)` so studio describes it from the module's own annotations. A module in the built-ins jar may +too, because the classes are in the exposed package: the placement stages register what Iris's `IrisObjectPlacement` holds +(`iris:prepare` its slope clip and rotation clamp, `iris:validate` its limit, `iris:stilt`, `iris:vacuum`, `iris:blocks` its +replace). Packs write the same JSON as before. Behaviour that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`). diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 11c465e23..83334df33 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -21,6 +21,7 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.blocks.ObjectMarkers; +import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.placement.MarkerRule; @@ -32,6 +33,7 @@ import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; @@ -88,6 +90,11 @@ public final class BlocksModule implements IrisModule { }); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(ObjectReplace.class); + } + private static void write(BlockStageContext context, WrittenBlocks written) { ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 470a2c539..96612eedb 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -31,9 +31,11 @@ import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectSpinKernel; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.stage.PlacementStageContext; @@ -66,6 +68,12 @@ public final class PrepareModule implements IrisModule { .produce(PrepareModule::transforms); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(SlopeClip.class); + registry.registerHeldType(AxisRotationClamp.class); + } + private static ObjectRotation slope(PlacementStageContext context) { ObjectPlacement placement = ObjectPlacement.current(); PlacementSettings settings = placement.settings(); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 6293d6176..3460a911a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -26,6 +26,7 @@ import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.stilt.StiltLayers; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.volmlib.util.math.RNG; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; @@ -80,6 +81,11 @@ public final class StiltModule implements IrisModule { .run(StiltModule::fill); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(StiltSettings.class); + } + private static void collectLayer(BlockStageContext context, StiltLayers layers) { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); if (prepared.mode().stilt() == StiltShape.NONE) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index aaca1167a..97aa32856 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -27,6 +27,7 @@ import art.arcane.iris.builtin.placement.PlaneNoise; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.iris.builtin.vacuum.VacuumSettings; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; @@ -61,6 +62,11 @@ public final class VacuumModule implements IrisModule { .run(VacuumModule::bendTerrain); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(VacuumSettings.class); + } + private static void bendTerrain(PlacementStageContext context) { PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 1940731b9..72c320aec 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -28,6 +28,8 @@ import art.arcane.iris.builtin.placement.PlacementSettings; import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.StructureVolumes; import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.validate.ObjectLimit; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; @@ -72,6 +74,11 @@ public final class ValidateModule implements IrisModule { .run(ValidateModule::checkCollisions); } + @Override + public void register(FeatureRegistry registry) { + registry.registerHeldType(ObjectLimit.class); + } + private static void checkSurface(PlacementStageContext context) { ObjectPlacement placement = ObjectPlacement.current(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); From 242ca3e323fc3be8997be30f60bddc0e4369bcd7 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 22 Oct 2026 09:45:37 +0200 Subject: [PATCH 094/139] Iris packages and bundles the built-ins jar; this build copies it The built-ins jar is now packaged and checked by Iris's :core:builtinModulesJar from core's own compiled classes and bundled into the plugin, so it always fits the Iris it ships with. builtinModulesJar here runs that task and copies the jar to build/libs; the packaging, entry file and check tasks moved to Iris, with the VolmLib include build they needed. SurfaceFitting (structure fitting, still Iris's) has its own outset instead of calling IrisObjectVacuum, which lives in the jar only: the plugin no longer carries the jar's classes outside the jar. --- README.md | 30 +++-- build.gradle.kts | 125 ++---------------- settings.gradle.kts | 7 - .../structure/fit/SurfaceFitting.java | 16 ++- 4 files changed, 38 insertions(+), 140 deletions(-) diff --git a/README.md b/README.md index be4f41b16..163a9ce1a 100644 --- a/README.md +++ b/README.md @@ -160,16 +160,19 @@ archive. The host project also provides `:core:defaultModuleSourcesJar` for the ## Built-in modules as a pack module jar -`./gradlew builtinModulesJar` builds `build/libs/iris-builtins.jar`, the built-in modules as an ordinary pack -module jar for a pack's `modules/` folder. `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 classes come from Iris core's compiled output, which the task builds first. -Before the jar lands in `build/libs`, `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. +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's own +`modules/iris-builtins.jar`, such as an old copy, is left out, and Iris warns once with its path. `./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 +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. 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 @@ -179,10 +182,9 @@ mantle's planned blocks; the placement stages read the placement being run throu spawn services, which have no chunk to ask, ask `LiveWorld` (both below). Without the jar a pack's world has no caves, vanilla placed features, loot, block drops, entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and `effects` are not read. -Iris no longer compiles them in (`IrisModuleHost.generationModules()`), so a pack gets them by putting -`iris-builtins.jar` into its `modules` folder; the built-ins that order after their stages (`iris:floating`, -`iris:objects`, `iris:decorant`, `iris:custom`) only order, so a pack without the jar still loads. Iris warns once per pack folder -when a pack loads none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to +Iris no longer compiles them in (`IrisModuleHost.generationModules()`); every pack gets them from the bundled jar. A pack +still loads without them, as with an Iris build that bundles no jar, and Iris warns once per pack folder when a pack loads +none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps equal to `builtin-modules.txt`): add a module to the jar and to that list together. `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of diff --git a/build.gradle.kts b/build.gradle.kts index daafabe83..634021283 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,5 +1,4 @@ import org.gradle.jvm.tasks.Jar -import java.io.ByteArrayOutputStream plugins { base @@ -35,129 +34,23 @@ val checkBuiltins = tasks.register("checkBuiltins") { ) } -// The built-ins as a pack module jar, to put into a pack's modules/ folder. What goes in is listed in builtin-modules.txt. - -/** What [builtinModulesFile] lists: module classes (the jar's entry points) and further class patterns. */ -data class BuiltinModuleList(val moduleClasses: List, val classPatterns: List) { - /** Ant patterns, relative to the class root, of every class the jar takes from Iris's compiled classes. */ - fun packagedClassPatterns(): List = - moduleClasses.flatMap { listOf(it.replace('.', '/') + ".class", it.replace('.', '/') + "$*.class") } + classPatterns -} - -fun readBuiltinModuleList(file: File): BuiltinModuleList { - val moduleClasses = mutableListOf() - val classPatterns = mutableListOf() - file.readLines().map { it.substringBefore('#').trim() }.filter { it.isNotEmpty() }.forEach { line -> - val (keyword, value) = line.split(Regex("\\s+"), limit = 2).let { it[0] to it.getOrElse(1) { "" }.trim() } - require(value.isNotEmpty()) { "${file.name}: '$line' needs a value after '$keyword'" } - when (keyword) { - "module" -> moduleClasses += value - "include" -> classPatterns += value - else -> throw GradleException("${file.name}: unknown line '$line'; start it with 'module' or 'include'") - } - } - return BuiltinModuleList(moduleClasses, classPatterns) -} - -val builtinModulesFile = layout.projectDirectory.file("builtin-modules.txt").asFile -val builtinModuleList = readBuiltinModuleList(builtinModulesFile) +// 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. val builtinModulesJarName = "iris-builtins.jar" -val builtinModuleEntryFile = "com.volmit.IrisModule" -/** - * Host packages pack modules may use besides the IrisApi: the built-in module API, VolmLib and Gson. Keep in step with - * IrisModuleHost.EXPOSED_PACKAGES in Iris. - */ -val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.volmlib", "com.google.gson") -val irisClasses = irisRoot.resolve("core/build/classes/java/main") -/** The VolmLib classes Iris's Bukkit jar strips; Iris's shadowJar reads the same file. A module may not use them. */ -val volmLibLeftOutFile = irisRoot.resolve("core/volmlib-left-out-of-bukkit-jar.txt") -val builtinModulesBuild = layout.buildDirectory.dir("builtin-modules") -val checkedJarsDirectory = layout.buildDirectory.dir("libs") - -repositories { - mavenCentral() -} - -/** What the jar check sees besides Iris's classes: the IrisApi and the libraries Iris shares with pack modules. */ -val irisApiForChecks by configurations.creating { - isCanBeConsumed = false - isTransitive = false - attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_RUNTIME)) -} - -dependencies { - irisApiForChecks("com.volmit:IrisApi") - irisApiForChecks("com.github.VolmitSoftware:VolmLib") - // The Gson Iris compiles against (Iris/gradle/libs.versions.toml); at runtime modules get the platform's copy. - irisApiForChecks("com.google.code.gson:gson:2.14.0") -} - -val compileBuiltins = tasks.register("compileBuiltins") { - description = "Compiles Iris core together with the built-in sources, which is where the jar's classes come from." +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:compileJava", "-PincludeModdedAdapters=false", "--console=plain") + offline) -} - -val writeBuiltinModuleEntries = tasks.register("writeBuiltinModuleEntries") { - description = "Writes the 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 { - entries.get().asFile.apply { parentFile.mkdirs() }.writeText(builtinModuleList.moduleClasses.joinToString("\n", postfix = "\n")) - } -} - -val packageBuiltinModules = tasks.register("packageBuiltinModules") { - description = "Packages the listed built-in modules and classes before they are checked." - dependsOn(compileBuiltins) - archiveFileName.set(builtinModulesJarName) - destinationDirectory.set(builtinModulesBuild.map { it.dir("unchecked") }) - inputs.file(builtinModulesFile) - val patterns = builtinModuleList.packagedClassPatterns() - // An empty include list would take every class of Iris. - if (patterns.isNotEmpty()) { - from(irisClasses) { include(patterns) } - from(writeBuiltinModuleEntries) { into("META-INF/services") } - } -} - -val checkBuiltinModulesJar = tasks.register("checkBuiltinModulesJar") { - description = "Runs IrisApi's pack class and reference checks on the packaged jar, as a pack load would." - dependsOn(packageBuiltinModules) - // A jar without module entries is not a loadable pack module; there is nothing to check until a module is listed. - onlyIf { builtinModuleList.moduleClasses.isNotEmpty() } - val packaged = packageBuiltinModules.flatMap { it.archiveFile } - classpath = irisApiForChecks + files(irisClasses) - mainClass.set("com.volmit.host.ModuleJarCheck") - javaLauncher.set(javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(25)) }) - inputs.file(volmLibLeftOutFile) - argumentProviders.add(CommandLineArgumentProvider { - listOf(packaged.get().asFile.absolutePath, "--left-out=${volmLibLeftOutFile.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. - checkedJarsDirectory.get().file(builtinModulesJarName).asFile.delete() - } - doLast { - if (executionResult.get().exitValue == 0) return@doLast - 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.") - } + commandLine(listOf("./gradlew", ":core:builtinModulesJar", "-PincludeModdedAdapters=false", "--console=plain") + offline) } tasks.register("builtinModulesJar") { group = "build" - description = "Builds build/libs/$builtinModulesJarName, the built-in modules as a pack module jar for a pack's modules/ folder." - dependsOn(checkBuiltinModulesJar) - from(packageBuiltinModules.flatMap { it.archiveFile }) - into(checkedJarsDirectory) + 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")) } tasks.named("check") { diff --git a/settings.gradle.kts b/settings.gradle.kts index 841797c9e..a480323b7 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -2,10 +2,3 @@ rootProject.name = "IrisModule" // Keep the public API discoverable when importing the default module. includeBuild("../IrisApi") - -// The built-ins jar check sees the libraries Iris shares with pack modules; VolmLib comes from the sibling checkout, as for Iris. -includeBuild("../VolmLib") { - dependencySubstitution { - substitute(module("com.github.VolmitSoftware:VolmLib")).using(project(":shared")) - } -} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java index 504a2cc20..9d773383d 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.framework.structure.fit; import art.arcane.iris.builtin.structure.StructureTerrainMode; -import art.arcane.iris.engine.object.placement.IrisObjectVacuum; import com.volmit.ModuleLog; import com.volmit.block.BlockState; import com.volmit.vanilla.DecorationStep; @@ -123,6 +122,17 @@ final class SurfaceFitting { return resolveSurface(anchors, worldX, worldZ, originalY).targetY(); } + /** How far {@code value} lies outside {@code [low, high]}; 0 inside. Iris's vacuum measures footprints the same way. */ + private static int outset(int value, int low, int high) { + if (value < low) { + return low - value; + } + if (value > high) { + return value - high; + } + return 0; + } + private static SurfaceResolution resolveSurface(List anchors, int worldX, int worldZ, int originalY) { int localTargetY = originalY; SurfaceAnchor selectedLocal = null; @@ -130,8 +140,8 @@ final class SurfaceFitting { long weightedTargetY = 0L; long maximumInfluence = 0L; for (SurfaceAnchor anchor : anchors) { - int outX = IrisObjectVacuum.outset(worldX, anchor.minX(), anchor.maxX()); - int outZ = IrisObjectVacuum.outset(worldZ, anchor.minZ(), anchor.maxZ()); + int outX = outset(worldX, anchor.minX(), anchor.maxX()); + int outZ = outset(worldZ, anchor.minZ(), anchor.maxZ()); boolean containsColumn = outX == 0 && outZ == 0; long distanceSquared = (long) outX * outX + (long) outZ * outZ; long radiusSquared = (long) SURFACE_TERRAIN_RADIUS * SURFACE_TERRAIN_RADIUS; From 06617d640b9917204d44880fe2a502e65951d764 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 22 Oct 2026 09:59:51 +0200 Subject: [PATCH 095/139] README: a pack must not hold its own copy of the bundled built-ins jar --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 163a9ce1a..f69401dbe 100644 --- a/README.md +++ b/README.md @@ -162,8 +162,8 @@ archive. The host project also provides `:core:defaultModuleSourcesJar` for the 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's own -`modules/iris-builtins.jar`, such as an old copy, is left out, and Iris warns once with its path. `./gradlew builtinModulesJar` +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 From c3d175d8dea50643576b0a34c8bdf3d256c24fbc Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 23 Oct 2026 13:00:11 +0200 Subject: [PATCH 096/139] Move the built-in modules to IrisModule.setup Every built-in module now sets up in one setup(ModuleSetup) body. Soft edges take the stage constants, conditioned stages read their settings through context.configured, mantle stages are the non-generic MantleStage, and the slope and anchor producers return null once they reject. --- README.md | 2 +- .../art/arcane/iris/builtin/IrisStages.java | 8 ++++---- .../iris/engine/actuator/DecorantModule.java | 14 +++++--------- .../iris/engine/actuator/TerrainModule.java | 12 ++++-------- .../vanillafeatures/VanillaFeaturesModule.java | 10 +++------- .../arcane/iris/engine/loot/LootModule.java | 10 +++------- .../engine/mantle/components/ObjectModule.java | 14 +++++--------- .../mantle/components/StructureModule.java | 12 ++++-------- .../iris/engine/modifier/CarveModule.java | 10 ++++------ .../iris/engine/modifier/DepositModule.java | 16 ++++++---------- .../iris/engine/modifier/FloatingModule.java | 18 ++++++++---------- .../iris/engine/modifier/MatterModule.java | 8 ++++---- .../iris/engine/modifier/PerfectionModule.java | 6 +++--- .../iris/engine/modifier/PostModule.java | 12 ++++-------- .../engine/object/placement/AnchorModule.java | 8 +++++--- .../engine/object/placement/BlocksModule.java | 12 ++++-------- .../engine/object/placement/BoreModule.java | 6 +++--- .../engine/object/placement/PrepareModule.java | 13 +++++-------- .../engine/object/placement/SnowModule.java | 8 ++++---- .../engine/object/placement/StiltModule.java | 14 +++++--------- .../engine/object/placement/VacuumModule.java | 13 ++++--------- .../object/placement/ValidateModule.java | 12 ++++-------- .../arcane/iris/engine/spawn/SpawnModule.java | 10 +++------- 23 files changed, 95 insertions(+), 153 deletions(-) diff --git a/README.md b/README.md index f69401dbe..23208e07f 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ core (`art.arcane.iris.core.modules.BiomeModule` and `CustomModule`) and Iris re the built-ins jar. Their stage constants stay in `art.arcane.iris.builtin.IrisStages`, so packs can still order after them. Built-in modules log through the `ModuleLog` IrisApi hands them (`context.log()` in a stage body, `world.log()` in a -service or hook, `registry.log()` while registering), which labels each line with the module's id, so these sources do not +service or hook, `setup.log()` during setup), which labels each line with the module's id, so these sources do not use `IrisLogging`. Classes of the host's object model (the host-classes list) and code that only has an engine or pack data still log as Iris itself. diff --git a/src/main/java/art/arcane/iris/builtin/IrisStages.java b/src/main/java/art/arcane/iris/builtin/IrisStages.java index 180132bc0..16810ab3f 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisStages.java +++ b/src/main/java/art/arcane/iris/builtin/IrisStages.java @@ -126,7 +126,7 @@ public final class IrisStages { /** Module {@code iris:carve}: caves, planned in the mantle and cut into each chunk's terrain. */ public static final class Carve { /** Plans the caves of the dimension's cave profiles into the mantle, one block into each neighbor. */ - public static final MantleStage CAVES = Stage.mantle("iris:carve/caves"); + public static final MantleStage CAVES = Stage.mantle("iris:carve/caves"); /** Cuts the planned caves out of the chunk's terrain and decorates their floors and ceilings. */ public static final ChunkStage APPLY = Stage.chunk("iris:carve/apply"); @@ -137,7 +137,7 @@ public final class IrisStages { /** Module {@code iris:objects}: the objects the dimension's regions and biomes place. */ public static final class Objects { /** Places surface, cave and upper-dimension objects into the mantle, after the caves they anchor in. */ - public static final MantleStage PLACE = Stage.mantle("iris:objects/place"); + public static final MantleStage PLACE = Stage.mantle("iris:objects/place"); private Objects() { } @@ -146,7 +146,7 @@ public final class IrisStages { /** Module {@code iris:floating}: the floating islands of floating child biomes. */ public static final class Floating { /** Places the objects on and under the islands into the mantle, after the dimension's other objects. */ - public static final MantleStage OBJECTS = Stage.mantle("iris:floating/objects"); + public static final MantleStage OBJECTS = Stage.mantle("iris:floating/objects"); /** Writes the islands' solid blocks. */ public static final ChunkStage SOLIDS = Stage.chunk("iris:floating/solids"); /** Decorates the islands' tops and bottoms once the chunk's own decoration is done. */ @@ -159,7 +159,7 @@ public final class IrisStages { /** Module {@code iris:structure}: Iris structures, assembled from pieces. */ public static final class Structure { /** Places the structures of the dimension, its regions and biomes into the mantle, after objects and floating objects. */ - public static final MantleStage PLACE = Stage.mantle("iris:structure/place"); + public static final MantleStage PLACE = Stage.mantle("iris:structure/place"); private Structure() { } diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 9c5499e39..94d02d58d 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -28,15 +28,14 @@ import art.arcane.iris.engine.decorator.IrisSeaFloorDecorator; import art.arcane.iris.engine.decorator.IrisSeaSurfaceDecorator; import art.arcane.iris.engine.decorator.IrisShoreLineDecorator; import art.arcane.iris.engine.decorator.IrisSurfaceDecorator; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.config.FeatureSettings; import com.volmit.hunk.Hunk; import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.BiomeKind; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; @@ -56,7 +55,10 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { } @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + // Ordering only: iris:matter ships in the built-ins jar, which a pack may not have. + setup.stages().define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT).run(DecorantModule::decorate); + var registry = setup.registry(); registry.registerSettings(DecorantSettings.class); registry.registerSettings(DecorateSettings.class); registry.registerLifecycle(this); @@ -67,12 +69,6 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { BiomeDecorators.of(world).warm(); } - @Override - public void install(StageGraph graph) { - // Ordering only: iris:matter ships in the built-ins jar, which a pack may not have. - graph.define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT.ref()).run(DecorantModule::decorate); - } - private static void decorate(ChunkStageContext context) { if (!decorates(context)) { return; diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 3ddcba9e3..6ddada286 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -32,12 +32,11 @@ import art.arcane.iris.builtin.terrain.RockPaletteSettings; import art.arcane.iris.builtin.terrain.SeaLayersSettings; import art.arcane.iris.builtin.terrain.SlabSettings; import art.arcane.iris.builtin.terrain.WallSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; +import com.volmit.ModuleSetup; import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.PackWorld; import art.arcane.iris.builtin.terrain.TerrainPalettes; @@ -57,7 +56,9 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { } @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); + var registry = setup.registry(); registry.registerSettings(LayersSettings.class); registry.registerSettings(SeaLayersSettings.class); registry.registerSettings(CaveCeilingLayersSettings.class); @@ -81,11 +82,6 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { new OreWarmUp(world).warm(); } - @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); - } - private static void shape(ChunkStageContext context) { TerrainShaper.of(context.world()).shape(context); } diff --git a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java index 035b15463..3e14713d5 100644 --- a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java +++ b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java @@ -19,11 +19,10 @@ package art.arcane.iris.engine.framework.vanillafeatures; import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.service.VanillaFeatures; -import com.volmit.stage.StageGraph; /** * Module {@code iris:vanilla-features}: whether the platform's own placed features (ores, trees, plants, springs) run @@ -40,11 +39,8 @@ public final class VanillaFeaturesModule implements IrisModule { } @Override - public void install(StageGraph graph) { - } - - @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + var registry = setup.registry(); registry.registerSettings(ImportedFeaturesSettings.class); registry.registerService(VanillaFeatures.class, new ImportedFeatures()); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index d3e2696e3..0c0106b67 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -22,12 +22,11 @@ import art.arcane.iris.builtin.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.builtin.loot.ObjectLoot; import art.arcane.iris.builtin.loot.ObjectVanillaLoot; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.service.BlockDrops; import com.volmit.service.Loot; -import com.volmit.stage.StageGraph; /** * Module {@code iris:loot}: the loot tables of the pack ({@link LootResources}), the {@link LootSettings} and @@ -44,11 +43,8 @@ public final class LootModule implements IrisModule { } @Override - public void install(StageGraph graph) { - } - - @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + var registry = setup.registry(); registry.registerSettings(LootSettings.class); registry.registerSettings(BlockDropSettings.class); registry.registerHeldType(ObjectLoot.class); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index d4d093c6d..7973b7990 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -27,16 +27,15 @@ 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 com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; import com.volmit.config.PackSettings; import com.volmit.service.ObjectsAt; import com.volmit.service.SaplingGrowth; import com.volmit.stage.MantleStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.PackWorld; /** @@ -58,14 +57,11 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { } @Override - public void install(StageGraph graph) { + public void setup(ModuleSetup setup) { + log = setup.log(); // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. - graph.define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES.ref()).reach(this::reach).run(ObjectModule::place); - } - - @Override - public void register(FeatureRegistry registry) { - log = registry.log(); + setup.stages().define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES).reach(this::reach).run(ObjectModule::place); + var registry = setup.registry(); registry.registerService(ObjectsAt.class, new ObjectLocating()); registry.registerService(SaplingGrowth.class, new TreeGrowing()); registry.registerSettings(ObjectSettings.class); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 68eb8d1d5..f4ea4f6b2 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -22,12 +22,11 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.structure.StructureHost; import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.config.PackSettings; import com.volmit.stage.MantleStageContext; -import com.volmit.stage.StageGraph; /** * Module {@code iris:structure}: the structure placements a pack declares, and the mantle stage that places the jigsaw @@ -44,13 +43,10 @@ public final class StructureModule implements IrisModule { } @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE.ref(), IrisStages.Floating.OBJECTS.ref()) + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE, IrisStages.Floating.OBJECTS) .reach(StructureModule::reach).run(StructureModule::place); - } - - @Override - public void register(FeatureRegistry registry) { + var registry = setup.registry(); registry.registerSettings(StructureSettings.class); registry.registerSettings(StructurePlacementSettings.class); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index eddf4d1a4..2c23616e0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -31,10 +31,10 @@ import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings; import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.iris.engine.mantle.components.CaveCarving; -import com.volmit.FeatureRegistry; import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.config.FeatureSettings; import com.volmit.config.FeatureSettings.Entry; import com.volmit.FeatureAttachment.Target; @@ -45,7 +45,6 @@ import com.volmit.block.BlockTrait; import com.volmit.service.CaveBiomes; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; @@ -72,7 +71,8 @@ public final class CarveModule implements IrisModule { } @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + var registry = setup.registry(); registry.registerSettings(CaveProfile.class); registry.registerSettings(CarvingSettings.class); registry.registerSettings(CarvingEnabledSettings.class); @@ -81,10 +81,8 @@ public final class CarveModule implements IrisModule { registry.registerSettings(CaveLavaHeightSettings.class); registry.registerSettings(UpperDimensionCarvingSettings.class); registry.registerService(CaveBiomes.class, new CaveBiomeBands()); - } - @Override - public void install(StageGraph graph) { + var graph = setup.stages(); graph.define(IrisStages.Carve.CAVES).reach(CAVE_REACH_BLOCKS).run(CarveModule::planCaves); graph.define(IrisStages.Carve.APPLY).requires(IrisStages.Terrain.SHAPE).run(CarveModule::applyCaves); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index 64b521cf8..d10806271 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -24,13 +24,11 @@ import art.arcane.iris.builtin.deposit.DepositSettings; import art.arcane.iris.builtin.deposit.DepositVariantSettings; import art.arcane.iris.builtin.deposit.OreFrequencySettings; import art.arcane.iris.builtin.deposit.OreSizeSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; import java.util.List; @@ -51,22 +49,20 @@ public final class DepositModule implements IrisModule { } @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + var registry = setup.registry(); registry.registerSettings(DepositVariantSettings.class); registry.registerSettings(OreFrequencySettings.class); registry.registerSettings(OreSizeSettings.class); - } - @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Deposit.ORES) + setup.stages().define(IrisStages.Deposit.ORES) .when(DepositSettings.class) .requires(IrisStages.Terrain.SHAPE) - .softAfter(IrisStages.Floating.SOLIDS.ref()) + .softAfter(IrisStages.Floating.SOLIDS) .run(DepositModule::place); } - private static void place(ChunkStageContext context, List> inChunk) { + private static void place(ChunkStageContext context) { List generators = generatorsAtCentre(context.settings(), context.originX(), context.originZ()); if (generators.isEmpty()) { return; diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 7a2fd6cbf..d9d3e7953 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -22,14 +22,13 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; import com.volmit.config.PackSettings; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.MantleStageContext; -import com.volmit.stage.StageGraph; /** * Module {@code iris:floating}: the islands of floating child biomes, their objects in the mantle after the @@ -48,20 +47,19 @@ public final class FloatingModule implements IrisModule { } @Override - public void register(FeatureRegistry registry) { - log = registry.log(); + public void setup(ModuleSetup setup) { + log = setup.log(); + var registry = setup.registry(); registry.registerSettings(FloatingChildSettings.class); registry.registerSettings(MergeFloatingChildrenSettings.class); - } - @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE.ref()).reach(this::objectReach) + var graph = setup.stages(); + graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE).reach(this::objectReach) .run(FloatingModule::objects); // Ordering only: iris:post ships in the built-ins jar, which a pack may not have. - graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH.ref()).run(FloatingModule::solids); + graph.define(IrisStages.Floating.SOLIDS).softAfter(IrisStages.Post.SMOOTH).run(FloatingModule::solids); // Ordering only: iris:decorant ships in the built-ins jar, which a pack may not have. - graph.define(IrisStages.Floating.DECORATE).softAfter(IrisStages.Decorant.DECORATE.ref()).run(FloatingModule::decorate); + graph.define(IrisStages.Floating.DECORATE).softAfter(IrisStages.Decorant.DECORATE).run(FloatingModule::decorate); } private static void objects(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java index 248cdd926..d8f8af0ad 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -21,11 +21,11 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.hunk.Hunk; import com.volmit.mantle.BlockBox; import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.TerrainSampler; /** @@ -45,10 +45,10 @@ public final class MatterModule implements IrisModule { } @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Matter.INSERT) + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Matter.INSERT) .requires(IrisStages.Floating.SOLIDS) - .softAfter(IrisStages.Deposit.ORES.ref()) + .softAfter(IrisStages.Deposit.ORES) .run(MatterModule::insert); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index 2b3d37c67..e07e6f521 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -22,13 +22,13 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.terrain.HideOresSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.hunk.Hunk; import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStageContext; -import com.volmit.stage.StageGraph; import java.util.ArrayList; import java.util.HashMap; @@ -54,8 +54,8 @@ public final class PerfectionModule implements IrisModule { } @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Perfection.SURFACE).requires(IrisStages.Floating.DECORATE).run(PerfectionModule::perfect); + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Perfection.SURFACE).requires(IrisStages.Floating.DECORATE).run(PerfectionModule::perfect); } private static void perfect(ChunkStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index 7b99a0856..eaef859e4 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -22,10 +22,9 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.post.PostProcessingSettings; import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; import art.arcane.iris.builtin.post.PostProcessingWallsSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; -import com.volmit.stage.StageGraph; +import com.volmit.ModuleSetup; /** Module {@code iris:post}: smooths the carved surface with {@link SurfaceSmoothing}. */ public final class PostModule implements IrisModule { @@ -37,15 +36,12 @@ public final class PostModule implements IrisModule { } @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + var registry = setup.registry(); registry.registerSettings(PostProcessingSettings.class); registry.registerSettings(PostProcessingSlabsSettings.class); registry.registerSettings(PostProcessingWallsSettings.class); - } - - @Override - public void install(StageGraph graph) { // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. - graph.define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY.ref()).run(SurfaceSmoothing::smooth); + setup.stages().define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index 41bef35b7..8420cbebf 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -31,8 +31,8 @@ import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; import java.util.Optional; @@ -51,7 +51,8 @@ public final class AnchorModule implements IrisModule { } @Override - public void install(StageGraph graph) { + public void setup(ModuleSetup setup) { + var graph = setup.stages(); graph.define(IrisStages.Anchor.HEIGHT) .requires(IrisStages.Prepare.TRANSFORMS) .produce(AnchorModule::height); @@ -72,7 +73,7 @@ public final class AnchorModule implements IrisModule { int y = settings.fromBottom() ? object.height() + 1 + prepared.rotatedCenterY() : placement.requestedY(); if (!settings.forcePlace() && !structurePiece && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { context.reject(CARVING_ANCHOR); - return new AnchorHeight(y); + return null; } if (placement.requestedY() < 0 || !settings.bottom() || structurePiece) { return new AnchorHeight(y); @@ -81,6 +82,7 @@ public final class AnchorModule implements IrisModule { if (!settings.forcePlace() && settings.carvingSupport() != CarvingMode.CARVING_ONLY && rejectsCarvingAnchor(prepared, placement.x(), y, placement.z())) { context.reject(CARVING_ANCHOR); + return null; } return new AnchorHeight(y); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 83334df33..8903fc01b 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -33,9 +33,9 @@ import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.engine.spawn.SpawnResources; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.object.BlockEntityData; @@ -43,7 +43,6 @@ import com.volmit.object.ObjectBlock; import com.volmit.placement.PlacedBlock; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; import java.util.Map; @@ -77,7 +76,8 @@ public final class BlocksModule implements IrisModule { } @Override - public void install(StageGraph graph) { + public void setup(ModuleSetup setup) { + var graph = setup.stages(); graph.define(IrisStages.Blocks.WRITE) .requires(IrisStages.Prepare.TRANSFORMS, IrisStages.Anchor.FINAL, IrisStages.Bore.CLEAR) .accumulate(WrittenBlocks::new, BlocksModule::write); @@ -88,11 +88,7 @@ public final class BlocksModule implements IrisModule { .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.MARKERS) .run(context -> { }); - } - - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(ObjectReplace.class); + setup.registry().registerHeldType(ObjectReplace.class); } private static void write(BlockStageContext context, WrittenBlocks written) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java index 9f4887f93..660a49e4a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -24,9 +24,9 @@ import art.arcane.iris.builtin.placement.PlacementSettings; import art.arcane.iris.builtin.prepare.PreparedPlacement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; /** Module {@code iris:bore}: fills the object's volume with air, extended up and down as configured. */ public final class BoreModule implements IrisModule { @@ -38,8 +38,8 @@ public final class BoreModule implements IrisModule { } @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Bore.CLEAR) + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Bore.CLEAR) .requires(IrisStages.Anchor.FINAL, IrisStages.Validate.COLLISIONS) .run(BoreModule::clear); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 96612eedb..2ebe5d86b 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -35,11 +35,10 @@ import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; import java.util.Optional; @@ -61,15 +60,13 @@ public final class PrepareModule implements IrisModule { } @Override - public void install(StageGraph graph) { + public void setup(ModuleSetup setup) { + var graph = setup.stages(); graph.define(IrisStages.Prepare.SLOPE).produce(PrepareModule::slope); graph.define(IrisStages.Prepare.TRANSFORMS) .requires(IrisStages.Prepare.SLOPE) .produce(PrepareModule::transforms); - } - - @Override - public void register(FeatureRegistry registry) { + var registry = setup.registry(); registry.registerHeldType(SlopeClip.class); registry.registerHeldType(AxisRotationClamp.class); } @@ -87,7 +84,7 @@ public final class PrepareModule implements IrisModule { } if (checksSlope && !settings.slopeCondition().isValid(placement.terrain().slopeAt(placement.x(), placement.z()))) { context.reject("slope"); - return requested; + return null; } return settings.rotateTowardsSlope() ? turnedDownhill(placement, requested) : requested; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java index 91aaa0461..4bba49b6f 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -24,10 +24,10 @@ import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.placement.PlacedBlock; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; import java.util.LinkedHashMap; @@ -50,10 +50,10 @@ public final class SnowModule implements IrisModule { } @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Snow.COVER) + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Snow.COVER) .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) - .softAfter(IrisStages.Stilt.FILL.ref(), IrisStages.Vacuum.TERRAIN.ref()) + .softAfter(IrisStages.Stilt.FILL, IrisStages.Vacuum.TERRAIN) .run(SnowModule::cover); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 3460a911a..7f2493b83 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -26,15 +26,14 @@ import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.stilt.StiltLayers; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.object.ObjectBlock; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; import java.util.List; @@ -70,20 +69,17 @@ public final class StiltModule implements IrisModule { } @Override - public void install(StageGraph graph) { + public void setup(ModuleSetup setup) { + var graph = setup.stages(); graph.define(IrisStages.Stilt.LAYERS) .requires(IrisStages.Prepare.TRANSFORMS) // Ordered after boring only so it shares the block pass that writes the object. - .softAfter(IrisStages.Bore.CLEAR.ref()) + .softAfter(IrisStages.Bore.CLEAR) .accumulate(StiltLayers::new, StiltModule::collectLayer); graph.define(IrisStages.Stilt.FILL) .requires(IrisStages.Stilt.LAYERS, IrisStages.Anchor.FINAL, IrisStages.Blocks.COMPLETE) .run(StiltModule::fill); - } - - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(StiltSettings.class); + setup.registry().registerHeldType(StiltSettings.class); } private static void collectLayer(BlockStageContext context, StiltLayers layers) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 97aa32856..90f9506f1 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -27,13 +27,12 @@ import art.arcane.iris.builtin.placement.PlaneNoise; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.iris.builtin.vacuum.VacuumSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; /** * Module {@code iris:vacuum}: bends the terrain around an object of a vacuum mode so it meets the object's @@ -55,16 +54,12 @@ public final class VacuumModule implements IrisModule { } @Override - public void install(StageGraph graph) { - graph.define(IrisStages.Vacuum.TERRAIN) + public void setup(ModuleSetup setup) { + setup.stages().define(IrisStages.Vacuum.TERRAIN) .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) .reach(IrisObjectVacuum.MAX_RADIUS_BLOCKS) .run(VacuumModule::bendTerrain); - } - - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(VacuumSettings.class); + setup.registry().registerHeldType(VacuumSettings.class); } private static void bendTerrain(PlacementStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 72c320aec..315cc4b89 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -29,14 +29,13 @@ import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.StructureVolumes; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; +import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.object.ObjectBlock; import com.volmit.stage.PlacementStageContext; -import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; import java.util.Optional; @@ -59,7 +58,8 @@ public final class ValidateModule implements IrisModule { } @Override - public void install(StageGraph graph) { + public void setup(ModuleSetup setup) { + var graph = setup.stages(); graph.define(IrisStages.Validate.SURFACE) .requires(IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkSurface); @@ -72,11 +72,7 @@ public final class ValidateModule implements IrisModule { graph.define(IrisStages.Validate.COLLISIONS) .requires(IrisStages.Validate.STRUCTURES, IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkCollisions); - } - - @Override - public void register(FeatureRegistry registry) { - registry.registerHeldType(ObjectLimit.class); + setup.registry().registerHeldType(ObjectLimit.class); } private static void checkSurface(PlacementStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index 96e08b52f..6fb53f4d3 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -21,12 +21,11 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.PlacementMarker; import art.arcane.iris.builtin.spawn.SpawnerSettings; -import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; import com.volmit.service.AmbientEffects; import com.volmit.service.EntitySpawns; -import com.volmit.stage.StageGraph; /** * Module {@code iris:spawn}: the spawners, entities and markers of the pack ({@link SpawnResources}), the @@ -44,11 +43,8 @@ public final class SpawnModule implements IrisModule { } @Override - public void install(StageGraph graph) { - } - - @Override - public void register(FeatureRegistry registry) { + public void setup(ModuleSetup setup) { + var registry = setup.registry(); registry.registerSettings(SpawnerSettings.class); registry.registerSettings(EffectSettings.class); registry.registerHeldType(PlacementMarker.class); From b15a41094dbf4fab6b4acb52e3b50873f0ff76a9 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 23 Oct 2026 14:17:21 +0200 Subject: [PATCH 097/139] Move the built-in modules to the batch 2 API Settings are read as SettingsStacks (dimension(), mostSpecific(), values()) and levels are com.volmit.config.Level. Chunk coordinates and centres come from the context's chunk helpers, surface heights from TerrainSampler.surfaceHeight, and resources from the world. Settings types register in one varargs call, and ObjectModule takes its log from setup instead of keeping a field. --- .../builtin/carve/CarvingBiomeSettings.java | 4 +- .../builtin/carve/CarvingEnabledSettings.java | 4 +- .../iris/builtin/carve/CarvingSettings.java | 4 +- .../iris/builtin/carve/CaveDepthSettings.java | 4 +- .../builtin/carve/CaveLavaHeightSettings.java | 4 +- .../iris/builtin/carve/CaveProfile.java | 4 +- .../carve/UpperDimensionCarvingSettings.java | 4 +- .../builtin/decorant/DecorantSettings.java | 4 +- .../builtin/decorant/DecorateSettings.java | 4 +- .../iris/builtin/deposit/DepositSettings.java | 4 +- .../deposit/DepositVariantSettings.java | 4 +- .../builtin/deposit/OreFrequencySettings.java | 4 +- .../iris/builtin/deposit/OreSizeSettings.java | 4 +- .../floating/FloatingChildSettings.java | 4 +- .../MergeFloatingChildrenSettings.java | 4 +- .../iris/builtin/loot/BlockDropSettings.java | 4 +- .../iris/builtin/loot/LootSettings.java | 4 +- .../iris/builtin/objects/ObjectHost.java | 4 +- .../iris/builtin/objects/ObjectSettings.java | 4 +- .../objects/ProceduralObjectSettings.java | 4 +- .../RequireSurfaceSupportSettings.java | 4 +- .../objects/SurfaceSupportBufferSettings.java | 4 +- .../builtin/objects/TreeGrowthSettings.java | 4 +- .../objects/UpperObjectsForceSettings.java | 4 +- .../builtin/objects/UpperObjectsSettings.java | 4 +- .../builtin/post/PostProcessingSettings.java | 4 +- .../post/PostProcessingSlabsSettings.java | 4 +- .../post/PostProcessingWallsSettings.java | 4 +- .../iris/builtin/spawn/EffectSettings.java | 4 +- .../iris/builtin/spawn/SpawnerSettings.java | 4 +- .../structure/StructurePlacementSettings.java | 4 +- .../builtin/structure/StructureSettings.java | 4 +- .../iris/builtin/terrain/BedrockSettings.java | 4 +- .../terrain/CaveCeilingLayersSettings.java | 4 +- .../ExplodeBiomePaletteSizeSettings.java | 4 +- .../terrain/ExplodeBiomePalettesSettings.java | 4 +- .../builtin/terrain/FluidPaletteSettings.java | 4 +- .../builtin/terrain/HideOresSettings.java | 4 +- .../iris/builtin/terrain/LayersSettings.java | 4 +- .../terrain/LockLayersMaxSettings.java | 4 +- .../builtin/terrain/LockLayersSettings.java | 4 +- .../iris/builtin/terrain/OreSettings.java | 4 +- .../builtin/terrain/PaletteExplosion.java | 15 ++-- .../builtin/terrain/RockPaletteSettings.java | 4 +- .../builtin/terrain/SeaLayersSettings.java | 4 +- .../iris/builtin/terrain/SlabSettings.java | 4 +- .../iris/builtin/terrain/TerrainPalettes.java | 17 ++--- .../iris/builtin/terrain/WallSettings.java | 4 +- .../ImportedFeaturesSettings.java | 4 +- .../iris/engine/actuator/DecorantModule.java | 10 ++- .../iris/engine/actuator/OreWarmUp.java | 16 ++--- .../iris/engine/actuator/TerrainModule.java | 18 ++--- .../iris/engine/actuator/TerrainShaper.java | 43 ++++-------- .../engine/decorator/BiomeDecorators.java | 4 +- .../engine/decorator/DecorationScene.java | 4 +- .../structure/ImportedStructures.java | 4 +- .../vanillafeatures/ImportedFeatures.java | 5 +- .../arcane/iris/engine/loot/LootModule.java | 3 +- .../iris/engine/loot/LootValidator.java | 12 ++-- .../engine/mantle/components/CaveAnchors.java | 2 +- .../engine/mantle/components/CaveCarving.java | 2 +- .../mantle/components/ChunkObjectPlacing.java | 70 +++++++++---------- .../components/FloatingObjectPlacing.java | 7 +- .../mantle/components/ObjectLocating.java | 4 +- .../mantle/components/ObjectModule.java | 19 ++--- .../mantle/components/ObjectPlacing.java | 17 ++--- .../mantle/components/ObjectWarmUp.java | 5 +- .../mantle/components/StructureModule.java | 3 +- .../engine/mantle/components/TreeGrowing.java | 9 +-- .../engine/modifier/BuiltInCaveDressing.java | 2 +- .../iris/engine/modifier/CarveModule.java | 53 +++++--------- .../iris/engine/modifier/CaveApplying.java | 2 +- .../iris/engine/modifier/DepositModule.java | 15 ++-- .../iris/engine/modifier/DepositPlacer.java | 23 ++---- .../iris/engine/modifier/FloatingIslands.java | 5 +- .../iris/engine/modifier/FloatingModule.java | 3 +- .../engine/modifier/PerfectionModule.java | 7 +- .../iris/engine/modifier/PostModule.java | 4 +- .../engine/modifier/SurfaceSmoothing.java | 18 ++--- .../engine/object/placement/BlocksModule.java | 2 +- .../object/placement/ResolvedReplaces.java | 8 +-- .../engine/object/placement/StiltModule.java | 4 +- .../terrain/carving/CarvingResolver.java | 10 +-- .../terrain/carving/DeclaredByLevel.java | 15 ++-- .../terrain/floating/FloatingWorld.java | 7 +- .../arcane/iris/engine/spawn/SpawnModule.java | 3 +- 86 files changed, 267 insertions(+), 391 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java index e2942aecb..9ee612265 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.carve; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -30,7 +30,7 @@ import java.util.Set; /** A biome's {@code carvingBiome}, written as the biome key: it registers that biome with the pack's layout and is not applied as a substitute under carvings. */ @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") -@Feature(id = "iris:carve/biome", name = "Carving biome", key = "carvingBiome", root = "biome", targets = Target.BIOME) +@Feature(id = "iris:carve/biome", name = "Carving biome", key = "carvingBiome", root = "biome", targets = Level.BIOME) public final class CarvingBiomeSettings implements IrisFeature, LinkedBiomes { @Ref(Reference.PACK_BIOME) @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java index d09f7e7ac..21f6c1385 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.carve; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** A dimension's {@code carvingEnabled}, written as the bare boolean. */ @Desc("Enable or disable all carving for this dimension") -@Feature(id = "iris:carve/enabled", name = "Carving enabled", key = "carvingEnabled", root = "enabled", targets = Target.DIMENSION) +@Feature(id = "iris:carve/enabled", name = "Carving enabled", key = "carvingEnabled", root = "enabled", targets = Level.DIMENSION) public final class CarvingEnabledSettings implements IrisFeature { @Desc("Enable or disable all carving for this dimension") private boolean enabled = true; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java index afd544963..3408c1cc6 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.carve; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -36,7 +36,7 @@ import java.util.Set; * The biome of every enabled entry takes part in the pack's layout like any biome the dimension reaches. */ @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") -@Feature(id = "iris:carve/bands", name = "Cave biome bands", key = "carving", root = "entries", targets = Target.DIMENSION) +@Feature(id = "iris:carve/bands", name = "Cave biome bands", key = "carving", root = "entries", targets = Level.DIMENSION) public final class CarvingSettings implements IrisFeature, LinkedBiomes { @MinItems(1) @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java index 08f005403..4c09160f5 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.carve; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.MinNumber; /** A biome's {@code caveMinDepthBelowSurface}, written as the bare number of blocks. */ @Desc("Minimum depth below terrain surface required before this cave biome can be selected.") -@Feature(id = "iris:carve/min-depth", name = "Cave minimum depth", key = "caveMinDepthBelowSurface", root = "depth", targets = Target.BIOME) +@Feature(id = "iris:carve/min-depth", name = "Cave minimum depth", key = "caveMinDepthBelowSurface", root = "depth", targets = Level.BIOME) public final class CaveDepthSettings implements IrisFeature { @MinNumber(0) @MaxNumber(256) diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java index 4355cbb47..51b174715 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveLavaHeightSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.carve; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.MinNumber; /** A dimension's {@code caveLavaHeight}, written as the bare number. */ @Desc("The subterranean fluid (cave lava) layer height, in engine-local Y where 0 is the bottom of the dimension, not world Y. With the default -64..320 height, 8 means world Y -56.") -@Feature(id = "iris:carve/lava-height", name = "Cave lava height", key = "caveLavaHeight", root = "height", targets = Target.DIMENSION) +@Feature(id = "iris:carve/lava-height", name = "Cave lava height", key = "caveLavaHeight", root = "height", targets = Level.DIMENSION) public final class CaveLavaHeightSettings implements IrisFeature { public static final int DEFAULT_HEIGHT = 8; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java b/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java index a64df4d67..13417f346 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java @@ -19,7 +19,7 @@ package art.arcane.iris.builtin.carve; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -43,7 +43,7 @@ import java.util.Optional; */ @Snippet("cave-profile") @Desc("Represents a configurable 3D cave profile.") -@Feature(id = "iris:carve/profile", name = "Cave profile", key = "caveProfile", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:carve/profile", name = "Cave profile", key = "caveProfile", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class CaveProfile implements IrisFeature { @Desc("Enable profile-driven cave carving.") private boolean enabled = false; diff --git a/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java index 741aaa382..2d6d05e2c 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.carve; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** A dimension's {@code upperDimensionCarving}, written as the bare boolean. */ @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") -@Feature(id = "iris:carve/upper-dimension", name = "Upper dimension carving", key = "upperDimensionCarving", root = "enabled", targets = Target.DIMENSION) +@Feature(id = "iris:carve/upper-dimension", name = "Upper dimension carving", key = "upperDimensionCarving", root = "enabled", targets = Level.DIMENSION) public final class UpperDimensionCarvingSettings implements IrisFeature { @Desc("When true, cave carving will cut through the upper dimension terrain. When false, the upper terrain is a solid untouched mass.") private boolean enabled = false; diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java index 3e00e8ed3..b83376f62 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.decorant; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -32,7 +32,7 @@ import java.util.List; * {@link Decorator}. */ @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") -@Feature(id = "iris:decorant", name = "Decorators", key = "decorators", root = "decorators", targets = Target.BIOME) +@Feature(id = "iris:decorant", name = "Decorators", key = "decorators", root = "decorators", targets = Level.BIOME) public final class DecorantSettings implements IrisFeature { @MinItems(1) @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java index bdcaf244c..c9d7cc943 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java @@ -17,14 +17,14 @@ */ package art.arcane.iris.builtin.decorant; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether a dimension decorates at all, written as {@code "decorate": false}. A dimension without the key decorates. */ @Desc("Generate decorations or not") -@Feature(id = "iris:decorant/decorate", name = "Decorate", key = "decorate", root = "decorate", targets = Target.DIMENSION) +@Feature(id = "iris:decorant/decorate", name = "Decorate", key = "decorate", root = "decorate", targets = Level.DIMENSION) public final class DecorateSettings implements IrisFeature { @Desc("Generate decorations or not") private boolean decorate = true; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java index 6fd8c5987..208f6fb52 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.deposit; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -31,7 +31,7 @@ import java.util.List; * like {@link DepositGenerator}. */ @Desc("Ores and other deposits generated in every chunk where this applies") -@Feature(id = "iris:deposit", name = "Deposits", key = "deposits", root = "generators", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:deposit", name = "Deposits", key = "deposits", root = "generators", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class DepositSettings implements IrisFeature { @Desc("Define deposit generators that this applies to chunks") private List generators = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java index e6a6d15ef..5578aa9f3 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.deposit; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -33,7 +33,7 @@ import java.util.List; */ @Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") @Feature(id = "iris:deposit/variants", name = "Deposit variants", key = "depositVariants", root = "variants", - targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) + targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class DepositVariantSettings implements IrisFeature { @MinItems(1) @Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") diff --git a/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java b/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java index e279b0df6..2d8f61ccb 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.deposit; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.MinNumber; /** A biome's {@code oreDepositFrequencyMultiplier}, written as the bare number. */ @Desc("Multiplier applied to the frequency of every ore deposit whose center is inside this biome. A value of 0.4 keeps 40% of ore veins while leaving non-ore deposits unchanged.") -@Feature(id = "iris:deposit/ore-frequency", name = "Ore deposit frequency", key = "oreDepositFrequencyMultiplier", root = "multiplier", targets = Target.BIOME) +@Feature(id = "iris:deposit/ore-frequency", name = "Ore deposit frequency", key = "oreDepositFrequencyMultiplier", root = "multiplier", targets = Level.BIOME) public final class OreFrequencySettings implements IrisFeature { private static final double UNCHANGED = 1D; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java b/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java index 80e1d5892..9c3dd9d2b 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java +++ b/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.deposit; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.MinNumber; /** A biome's {@code oreDepositSizeMultiplier}, written as the bare number. */ @Desc("Multiplier applied to the block count of every ore deposit whose center is inside this biome. Non-ore deposits are unchanged.") -@Feature(id = "iris:deposit/ore-size", name = "Ore deposit size", key = "oreDepositSizeMultiplier", root = "multiplier", targets = Target.BIOME) +@Feature(id = "iris:deposit/ore-size", name = "Ore deposit size", key = "oreDepositSizeMultiplier", root = "multiplier", targets = Level.BIOME) public final class OreSizeSettings implements IrisFeature { private static final double UNCHANGED = 1D; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java index 796b062f8..fdff1ebfe 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java @@ -19,7 +19,7 @@ package art.arcane.iris.builtin.floating; import art.arcane.iris.builtin.carve.CarvingSettings; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -38,7 +38,7 @@ import java.util.Set; * pack's layout like any biome a dimension reaches. */ @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") -@Feature(id = "iris:floating/children", name = "Floating child biomes", key = "floatingChildBiomes", root = "children", targets = Target.BIOME) +@Feature(id = "iris:floating/children", name = "Floating child biomes", key = "floatingChildBiomes", root = "children", targets = Level.BIOME) public final class FloatingChildSettings implements IrisFeature, LinkedBiomes { @MinItems(1) @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") diff --git a/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java b/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java index 24224b836..2fad82f8b 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java +++ b/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.floating; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** A biome's {@code mergeFloatingChildBiomes}, written as the bare boolean. */ @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") -@Feature(id = "iris:floating/merge", name = "Merge floating child biomes", key = "mergeFloatingChildBiomes", root = "merge", targets = Target.BIOME) +@Feature(id = "iris:floating/merge", name = "Merge floating child biomes", key = "mergeFloatingChildBiomes", root = "merge", targets = Level.BIOME) public final class MergeFloatingChildrenSettings implements IrisFeature { @Desc("When true, every floating child entry is sampled independently and their solid masks are unioned, so multiple floating islands can stack, overlap, and collide instead of the picker choosing only one child per column.") private boolean merge = false; diff --git a/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java b/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java index a58786622..948c3b5c9 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java +++ b/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.loot; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -33,7 +33,7 @@ import java.util.List; * region and dimension. */ @Desc("Define custom block drops for this area") -@Feature(id = "iris:loot/drops", name = "Block drops", key = "blockDrops", root = "drops", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:loot/drops", name = "Block drops", key = "blockDrops", root = "drops", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class BlockDropSettings implements IrisFeature { @MinItems(1) @Desc("Define custom block drops for this area") diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java index 5d9b12ae7..1d6fff05b 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.loot; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -37,7 +37,7 @@ import java.util.List; */ @Snippet("loot-registry") @Desc("Reference loot tables in this area") -@Feature(id = "iris:loot", name = "Loot", key = "loot", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:loot", name = "Loot", key = "loot", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class LootSettings implements IrisFeature { public static final double MAX_MULTIPLIER = 16D; diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java index bc85329ad..85a02cd3e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java @@ -19,7 +19,7 @@ package art.arcane.iris.builtin.objects; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; import com.volmit.config.PackSettings; @@ -125,6 +125,6 @@ public interface ObjectHost { } /** One region's or biome's declaration of settings. */ - record Declaration(Target level, String key, F settings) { + record Declaration(Level level, String key, F settings) { } } diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java index c1b7484c1..a88ddef01 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.objects; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -32,7 +32,7 @@ import java.util.List; * places those of its centre column's region and of that column's biome, and of the cave biome where it places in caves. */ @Desc("Objects define what schematics (iob files) iris will place here") -@Feature(id = "iris:objects", name = "Objects", key = "objects", root = "objects", targets = {Target.REGION, Target.BIOME}) +@Feature(id = "iris:objects", name = "Objects", key = "objects", root = "objects", targets = {Level.REGION, Level.BIOME}) public final class ObjectSettings implements IrisFeature { @MinItems(1) @Desc("Objects define what schematics (iob files) iris will place here") diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java b/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java index a23f89b5c..c64f3fe53 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java @@ -24,7 +24,7 @@ import art.arcane.iris.builtin.objects.formation.Formation; import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.builtin.objects.ruin.Ruin; import art.arcane.iris.builtin.objects.tree.Tree; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -40,7 +40,7 @@ import java.util.List; */ @Snippet("procedural-objects") @Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") -@Feature(id = "iris:objects/procedural", name = "Procedural objects", key = "proceduralObjects", targets = {Target.REGION, Target.BIOME}) +@Feature(id = "iris:objects/procedural", name = "Procedural objects", key = "proceduralObjects", targets = {Level.REGION, Level.BIOME}) public final class ProceduralObjectSettings implements IrisFeature { @MinItems(1) @Desc("Procedurally generated trees.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java b/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java index 684951af1..a612ba35e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/RequireSurfaceSupportSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.objects; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether a dimension refuses surface objects over carved openings, written as {@code "requireObjectSurfaceSupport": true}. */ @Desc("Refuse to place surface objects and trees over carved surface openings.") -@Feature(id = "iris:objects/surface-support", name = "Require surface support", key = "requireObjectSurfaceSupport", root = "require", targets = Target.DIMENSION) +@Feature(id = "iris:objects/surface-support", name = "Require surface support", key = "requireObjectSurfaceSupport", root = "require", targets = Level.DIMENSION) public final class RequireSurfaceSupportSettings implements IrisFeature { private static final boolean DEFAULT_REQUIRED = true; diff --git a/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java b/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java index 91b44f3ec..4070d0713 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/SurfaceSupportBufferSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.objects; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.MinNumber; /** The least surface-support buffer a dimension gives its surface objects, written as {@code "objectSurfaceSupportBuffer": 2}. */ @Desc("Minimum surface-support buffer, in blocks, applied to every surface object placement in this dimension. A placement may ask for more but never less.") -@Feature(id = "iris:objects/surface-support-buffer", name = "Surface support buffer", key = "objectSurfaceSupportBuffer", root = "buffer", targets = Target.DIMENSION) +@Feature(id = "iris:objects/surface-support-buffer", name = "Surface support buffer", key = "objectSurfaceSupportBuffer", root = "buffer", targets = Level.DIMENSION) public final class SurfaceSupportBufferSettings implements IrisFeature { private static final int DEFAULT_BUFFER_BLOCKS = 2; diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java b/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java index 584fe7ea3..0bec6667c 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.objects; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -28,7 +28,7 @@ import com.volmit.config.Snippet; /** Whether a dimension's saplings grow the trees of its object placements, written as {@code "treeSettings": {...}}. */ @Snippet("tree-settings") @Desc("Tree growth override settings") -@Feature(id = "iris:objects/trees", name = "Tree growth", key = "treeSettings", targets = Target.DIMENSION) +@Feature(id = "iris:objects/trees", name = "Tree growth", key = "treeSettings", targets = Level.DIMENSION) public final class TreeGrowthSettings implements IrisFeature { @Required @Desc("Turn replacing on and off") diff --git a/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java index 5264ce562..1e4a6c507 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsForceSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.objects; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether the objects placed in the terrain stacked above ignore placement restrictions, written as {@code "upperObjectsForcePlace": true}. */ @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") -@Feature(id = "iris:objects/upper-force", name = "Force upper dimension objects", key = "upperObjectsForcePlace", root = "force", targets = Target.DIMENSION) +@Feature(id = "iris:objects/upper-force", name = "Force upper dimension objects", key = "upperObjectsForcePlace", root = "force", targets = Level.DIMENSION) public final class UpperObjectsForceSettings implements IrisFeature { @Desc("When true, upper-dimension objects force-place regardless of placement restrictions (slope, underwater, clamp, collisions, carving). Normal dimension objects always place first; upper objects place second and may clip or occlude lower-dimension placements when this is enabled.") private boolean force = false; diff --git a/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java index 9d9c832fe..27592d959 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/UpperObjectsSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.objects; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether the objects of a dimension are also placed in the terrain stacked above it, written as {@code "upperDimensionObjects": true}. */ @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") -@Feature(id = "iris:objects/upper", name = "Upper dimension objects", key = "upperDimensionObjects", root = "enabled", targets = Target.DIMENSION) +@Feature(id = "iris:objects/upper", name = "Upper dimension objects", key = "upperDimensionObjects", root = "enabled", targets = Level.DIMENSION) public final class UpperObjectsSettings implements IrisFeature { @Desc("When true, objects from the mantle (structures, trees, etc.) can be placed in the upper dimension terrain zone. When false, the upper terrain is protected from object placement.") private boolean enabled = false; diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java index ceb2f1442..c434601f7 100644 --- a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java +++ b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.post; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -28,7 +28,7 @@ import com.volmit.config.Feature; * whatever it says, so it is declared to keep the key valid in packs. */ @Desc("Use post processing or not") -@Feature(id = "iris:post/enabled", name = "Post processing", key = "postProcessing", root = "enabled", targets = Target.DIMENSION) +@Feature(id = "iris:post/enabled", name = "Post processing", key = "postProcessing", root = "enabled", targets = Level.DIMENSION) public final class PostProcessingSettings implements IrisFeature { public static final boolean DEFAULT_ENABLED = true; diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java index a6bffc932..36c5b9885 100644 --- a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java +++ b/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.post; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.Feature; * Whether post processing adds slabs on steps in a dimension, written as {@code "postProcessingSlabs": false}. A dimension without the key adds them. */ @Desc("Add slabs in post processing") -@Feature(id = "iris:post/slabs", name = "Post processing slabs", key = "postProcessingSlabs", root = "enabled", targets = Target.DIMENSION) +@Feature(id = "iris:post/slabs", name = "Post processing slabs", key = "postProcessingSlabs", root = "enabled", targets = Level.DIMENSION) public final class PostProcessingSlabsSettings implements IrisFeature { public static final boolean DEFAULT_ENABLED = true; diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java b/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java index f49e5e6a7..658f97e0c 100644 --- a/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java +++ b/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.post; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.Feature; * Whether post processing paints walls on steep faces in a dimension, written as {@code "postProcessingWalls": false}. A dimension without the key paints them. */ @Desc("Add painted walls in post processing") -@Feature(id = "iris:post/walls", name = "Post processing walls", key = "postProcessingWalls", root = "enabled", targets = Target.DIMENSION) +@Feature(id = "iris:post/walls", name = "Post processing walls", key = "postProcessingWalls", root = "enabled", targets = Level.DIMENSION) public final class PostProcessingWallsSettings implements IrisFeature { public static final boolean DEFAULT_ENABLED = true; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java b/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java index 49f90914c..99a51be5f 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.spawn; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -32,7 +32,7 @@ import java.util.List; * {@link AmbientEffect}s. They play around every player in the area. */ @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") -@Feature(id = "iris:spawn/effects", name = "Effects", key = "effects", root = "effects", targets = {Target.REGION, Target.BIOME}) +@Feature(id = "iris:spawn/effects", name = "Effects", key = "effects", root = "effects", targets = {Level.REGION, Level.BIOME}) public final class EffectSettings implements IrisFeature { @MinItems(1) @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player.") diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java index b4e976c52..a8a628c3c 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.spawn; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -33,7 +33,7 @@ import java.util.List; * {@link Spawner}s. A chunk may fire the spawners of its dimension, region and biome. */ @Desc("Entity spawners that fire in this area") -@Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class SpawnerSettings implements IrisFeature { @MinItems(1) @ResourceRef(Spawner.class) diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java index 32eaffff3..18f450be1 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.structure; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -33,7 +33,7 @@ import java.util.List; */ @Desc("Iris structure placements of this dimension, region or biome: where and how often its structures start.") @Feature(id = "iris:structure/placements", name = "Structure placements", key = "structures", root = "placements", - targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) + targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class StructurePlacementSettings implements IrisFeature { @MinItems(1) @Desc("Iris structure placements, each independent of the others.") diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java index 29c7a432a..ac9b13d61 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.structure; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -38,7 +38,7 @@ import java.util.List; * platform's own definitions. IrisApi types only. */ @Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris structure list ' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") -@Feature(id = "iris:structure", name = "Structures", key = "importedStructures", targets = Target.DIMENSION) +@Feature(id = "iris:structure", name = "Structures", key = "importedStructures", targets = Level.DIMENSION) public final class StructureSettings implements IrisFeature { @MinItems(1) @Ref(Reference.STRUCTURE_PREFIX) diff --git a/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java index b92e2190d..c22523760 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/BedrockSettings.java @@ -17,14 +17,14 @@ */ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether a dimension has a layer of bedrock at its bottom, written as {@code "bedrock": false}. A dimension without the key has it. */ @Desc("Should bedrock be generated or not.") -@Feature(id = "iris:terrain/bedrock", name = "Bedrock", key = "bedrock", root = "bedrock", targets = Target.DIMENSION) +@Feature(id = "iris:terrain/bedrock", name = "Bedrock", key = "bedrock", root = "bedrock", targets = Level.DIMENSION) public final class BedrockSettings implements IrisFeature { @Desc("Should bedrock be generated or not.") private boolean bedrock = true; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java index e8ce22b91..e2a8c9c12 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -29,7 +29,7 @@ import java.util.List; * The layers of material on the ceilings of caves in a biome, written as {@code "caveCeilingLayers": [...]}, the list of layers. */ @Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") -@Feature(id = "iris:terrain/cave-ceiling-layers", name = "Cave ceiling layers", key = "caveCeilingLayers", root = "layers", targets = Target.BIOME) +@Feature(id = "iris:terrain/cave-ceiling-layers", name = "Cave ceiling layers", key = "caveCeilingLayers", root = "layers", targets = Level.BIOME) public final class CaveCeilingLayersSettings implements IrisFeature { @Desc("Layers of materials placed on cave ceilings in this biome, indexed upward from the ceiling surface. Must not have more entries than layers, whose height generators it reuses. Omitting this leaves cave ceilings unchanged.") private List layers = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java index 85a1b81d2..bc1d156ba 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java @@ -17,7 +17,7 @@ */ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -26,7 +26,7 @@ import com.volmit.config.MinNumber; /** How many barrier blocks a dimension puts between layers when it explodes its biome palettes, written as {@code "explodeBiomePaletteSize": 3}. */ @Desc("Customize the palette height explosion") -@Feature(id = "iris:terrain/explode-palette-size", name = "Explode biome palette size", key = "explodeBiomePaletteSize", root = "size", targets = Target.DIMENSION) +@Feature(id = "iris:terrain/explode-palette-size", name = "Explode biome palette size", key = "explodeBiomePaletteSize", root = "size", targets = Level.DIMENSION) public final class ExplodeBiomePaletteSizeSettings implements IrisFeature { public static final int DEFAULT_SIZE = 3; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java index 7a47733aa..a47485ed6 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java @@ -17,14 +17,14 @@ */ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether a dimension puts barrier blocks between the layers of its biomes to show them apart, written as {@code "explodeBiomePalettes": true}. */ @Desc("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") -@Feature(id = "iris:terrain/explode-palettes", name = "Explode biome palettes", key = "explodeBiomePalettes", root = "explode", targets = Target.DIMENSION) +@Feature(id = "iris:terrain/explode-palettes", name = "Explode biome palettes", key = "explodeBiomePalettes", root = "explode", targets = Level.DIMENSION) public final class ExplodeBiomePalettesSettings implements IrisFeature { @Desc("Vertically split up the biome palettes with barrier blocks in between to visualize them. The gap size comes from explodeBiomePaletteSize.") private boolean explode = false; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java index 3dbaef879..b0a336996 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.block.BlockSpec; import com.volmit.block.PaletteSpec; @@ -31,7 +31,7 @@ import java.util.List; * The blocks that fill ocean columns and cave aquifers of a dimension, written as {@code "fluidPalette": {...}}, a palette. A dimension without the key is water. */ @Desc("The dimension fluid block palette used for ocean columns and cave aquifers.") -@Feature(id = "iris:terrain/fluid-palette", name = "Fluid palette", key = "fluidPalette", root = "palette", targets = Target.DIMENSION) +@Feature(id = "iris:terrain/fluid-palette", name = "Fluid palette", key = "fluidPalette", root = "palette", targets = Level.DIMENSION) public final class FluidPaletteSettings implements IrisFeature { private static final String DEFAULT_BLOCK = "water"; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java index afebc3443..84cfb13b8 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -28,7 +28,7 @@ import com.volmit.config.Feature; * material. Written as the bare boolean. */ @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") -@Feature(id = "iris:terrain/hide-ores", name = "Hide ores", key = "hideOresForHiddenOre", root = "hide", targets = Target.DIMENSION) +@Feature(id = "iris:terrain/hide-ores", name = "Hide ores", key = "hideOresForHiddenOre", root = "hide", targets = Level.DIMENSION) public final class HideOresSettings implements IrisFeature { @Desc("When true, every ore block the generator would place (terrain ores, deposits, ores inside objects) is replaced with its base material such as stone, deepslate or netherrack, so drop-control plugins like HiddenOre can manage ore rewards themselves") private boolean hide = false; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java index 02f2ba399..41151447e 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/LayersSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -30,7 +30,7 @@ import java.util.List; * that declares none gets one layer of grass, so the settings class default is what a biome without the key has. */ @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") -@Feature(id = "iris:terrain/layers", name = "Layers", key = "layers", root = "layers", targets = Target.BIOME) +@Feature(id = "iris:terrain/layers", name = "Layers", key = "layers", root = "layers", targets = Level.BIOME) public final class LayersSettings implements IrisFeature { @Desc("This defines the layers of materials in this biome. Each layer has a palette and min/max height and some other properties. Usually a grassy/sandy layer then a dirt layer then a stone layer. Iris will fill in the remaining blocks below your layers with stone.") private List layers = List.of(new PaletteLayer()); diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java index 9b18cf7f1..4746b6ab6 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** How many layers a locked biome iterates below the surface, written as {@code "lockLayersMax": 7}. A biome without the key iterates seven. */ @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") -@Feature(id = "iris:terrain/lock-layers-max", name = "Lock layers max", key = "lockLayersMax", root = "layers", targets = Target.BIOME) +@Feature(id = "iris:terrain/lock-layers-max", name = "Lock layers max", key = "lockLayersMax", root = "layers", targets = Level.BIOME) public final class LockLayersMaxSettings implements IrisFeature { public static final int DEFAULT_LAYERS = 7; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java index a8a98063c..7204003c4 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java @@ -18,14 +18,14 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; /** Whether a biome's layers are locked to its highest possible height, written as {@code "lockLayers": true}. A biome without the key is not locked. */ @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") -@Feature(id = "iris:terrain/lock-layers", name = "Lock layers", key = "lockLayers", root = "locked", targets = Target.BIOME) +@Feature(id = "iris:terrain/lock-layers", name = "Lock layers", key = "lockLayers", root = "locked", targets = Level.BIOME) public final class LockLayersSettings implements IrisFeature { @Desc("Layers no longer descend from the surface block, they descend from the max possible height the biome can produce (constant) creating mesa like layers.") private boolean locked = false; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java index ae2d39553..4f82565aa 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -33,7 +33,7 @@ import java.util.List; * like {@link OreGenerator}. */ @Desc("Collection of ores to be generated") -@Feature(id = "iris:terrain/ores", name = "Ores", key = "ores", root = "generators", targets = {Target.DIMENSION, Target.REGION, Target.BIOME}) +@Feature(id = "iris:terrain/ores", name = "Ores", key = "ores", root = "generators", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class OreSettings implements IrisFeature { @MinItems(1) @Desc("Collection of ores to be generated") diff --git a/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java b/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java index 0e0201678..b88d7a2f7 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java @@ -18,9 +18,6 @@ package art.arcane.iris.builtin.terrain; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; - -import java.util.List; /** Whether a dimension separates the layers of its biomes with barrier blocks to show them apart, and how many barriers it puts between them. */ public record PaletteExplosion(boolean exploded, int size) { @@ -28,14 +25,10 @@ public record PaletteExplosion(boolean exploded, int size) { /** What the dimension at the column of {@code settings} declares. */ public static PaletteExplosion of(FeatureSettings settings, int worldX, int worldZ) { - boolean exploded = dimensionValue(settings.at(ExplodeBiomePalettesSettings.class, worldX, worldZ), ExplodeBiomePalettesSettings::explode, false); - int size = dimensionValue(settings.at(ExplodeBiomePaletteSizeSettings.class, worldX, worldZ), ExplodeBiomePaletteSizeSettings::size, - ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); + boolean exploded = settings.at(ExplodeBiomePalettesSettings.class, worldX, worldZ).dimension() + .map(ExplodeBiomePalettesSettings::explode).orElse(false); + int size = settings.at(ExplodeBiomePaletteSizeSettings.class, worldX, worldZ).dimension() + .map(ExplodeBiomePaletteSizeSettings::size).orElse(ExplodeBiomePaletteSizeSettings.DEFAULT_SIZE); return new PaletteExplosion(exploded, size); } - - private static V dimensionValue(List> entries, java.util.function.Function read, V fallback) { - return entries.stream().filter(entry -> entry.level() == com.volmit.FeatureAttachment.Target.DIMENSION).findFirst() - .map(entry -> read.apply(entry.value())).orElse(fallback); - } } diff --git a/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java index 786c25326..66dd5fd4a 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.block.BlockSpec; import com.volmit.block.PaletteSpec; @@ -31,7 +31,7 @@ import java.util.List; * The blocks that fill terrain below the layers of a dimension, written as {@code "rockPalette": {...}}, a palette. A dimension without the key is stone. */ @Desc("The palette of blocks for 'stone'") -@Feature(id = "iris:terrain/rock-palette", name = "Rock palette", key = "rockPalette", root = "palette", targets = Target.DIMENSION) +@Feature(id = "iris:terrain/rock-palette", name = "Rock palette", key = "rockPalette", root = "palette", targets = Level.DIMENSION) public final class RockPaletteSettings implements IrisFeature { private static final String DEFAULT_BLOCK = "stone"; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java index d6693e572..e81e00b2a 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -29,7 +29,7 @@ import java.util.List; * The layers of material filling the water column of a sea biome, written as {@code "seaLayers": [...]}, the list of layers. */ @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") -@Feature(id = "iris:terrain/sea-layers", name = "Sea layers", key = "seaLayers", root = "layers", targets = Target.BIOME) +@Feature(id = "iris:terrain/sea-layers", name = "Sea layers", key = "seaLayers", root = "layers", targets = Level.BIOME) public final class SeaLayersSettings implements IrisFeature { @Desc("Layers of materials filling the water column of sea biomes, indexed downward from the water surface. Anything below the last layer is filled with the dimension fluid palette, not stone.") private List layers = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java index a9f1d9f0d..46adeef22 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -27,7 +27,7 @@ import com.volmit.config.Feature; * The slab post processing places on steps in a biome, written as {@code "slab": {...}}, one layer. A biome without the key has no slab. */ @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") -@Feature(id = "iris:terrain/slab", name = "Slab", key = "slab", root = "layer", targets = Target.BIOME) +@Feature(id = "iris:terrain/slab", name = "Slab", key = "slab", root = "layer", targets = Level.BIOME) public final class SlabSettings implements IrisFeature { @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") private PaletteLayer layer = PaletteLayer.withoutBlocks(); diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java index 1d991d0ae..a415ed931 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java @@ -20,10 +20,9 @@ package art.arcane.iris.builtin.terrain; import art.arcane.iris.builtin.IrisSeed; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.SettingsStack; import com.volmit.noise.NoiseSampler; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; @@ -112,20 +111,16 @@ public final class TerrainPalettes { long seedOffset = upper.key().hashCode(); RNG rng = new RNG(complexSeed ^ seedOffset); - List> declared = upper.settings().at(RockPaletteSettings.class, (int) x, (int) z); + SettingsStack declared = upper.settings().at(RockPaletteSettings.class, (int) x, (int) z); return columns(rockPalette(declared), rng.nextParallelRNG(ROCK_SIGNATURE), upper.resources()); } - private static PaletteSpec rockPalette(List> declared) { - return dimensionLevel(declared).map(Entry::value).orElseGet(RockPaletteSettings::new).palette(); + private static PaletteSpec rockPalette(SettingsStack declared) { + return declared.dimension().orElseGet(RockPaletteSettings::new).palette(); } - private static PaletteSpec fluidPalette(List> declared) { - return dimensionLevel(declared).map(Entry::value).orElseGet(FluidPaletteSettings::new).palette(); - } - - private static java.util.Optional> dimensionLevel(List> declared) { - return declared.stream().filter(entry -> entry.level() == Target.DIMENSION).findFirst(); + private static PaletteSpec fluidPalette(SettingsStack declared) { + return declared.dimension().orElseGet(FluidPaletteSettings::new).palette(); } /** The palette's blocks over the columns, picked by its noise: the noise at a column, from 0 to 1, is how far down the weighted list the block is. */ diff --git a/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java b/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java index 4c700b1e4..3ef3e8d8a 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.terrain; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -28,7 +28,7 @@ import com.volmit.config.Feature; * A biome without the key has no wall. */ @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") -@Feature(id = "iris:terrain/wall", name = "Wall", key = "wall", root = "layer", targets = Target.BIOME) +@Feature(id = "iris:terrain/wall", name = "Wall", key = "wall", root = "layer", targets = Level.BIOME) public final class WallSettings implements IrisFeature { @Desc("The default wall if iris decides to place a wall higher than 2 blocks (steep hills or possibly cliffs)") private PaletteLayer layer = PaletteLayer.withoutBlocks(); diff --git a/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java b/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java index cf5bfaf2b..543309866 100644 --- a/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java +++ b/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java @@ -18,7 +18,7 @@ package art.arcane.iris.builtin.vanillafeatures; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; @@ -34,7 +34,7 @@ import java.util.List; * decoration steps it leaves out. IrisApi types only. */ @Desc("Controls native vanilla, mod, and ingested datapack PLACED FEATURE generation for this dimension. Placed features are ores, trees, plants, springs, geodes and every other decoration entry a biome declares. This is OFF by default: with 'enabled' false Iris generates exactly the terrain it always has and no native feature runs. With it true, every placed feature the biome's vanilla derivative declares runs over Iris terrain, in vanilla step order, on the same worldgen thread vanilla uses. Carvers are never imported - Iris has no NoiseGeneratorSettings, so there is nothing for a carver to carve against. Family matching on 'disabled' uses namespace, slash, or underscore boundaries, so 'minecraft:ore' covers every vanilla ore feature without matching unrelated names.") -@Feature(id = "iris:vanilla-features", name = "Vanilla features", key = "importedFeatures", targets = Target.DIMENSION) +@Feature(id = "iris:vanilla-features", name = "Vanilla features", key = "importedFeatures", targets = Level.DIMENSION) public final class ImportedFeaturesSettings implements IrisFeature { @Desc("Master switch. False (the default) means no native placed feature generates and chunk output is identical to a pack without this block at all. True runs the vanilla decoration feature pass over Iris terrain.") private boolean enabled = false; diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 94d02d58d..6848c4fa6 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -47,7 +47,6 @@ import com.volmit.world.TerrainSampler; */ public final class DecorantModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; - private static final int CHUNK_CENTRE = 7; @Override public ModuleInfo info() { @@ -59,8 +58,7 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { // Ordering only: iris:matter ships in the built-ins jar, which a pack may not have. setup.stages().define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT).run(DecorantModule::decorate); var registry = setup.registry(); - registry.registerSettings(DecorantSettings.class); - registry.registerSettings(DecorateSettings.class); + registry.registerSettings(DecorantSettings.class, DecorateSettings.class); registry.registerLifecycle(this); } @@ -78,8 +76,8 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { /** A dimension decorates unless it says {@code decorate: false}. */ private static boolean decorates(ChunkStageContext context) { - return context.settings().at(DecorateSettings.class, context.originX() + CHUNK_CENTRE, context.originZ() + CHUNK_CENTRE).stream() - .allMatch(entry -> entry.value().decorate()); + return context.settings().at(DecorateSettings.class, context.centreX(), context.centreZ()).dimension() + .map(DecorateSettings::decorate).orElse(true); } /** Decorates the 16 x 16 columns of the chunk whose first block is {@code x}, {@code z}, a biome's decorators on the surface its blocks left. */ @@ -102,7 +100,7 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { if (!decorators.hasDecorators(biome)) { continue; } - int height = (int) Math.round(terrain.surfaceY(realX, realZ)); + int height = terrain.surfaceHeight(realX, realZ); if (height >= 0 && height < fluidHeight && scene.isSolid(output.get(i, height, j)) && height + 1 < output.getHeight() && scene.isWater(output.get(i, height + 1, j))) { diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java index f3812b71a..366b6b415 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -20,13 +20,13 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.terrain.OreSettings; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import java.util.Comparator; -import java.util.List; import java.util.function.LongSupplier; /** @@ -55,15 +55,15 @@ final class OreWarmUp { void warm() { LongSupplier seeds = () -> root.nextParallelRNG(warmed++).getSeed(); - List> declared = world.settings().declared(OreSettings.class); - warmLevel(declared, Target.BIOME, seeds); - warmLevel(declared, Target.REGION, seeds); - warmLevel(declared, Target.DIMENSION, seeds); + SettingsStack declared = world.settings().declared(OreSettings.class); + warmLevel(declared, Level.BIOME, seeds); + warmLevel(declared, Level.REGION, seeds); + warmLevel(declared, Level.DIMENSION, seeds); } /** The ores of every owner at {@code level}, ordered by the key of the biome, region or dimension that declares them. */ - private void warmLevel(List> declared, Target level, LongSupplier seeds) { - declared.stream() + private void warmLevel(SettingsStack declared, Level level, LongSupplier seeds) { + declared.entries().stream() .filter(entry -> entry.level() == level) .sorted(Comparator.comparing((Entry entry) -> key(entry.source()))) .forEach(entry -> ores.of(entry.value()).warm(seeds)); diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 6ddada286..f11596586 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -59,20 +59,10 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { public void setup(ModuleSetup setup) { setup.stages().define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); var registry = setup.registry(); - registry.registerSettings(LayersSettings.class); - registry.registerSettings(SeaLayersSettings.class); - registry.registerSettings(CaveCeilingLayersSettings.class); - registry.registerSettings(SlabSettings.class); - registry.registerSettings(WallSettings.class); - registry.registerSettings(LockLayersSettings.class); - registry.registerSettings(LockLayersMaxSettings.class); - registry.registerSettings(RockPaletteSettings.class); - registry.registerSettings(FluidPaletteSettings.class); - registry.registerSettings(OreSettings.class); - registry.registerSettings(HideOresSettings.class); - registry.registerSettings(BedrockSettings.class); - registry.registerSettings(ExplodeBiomePalettesSettings.class); - registry.registerSettings(ExplodeBiomePaletteSizeSettings.class); + registry.registerSettings(LayersSettings.class, SeaLayersSettings.class, CaveCeilingLayersSettings.class, SlabSettings.class, + WallSettings.class, LockLayersSettings.class, LockLayersMaxSettings.class, RockPaletteSettings.class, FluidPaletteSettings.class, + OreSettings.class, HideOresSettings.class, BedrockSettings.class, ExplodeBiomePalettesSettings.class, + ExplodeBiomePaletteSizeSettings.class); registry.registerLifecycle(this); } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index 5a5429466..2af428c30 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -29,11 +29,11 @@ import art.arcane.iris.builtin.terrain.PaletteExplosion; import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.block.BlockState; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.hunk.Hunk; import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStageContext; @@ -41,15 +41,12 @@ import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import com.volmit.world.UpperDimension; -import java.util.List; import java.util.Optional; import java.util.OptionalInt; -import java.util.function.Function; /** What shaping terrain keeps for one world: the terrain stream's random and the palettes, layers and ores the columns are filled from. */ final class TerrainShaper { private static final BlockState BEDROCK = new BlockState("minecraft:bedrock"); - private static final int CHUNK_CENTRE = 7; private final TerrainPalettes palettes; private final BiomeLayers layers; @@ -70,8 +67,8 @@ final class TerrainShaper { this.layers = layers; this.ores = ores; this.rng = new RNG(IrisSeed.TERRAIN.of(world)); - this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).stream() - .anyMatch(entry -> entry.level() != Target.DIMENSION); + this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).entries().stream() + .anyMatch(entry -> entry.level() != Level.DIMENSION); } /** Fills the 16 x 16 columns of the chunk, one slice along x at a time. */ @@ -91,7 +88,7 @@ final class TerrainShaper { for (int zf = 0; zf < chunkDepth; zf++) { int realZ = zf + chunk.originZ; - int he = Math.min(chunkHeight, (int) Math.round(chunk.terrain.surfaceY(realX, realZ))); + int he = Math.min(chunkHeight, chunk.terrain.surfaceHeight(realX, realZ)); int hf = Math.max(chunk.clampedFluidHeight, he); if (hf < 0) { continue; @@ -238,7 +235,7 @@ final class TerrainShaper { } private static S biomeLevel(FeatureSettings settings, Class type, int worldX, int worldZ) { - return settings.at(type, worldX, worldZ).stream().filter(entry -> entry.level() == Target.BIOME).map(Entry::value).findFirst().orElse(null); + return settings.at(type, worldX, worldZ).level(Level.BIOME).orElse(null); } /** A block the palette has none of leaves the column as it is. */ @@ -276,15 +273,15 @@ final class TerrainShaper { this.originX = context.originX(); this.originZ = context.originZ(); this.clampedFluidHeight = Math.min(blocks.getHeight(), terrain.fluidHeight()); - int centreX = originX + CHUNK_CENTRE; - int centreZ = originZ + CHUNK_CENTRE; - this.bedrockEnabled = dimensionValue(settings.at(BedrockSettings.class, centreX, centreZ), BedrockSettings::bedrock, true); - this.hideOres = dimensionValue(settings.at(HideOresSettings.class, centreX, centreZ), HideOresSettings::hide, false); + int centreX = context.centreX(); + int centreZ = context.centreZ(); + this.bedrockEnabled = settings.at(BedrockSettings.class, centreX, centreZ).dimension().map(BedrockSettings::bedrock).orElse(true); + this.hideOres = settings.at(HideOresSettings.class, centreX, centreZ).dimension().map(HideOresSettings::hide).orElse(false); this.explosion = PaletteExplosion.of(settings, centreX, centreZ); this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); this.upper = terrain.upperDimension(); // Dimension-level ore lookups are chunk-invariant; resolving them per column paid the settings lookup times 256 per chunk for a constant. - this.dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(levelValue(settings.at(OreSettings.class, centreX, centreZ), Target.DIMENSION)); + this.dimensionOres = hideOres ? ResolvedOres.NONE : ores.of(settings.at(OreSettings.class, centreX, centreZ).dimension().orElse(null)); } /** What the upper dimension declares about exploded palettes: a setting of the dimension, so the same for every column of the chunk. */ @@ -300,22 +297,8 @@ final class TerrainShaper { if (hideOres || !levelsBelowTheDimensionDeclareOres) { return ColumnOres.NONE; } - List> declared = settings.at(OreSettings.class, worldX, worldZ); - return new ColumnOres(ores.of(levelValue(declared, Target.REGION)), ores.of(levelValue(declared, Target.BIOME))); + SettingsStack declared = settings.at(OreSettings.class, worldX, worldZ); + return new ColumnOres(ores.of(declared.level(Level.REGION).orElse(null)), ores.of(declared.level(Level.BIOME).orElse(null))); } } - - private static V dimensionValue(List> entries, Function read, V fallback) { - S declared = levelValue(entries, Target.DIMENSION); - return declared == null ? fallback : read.apply(declared); - } - - private static S levelValue(List> entries, Target level) { - for (Entry entry : entries) { - if (entry.level() == level) { - return entry.value(); - } - } - return null; - } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java index 0a346f27a..526ccb134 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java +++ b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -75,7 +75,7 @@ public final class BiomeDecorators { /** The biome of the entry a column's settings gave, which is the column's surface biome; null when the biome declares nothing. */ public static DecoratedBiome biomeOf(FeatureSettings settings, int worldX, int worldZ, com.volmit.world.BiomeKind kind) { - List> entries = settings.at(DecorantSettings.class, worldX, worldZ); + List> entries = settings.at(DecorantSettings.class, worldX, worldZ).entries(); if (entries.isEmpty()) { return null; } @@ -108,7 +108,7 @@ public final class BiomeDecorators { /** Resolves every decorator of every biome the dimension reaches and builds its noise, so that generation finds them ready. */ public void warm() { - List> declared = new ArrayList<>(world.settings().declared(DecorantSettings.class)); + List> declared = new ArrayList<>(world.settings().declared(DecorantSettings.class).entries()); declared.sort(Comparator.comparing(entry -> biomeKey(entry.source()))); for (Entry entry : declared) { DecoratedBiome biome = new DecoratedBiome(biomeKey(entry.source()), entry.value(), null); diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java index 7df79fdc1..272797c76 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -51,7 +51,7 @@ public final class DecorationScene { /** The chunk of {@code context}, decorated with the world's decorators. */ public static DecorationScene of(ChunkStageContext context) { Mantle mantle = context.mantle(); - return new DecorationScene(context.hunk(BlockState.class), context.resources().blocks(), context.terrain(), + return new DecorationScene(context.hunk(BlockState.class), context.world().resources().blocks(), context.terrain(), mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), IrisSeed.COMPONENT.of(context.world()), context.log()); } @@ -108,7 +108,7 @@ public final class DecorationScene { /** The height of the terrain at the column, rounded. */ long roundedHeightAt(int worldX, int worldZ) { - return Math.round(terrain.surfaceY(worldX, worldZ)); + return terrain.surfaceHeight(worldX, worldZ); } /** The block a placement planned at the position, or air; positions the mantle does not cover read as air. */ diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java index fd4680bfd..9f323742c 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructures.java @@ -22,7 +22,6 @@ import art.arcane.iris.builtin.RegistryKeyFamily; import art.arcane.iris.builtin.structure.StructureAdjustment; import art.arcane.iris.builtin.structure.StructureSetFrequency; import art.arcane.iris.builtin.structure.StructureSettings; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; import com.volmit.resource.ResourceId; import com.volmit.vanilla.VanillaStructureSetup; @@ -46,8 +45,7 @@ public final class ImportedStructures { /** The settings the dimension of {@code settings} declares, or the defaults when it declares none. */ public static ImportedStructures of(PackSettings settings) { - List> declared = settings.declared(StructureSettings.class); - return new ImportedStructures(declared.isEmpty() ? new StructureSettings() : declared.getFirst().value()); + return new ImportedStructures(settings.declared(StructureSettings.class).dimension().orElseGet(StructureSettings::new)); } /** Whether the dimension disables the platform structure {@code key}, by family or by its exact key. */ diff --git a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java index 0cafe0ba5..15f5367d5 100644 --- a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java +++ b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java @@ -20,13 +20,11 @@ package art.arcane.iris.engine.framework.vanillafeatures; import art.arcane.iris.builtin.RegistryKeyFamily; import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.resource.ResourceId; import com.volmit.service.VanillaFeatures; import com.volmit.vanilla.DecorationStep; import com.volmit.world.PackWorld; -import java.util.List; import java.util.Optional; /** @@ -61,7 +59,6 @@ public final class ImportedFeatures implements VanillaFeatures { } private static ImportedFeaturesSettings settings(PackWorld world) { - List> declared = world.settings().declared(ImportedFeaturesSettings.class); - return declared.isEmpty() ? NONE : declared.getFirst().value(); + return world.settings().declared(ImportedFeaturesSettings.class).dimension().orElse(NONE); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index 0c0106b67..d29cd6677 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -45,8 +45,7 @@ public final class LootModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(LootSettings.class); - registry.registerSettings(BlockDropSettings.class); + registry.registerSettings(LootSettings.class, BlockDropSettings.class); registry.registerHeldType(ObjectLoot.class); registry.registerHeldType(ObjectVanillaLoot.class); LootResources.kinds().forEach(registry::registerResourceKind); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java index 1ffb66a50..e1c1dc5cc 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -23,8 +23,8 @@ import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootMode; import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.builtin.loot.LootTable; -import com.volmit.FeatureAttachment.Target; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.validation.Problem; @@ -70,7 +70,7 @@ public final class LootValidator implements Validator { private static List checkReferences(ValidationContext pack) { Set lootIds = Set.copyOf(pack.resources().ids(LootTable.class)); List problems = new ArrayList<>(); - List> declared = new ArrayList<>(pack.settings().declared(LootSettings.class)); + List> declared = new ArrayList<>(pack.settings().declared(LootSettings.class).entries()); declared.sort(Comparator.comparing(Entry::level).thenComparing(Entry::source)); for (Entry entry : declared) { String resourceKey = keyOf(entry); @@ -106,21 +106,21 @@ public final class LootValidator implements Validator { return path.substring(path.indexOf(LEVEL_FOLDER_SEPARATOR) + 1); } - private static String hostType(Target level) { + private static String hostType(Level level) { return switch (level) { case DIMENSION -> "Dimension"; case REGION -> "Region"; case BIOME -> "Biome"; - case OBJECT_PLACEMENT -> "Resource"; + case PLACEMENT -> "Resource"; }; } - private static String folderOf(Target level) { + private static String folderOf(Level level) { return switch (level) { case DIMENSION -> "dimensions"; case REGION -> "regions"; case BIOME -> "biomes"; - case OBJECT_PLACEMENT -> "placements"; + case PLACEMENT -> "placements"; }; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java index 71cabe0de..e7444ceb9 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java @@ -221,7 +221,7 @@ final class CaveAnchors { if (known != null) { return known; } - int surfaceY = (int) Math.round(terrain.surfaceY(x, z)); + int surfaceY = terrain.surfaceHeight(x, z); surfaceHeights.put(columnKey, surfaceY); return surfaceY; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 2cebe417d..d6ca52145 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -471,7 +471,7 @@ public class CaveCarving { int worldX = baseX + localX; for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - scratch[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, baseZ + localZ)); + scratch[columnIndex] = terrain.surfaceHeight(worldX, baseZ + localZ); } } return scratch; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 027f10da0..950a5eb6d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -38,10 +38,10 @@ import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.ModuleLog; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.resource.ResourceId; import com.volmit.stage.MantleStageContext; import com.volmit.world.TerrainSampler; @@ -55,8 +55,8 @@ import java.util.OptionalInt; * and its procedural objects, in that order, all drawing from the one random of the chunk. */ final class ChunkObjectPlacing { - private static final int CENTER_OFFSET_BLOCKS = 8; - private static final int CHUNK_SHIFT = 4; + /** Objects read their chunk's settings at local 8, 8 as Iris always did, not at the API's centre column (local 7, 7): moving it would move objects. */ + private static final int OBJECT_COLUMN_OFFSET_BLOCKS = 8; private static final int CHUNK_WIDTH_BLOCKS = 16; private static final double CHANCE_JITTER = 0.005; private static final int[] CAVE_BIOME_SAMPLE_DEPTHS = {48, 80, 112}; @@ -91,10 +91,10 @@ final class ChunkObjectPlacing { this.context = context; this.chunk = host.chunk(); this.terrain = context.terrain(); - this.chunkX = context.originX() >> CHUNK_SHIFT; - this.chunkZ = context.originZ() >> CHUNK_SHIFT; - this.centerX = CENTER_OFFSET_BLOCKS + (chunkX << CHUNK_SHIFT); - this.centerZ = CENTER_OFFSET_BLOCKS + (chunkZ << CHUNK_SHIFT); + this.chunkX = context.chunkX(); + this.chunkZ = context.chunkZ(); + this.centerX = context.originX() + OBJECT_COLUMN_OFFSET_BLOCKS; + this.centerZ = context.originZ() + OBJECT_COLUMN_OFFSET_BLOCKS; this.rng = host.chunkRandom(chunkX, chunkZ); this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && host.debugging(); this.golden = chunk.goldenDebug(chunkX, chunkZ); @@ -127,16 +127,12 @@ final class ChunkObjectPlacing { private Column readColumn() { ResourceId region = host.regionAt(centerX, centerZ); ResourceId surface = host.surfaceBiomeAt(centerX, centerZ); - int surfaceY = surfaceY(centerX, centerZ); + int surfaceY = terrain.surfaceHeight(centerX, centerZ); ResourceId cave = resolveCaveObjectBiome(surfaceY, surface); return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), proceduralOf(cave, region, surface), profilesOf(cave, region, surface)); } - private int surfaceY(int x, int z) { - return (int) Math.round(terrain.surfaceY(x, z)); - } - private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) { ResourceId legacy = caveBiomeAt(Math.max(1, surfaceY - LEGACY_CAVE_SAMPLE_DEPTH)).orElse(surfaceBiome); ResourceId ladderChoice = null; @@ -161,39 +157,37 @@ final class ChunkObjectPlacing { } private ColumnObjects objectsOf(ResourceId cave, ResourceId region, ResourceId surface) { - List> entries = context.settings().at(ObjectSettings.class, centerX, centerZ); - return new ColumnObjects(level(entries, Target.BIOME), caveSettings(cave, surface, entries, ObjectSettings.class), level(entries, Target.REGION)); + SettingsStack declared = context.settings().at(ObjectSettings.class, centerX, centerZ); + return new ColumnObjects(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, ObjectSettings.class), + levelValue(declared, Level.REGION)); } private ColumnProcedural proceduralOf(ResourceId cave, ResourceId region, ResourceId surface) { - List> entries = context.settings().at(ProceduralObjectSettings.class, centerX, centerZ); - return new ColumnProcedural(level(entries, Target.BIOME), - caveSettings(cave, surface, entries, ProceduralObjectSettings.class), level(entries, Target.REGION)); + SettingsStack declared = context.settings().at(ProceduralObjectSettings.class, centerX, centerZ); + return new ColumnProcedural(levelValue(declared, Level.BIOME), + caveSettings(cave, surface, declared, ProceduralObjectSettings.class), levelValue(declared, Level.REGION)); } private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) { - List> entries = context.settings().at(CaveProfile.class, centerX, centerZ); - return new ColumnProfiles(level(entries, Target.BIOME), caveSettings(cave, surface, entries, CaveProfile.class), level(entries, Target.REGION)); + SettingsStack declared = context.settings().at(CaveProfile.class, centerX, centerZ); + return new ColumnProfiles(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, CaveProfile.class), + levelValue(declared, Level.REGION)); } - private F caveSettings(ResourceId cave, ResourceId surface, List> entries, Class type) { + private F caveSettings(ResourceId cave, ResourceId surface, SettingsStack declared, Class type) { if (cave.equals(surface)) { - return level(entries, Target.BIOME); + return levelValue(declared, Level.BIOME); } return host.biomeDeclaration(cave, type).orElse(null); } private F dimensionLevel(Class type) { - return level(context.settings().at(type, centerX, centerZ), Target.DIMENSION); + return levelValue(context.settings().at(type, centerX, centerZ), Level.DIMENSION); } - private static F level(List> entries, Target level) { - for (Entry entry : entries) { - if (entry.level() == level) { - return entry.value(); - } - } - return null; + /** The value {@code level} declares, or null: the column records below hold null for a level that declares nothing. */ + private static F levelValue(SettingsStack declared, Level level) { + return declared.level(level).orElse(null); } private boolean dimensionRequiresSurfaceSupport() { @@ -288,8 +282,8 @@ final class ChunkObjectPlacing { } private void placeObject(Tally tally, ObjectPlacement placement, String scope) { - int blockX = chunkX << CHUNK_SHIFT; - int blockZ = chunkZ << CHUNK_SHIFT; + int blockX = context.originX(); + int blockZ = context.originZ(); int density = host.density(placement, rng, blockX, blockZ); for (int i = 0; i < density; i++) { tally.attempts++; @@ -329,8 +323,8 @@ final class ChunkObjectPlacing { private void placeCaveObject(Tally tally, ObjectPlacement placement, CaveProfile profile, String scope, ResourceId expectedCaveBiome, CaveAnchors anchors) { - int minX = chunkX << CHUNK_SHIFT; - int minZ = chunkZ << CHUNK_SHIFT; + int minX = context.originX(); + int minZ = context.originZ(); int density = host.density(placement, rng, minX, minZ); CaveAnchors.Search search = caves.searchFor(placement, profile); for (int i = 0; i < density; i++) { @@ -408,8 +402,8 @@ final class ChunkObjectPlacing { if (placements.isEmpty()) { return; } - int blockX = chunkX << CHUNK_SHIFT; - int blockZ = chunkZ << CHUNK_SHIFT; + int blockX = context.originX(); + int blockZ = context.originZ(); CaveAnchors anchors = newAnchors(); for (ProceduralPlacement placement : placements) { boolean chancePassed = passesProceduralChance(rng, placement.chance()); @@ -521,8 +515,8 @@ final class ChunkObjectPlacing { } private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) { - int minX = chunkX << CHUNK_SHIFT; - int minZ = chunkZ << CHUNK_SHIFT; + int minX = context.originX(); + int minZ = context.originZ(); int density = host.density(placement, rng, minX, minZ); for (int i = 0; i < density; i++) { Optional picked = host.pickScaled(placement, rng); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index df128ed41..43b2ccf66 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -34,9 +34,9 @@ import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; import com.volmit.config.PackSettings; import com.volmit.mantle.BlockBox; import com.volmit.resource.ResourceId; @@ -60,7 +60,6 @@ import java.util.Set; public final class FloatingObjectPlacing { private static final int INVERTED_PICK_ATTEMPTS = 8; private static final long CHUNK_RANDOM_SALT = 0x0FA710BEL; - private static final int CHUNK_SHIFT = 4; private static final int CHUNK_COLUMNS = 256; private static final int MIN_REACH_BLOCKS = 16; private static final int LARGE_REACH_WARNING_BLOCKS = 128; @@ -97,7 +96,7 @@ public final class FloatingObjectPlacing { int minZ = context.originZ(); BlockBox bounds = context.terrain().bounds(); int worldHeight = bounds.maxY() - bounds.minY(); - RNG chunkRng = new RNG(CacheKey.key(minX >> CHUNK_SHIFT, minZ >> CHUNK_SHIFT) + mantleSeed + CHUNK_RANDOM_SALT); + RNG chunkRng = new RNG(CacheKey.key(context.chunkX(), context.chunkZ()) + mantleSeed + CHUNK_RANDOM_SALT); FloatingIslandSampleResolver samples = new FloatingIslandSampleResolver(world, worldHeight, new FloatingIslandBoundarySampler(host::surfaceBiome), log); @@ -391,7 +390,7 @@ public final class FloatingObjectPlacing { int maxObjectExtent = MIN_REACH_BLOCKS; try { for (Entry declared : settings.declared(FloatingChildSettings.class)) { - if (declared.level() != Target.BIOME) { + if (declared.level() != Level.BIOME) { continue; } ResourceId biome = biomeIdOf(declared.source()); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index 144077e11..f058dd1d7 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -22,7 +22,7 @@ import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectHost.Declaration; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.service.ObjectsAt; import com.volmit.world.PackWorld; @@ -48,7 +48,7 @@ public final class ObjectLocating implements ObjectsAt { if (!placesObject(declaration.settings().objects(), objectKey)) { continue; } - (declaration.level() == Target.BIOME ? biomes : regions).add(declaration.key()); + (declaration.level() == Level.BIOME ? biomes : regions).add(declaration.key()); } return new PlacedBy(biomes, regions); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 7973b7990..8000bbced 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -49,8 +49,6 @@ import com.volmit.world.PackWorld; public final class ObjectModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; - private ModuleLog log; - @Override public ModuleInfo info() { return ModuleInfo.of("iris:objects", "Objects", VERSION); @@ -58,19 +56,16 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { @Override public void setup(ModuleSetup setup) { - log = setup.log(); + ModuleLog log = setup.log(); // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. - setup.stages().define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES).reach(this::reach).run(ObjectModule::place); + setup.stages().define(IrisStages.Objects.PLACE).softAfter(IrisStages.Carve.CAVES).reach(settings -> reach(settings, log)) + .run(ObjectModule::place); var registry = setup.registry(); registry.registerService(ObjectsAt.class, new ObjectLocating()); registry.registerService(SaplingGrowth.class, new TreeGrowing()); - registry.registerSettings(ObjectSettings.class); - registry.registerSettings(ProceduralObjectSettings.class); - registry.registerSettings(TreeGrowthSettings.class); - registry.registerSettings(RequireSurfaceSupportSettings.class); - registry.registerSettings(SurfaceSupportBufferSettings.class); - registry.registerSettings(UpperObjectsSettings.class); - registry.registerSettings(UpperObjectsForceSettings.class); + registry.registerSettings(ObjectSettings.class, ProceduralObjectSettings.class, TreeGrowthSettings.class, + RequireSurfaceSupportSettings.class, SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, + UpperObjectsForceSettings.class); registry.registerLifecycle(this); } @@ -83,7 +78,7 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { ObjectPlacing.of(context.world()).place(context); } - private int reach(PackSettings settings) { + private static int reach(PackSettings settings, ModuleLog log) { return new PlacementReach(ObjectHost.of(settings), log).ofPack(settings); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index e07447045..53cae24f7 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -23,15 +23,14 @@ import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.ModuleLog; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; import com.volmit.stage.MantleStageContext; import com.volmit.world.PackWorld; import java.util.HashSet; -import java.util.List; import java.util.Optional; import java.util.Set; @@ -44,6 +43,8 @@ public final class ObjectPlacing { private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; private static final int CHUNK_SHIFT = 4; private static final double CHANCE_JITTER = 0.005; + /** A guess draws from the biome's objects before the region's, as placing does. */ + private static final Level[] GUESSED_LEVELS = {Level.BIOME, Level.REGION}; private final ObjectHost host; private final ModuleLog log; @@ -68,14 +69,10 @@ public final class ObjectPlacing { RNG rng = host.chunkRandom(chunkX, chunkZ); int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; - List> entries = host.columnSettings().at(ObjectSettings.class, centerX, centerZ); + SettingsStack declared = host.columnSettings().at(ObjectSettings.class, centerX, centerZ); Set keys = new HashSet<>(); - for (Target level : new Target[]{Target.BIOME, Target.REGION}) { - for (Entry entry : entries) { - if (entry.level() == level) { - guessFrom(entry.value(), rng, chunkX, chunkZ, keys); - } - } + for (Level level : GUESSED_LEVELS) { + declared.level(level).ifPresent(settings -> guessFrom(settings, rng, chunkX, chunkZ, keys)); } return keys; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 4af693f2a..5501701e0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -27,7 +27,7 @@ import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.world.PackWorld; import java.util.Comparator; @@ -41,6 +41,7 @@ import java.util.List; */ final class ObjectWarmUp { private static final long ROOT_SEED_SALT = 7777L; + private static final Level[] WARMED_LEVELS = {Level.BIOME, Level.REGION}; private final ObjectHost host; private final RNG root; @@ -54,7 +55,7 @@ final class ObjectWarmUp { void warm() { List> placements = byKey(host.declarations(ObjectSettings.class)); List> procedural = byKey(host.declarations(ProceduralObjectSettings.class)); - for (Target level : new Target[]{Target.BIOME, Target.REGION}) { + for (Level level : WARMED_LEVELS) { for (Declaration declaration : placements) { if (declaration.level() == level) { warmPlacements(declaration.settings().objects()); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index f4ea4f6b2..278492a78 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -47,8 +47,7 @@ public final class StructureModule implements IrisModule { setup.stages().define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE, IrisStages.Floating.OBJECTS) .reach(StructureModule::reach).run(StructureModule::place); var registry = setup.registry(); - registry.registerSettings(StructureSettings.class); - registry.registerSettings(StructurePlacementSettings.class); + registry.registerSettings(StructureSettings.class, StructurePlacementSettings.class); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 51f73827a..2214ec445 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -29,8 +29,6 @@ import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.TreeMode; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.block.BlockState; import com.volmit.placement.PlacedBlock; import com.volmit.resource.ResourceId; @@ -92,12 +90,7 @@ public final class TreeGrowing implements SaplingGrowth { } private static TreeGrowthSettings treeGrowth(ObjectHost host, BlockPosition at) { - for (Entry entry : host.columnSettings().at(TreeGrowthSettings.class, at.x(), at.z())) { - if (entry.level() == Target.DIMENSION) { - return entry.value(); - } - } - return new TreeGrowthSettings(); + return host.columnSettings().at(TreeGrowthSettings.class, at.x(), at.z()).dimension().orElseGet(TreeGrowthSettings::new); } /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java b/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java index e7ed1001a..c54076c93 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java @@ -57,7 +57,7 @@ final class BuiltInCaveDressing implements CaveDressing { this.layers = BiomeLayers.of(context.world()); this.palettes = TerrainPalettes.of(context.world()); this.settings = context.settings(); - this.blocks = context.resources().blocks(); + this.blocks = context.world().resources().blocks(); this.explosion = PaletteExplosion.of(settings, context.originX(), context.originZ()); this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); this.scene = DecorationScene.of(context); diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 2c23616e0..062ce3ad8 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -35,9 +35,7 @@ import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; -import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; -import com.volmit.FeatureAttachment.Target; +import com.volmit.generation.ChunkContext; import com.volmit.hunk.Hunk; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; @@ -61,9 +59,6 @@ public final class CarveModule implements IrisModule { private static final String VERSION = "built-in"; /** Blended cave walls reach one block past the chunk. */ private static final int CAVE_REACH_BLOCKS = 1; - private static final int CHUNK_SHIFT = 4; - /** The centre column of a chunk, where per-chunk settings are read. */ - private static final int CHUNK_CENTRE_BLOCKS = 7; @Override public ModuleInfo info() { @@ -73,13 +68,8 @@ public final class CarveModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(CaveProfile.class); - registry.registerSettings(CarvingSettings.class); - registry.registerSettings(CarvingEnabledSettings.class); - registry.registerSettings(CarvingBiomeSettings.class); - registry.registerSettings(CaveDepthSettings.class); - registry.registerSettings(CaveLavaHeightSettings.class); - registry.registerSettings(UpperDimensionCarvingSettings.class); + registry.registerSettings(CaveProfile.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class, + CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class); registry.registerService(CaveBiomes.class, new CaveBiomeBands()); var graph = setup.stages(); @@ -88,29 +78,27 @@ public final class CarveModule implements IrisModule { } private static void planCaves(MantleStageContext context) { - if (!carves(context.settings(), context.originX(), context.originZ())) { + if (!carves(context)) { return; } MatterMantle mantle = MatterMantle.of(context.mantle()); - caveCarving(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) - .carve(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT); + caveCarving(context).carve(mantle, context.terrain(), context.chunkX(), context.chunkZ()); } private static void applyCaves(ChunkStageContext context) { MatterMantle mantle = MatterMantle.of(context.mantle()); Hunk blocks = context.hunk(BlockState.class); - caveApplying(context.world(), context.terrain(), context.settings(), context.originX(), context.originZ()) - .apply(mantle, context.terrain(), context.originX() >> CHUNK_SHIFT, context.originZ() >> CHUNK_SHIFT, blocks, CaveDressing.of(context)); + caveApplying(context).apply(mantle, context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context)); } - private static CaveCarving caveCarving(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { - return world.state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, terrain), - upperDimensionCarving(settings, originX, originZ), fluidColumns(generating))); + private static CaveCarving caveCarving(ChunkContext context) { + return context.world().state(CaveCarving.class, generating -> new CaveCarving(generating, carveWorld(generating, context.terrain()), + upperDimensionCarving(context), fluidColumns(generating))); } - private static CaveApplying caveApplying(PackWorld world, TerrainSampler terrain, FeatureSettings settings, int originX, int originZ) { - return world.state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, terrain), - upperDimensionCarving(settings, originX, originZ))); + private static CaveApplying caveApplying(ChunkContext context) { + return context.world().state(CaveApplying.class, generating -> new CaveApplying(generating, carveWorld(generating, context.terrain()), + upperDimensionCarving(context))); } /** The columns the dimension's fluid palette fills with a fluid. */ @@ -130,26 +118,23 @@ public final class CarveModule implements IrisModule { world.minHeight()); } - private static boolean upperDimensionCarving(FeatureSettings settings, int originX, int originZ) { - return dimensionEntry(settings, UpperDimensionCarvingSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS) - .map(UpperDimensionCarvingSettings::enabled).orElse(false); + private static boolean upperDimensionCarving(ChunkContext context) { + return centreDimensionValue(context, UpperDimensionCarvingSettings.class).map(UpperDimensionCarvingSettings::enabled).orElse(false); } /** * A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents} * also does: Iris then skips this stage's mantle pass like any disabled component. */ - private static boolean carves(FeatureSettings settings, int originX, int originZ) { - return dimensionEntry(settings, CarvingEnabledSettings.class, originX + CHUNK_CENTRE_BLOCKS, originZ + CHUNK_CENTRE_BLOCKS) - .map(CarvingEnabledSettings::enabled).orElse(true); + private static boolean carves(ChunkContext context) { + return centreDimensionValue(context, CarvingEnabledSettings.class).map(CarvingEnabledSettings::enabled).orElse(true); } - private static Optional dimensionEntry(FeatureSettings settings, Class type, int x, int z) { - return settings.at(type, x, z).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).findFirst(); + private static Optional centreDimensionValue(ChunkContext context, Class type) { + return context.settings().at(type, context.centreX(), context.centreZ()).dimension(); } private static V dimensionSetting(PackWorld world, Class type, Function read, V fallback) { - return world.settings().declared(type).stream().filter(entry -> entry.level() == Target.DIMENSION).map(Entry::value).map(read) - .findFirst().orElse(fallback); + return world.settings().declared(type).dimension().map(read).orElse(fallback); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 5d77c7741..2ac4475fe 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -183,7 +183,7 @@ public class CaveApplying { int localZ = columnIndex & 15; int worldX = localX + chunkBlockX; int worldZ = localZ + chunkBlockZ; - surfaceHeights[columnIndex] = (int) Math.round(terrain.surfaceY(worldX, worldZ)); + surfaceHeights[columnIndex] = terrain.surfaceHeight(worldX, worldZ); if (protectUpper) { upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt(); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index d10806271..fbdb502e7 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -41,7 +41,6 @@ import java.util.List; */ public final class DepositModule implements IrisModule { private static final String VERSION = "built-in"; - private static final int CHUNK_CENTRE = 7; @Override public ModuleInfo info() { @@ -51,9 +50,7 @@ public final class DepositModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(DepositVariantSettings.class); - registry.registerSettings(OreFrequencySettings.class); - registry.registerSettings(OreSizeSettings.class); + registry.registerSettings(DepositVariantSettings.class, OreFrequencySettings.class, OreSizeSettings.class); setup.stages().define(IrisStages.Deposit.ORES) .when(DepositSettings.class) @@ -63,17 +60,17 @@ public final class DepositModule implements IrisModule { } private static void place(ChunkStageContext context) { - List generators = generatorsAtCentre(context.settings(), context.originX(), context.originZ()); + List generators = generatorsAt(context.settings(), context.centreX(), context.centreZ()); if (generators.isEmpty()) { return; } DepositPlacer.of(context.world()).generate(context, generators); } - /** Every level's generators at the centre column of the chunk whose first block is {@code originX}, {@code originZ}, in level order. */ - static List generatorsAtCentre(FeatureSettings settings, int originX, int originZ) { - return settings.at(DepositSettings.class, originX + CHUNK_CENTRE, originZ + CHUNK_CENTRE).stream() - .flatMap(entry -> entry.value().generators().stream()) + /** Every level's generators at the column {@code x}, {@code z}, in level order. */ + static List generatorsAt(FeatureSettings settings, int x, int z) { + return settings.at(DepositSettings.class, x, z).values().stream() + .flatMap(declared -> declared.generators().stream()) .toList(); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index f611b34f8..c582696e7 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -28,13 +28,13 @@ import art.arcane.iris.builtin.deposit.OreSizeSettings; import art.arcane.iris.engine.modifier.ResolvedDeposit.BiomeIdentity; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; -import com.volmit.FeatureAttachment.Target; import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.hunk.Hunk; import com.volmit.mantle.MantleLayer; import com.volmit.resource.PackResources; @@ -61,7 +61,6 @@ import java.util.function.Supplier; */ final class DepositPlacer { private static final double UNCHANGED_ORE_MULTIPLIER = 1D; - private static final int CHUNK_SHIFT = 4; private static final int CHUNK_WIDTH = 16; private static final long CHUNK_X_SEED_FACTOR = 341873128712L; private static final long CHUNK_Z_SEED_FACTOR = 132897987541L; @@ -100,9 +99,7 @@ final class DepositPlacer { /** Runs {@code generators}, in order, on the chunk of {@code context}. */ void generate(ChunkStageContext context, List generators) { Placing placing = new Placing(context); - int chunkX = context.originX() >> CHUNK_SHIFT; - int chunkZ = context.originZ() >> CHUNK_SHIFT; - long seed = chunkX * CHUNK_X_SEED_FACTOR + chunkZ * CHUNK_Z_SEED_FACTOR; + long seed = context.chunkX() * CHUNK_X_SEED_FACTOR + context.chunkZ() * CHUNK_Z_SEED_FACTOR; long mask = 0; for (DepositGenerator generator : generators) { long finalSeed = seed * ++mask; @@ -294,7 +291,7 @@ final class DepositPlacer { if (!surfaceKnown) { for (int x = 0; x < CHUNK_WIDTH; x++) { for (int z = 0; z < CHUNK_WIDTH; z++) { - surfaceHeights[x * CHUNK_WIDTH + z] = (int) Math.round(terrain.surfaceY(originX + x, originZ + z)); + surfaceHeights[x * CHUNK_WIDTH + z] = terrain.surfaceHeight(originX + x, originZ + z); } } surfaceKnown = true; @@ -318,19 +315,13 @@ final class DepositPlacer { } } - BlockState match = matchDepositVariant(levelSettings(Target.REGION, worldX, worldZ), ore, worldY); + SettingsStack declared = settings.at(DepositVariantSettings.class, worldX, worldZ); + BlockState match = matchDepositVariant(declared.level(Level.REGION), ore, worldY); if (match != null) { return match; } - return matchDepositVariant(levelSettings(Target.DIMENSION, worldX, worldZ), ore, worldY); - } - - private Optional levelSettings(Target level, int worldX, int worldZ) { - return settings.at(DepositVariantSettings.class, worldX, worldZ).stream() - .filter(entry -> entry.level() == level) - .map(Entry::value) - .findFirst(); + return matchDepositVariant(declared.dimension(), ore, worldY); } private BlockState matchDepositVariant(Optional owner, BlockState ore, int y) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 28af360d0..7feaf2408 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -68,7 +68,6 @@ final class FloatingIslands { private static final int FIRST_LAYER_GENERATOR_SEED = 7235; private static final int MIN_PALETTE_DEPTH = 4; private static final int CHUNK_WIDTH = 16; - private static final int CHUNK_CENTRE = 7; private static final BlockState BARRIER = new BlockState("minecraft:barrier"); private static final BlockState FALLBACK_SOLID = new BlockState("minecraft:stone"); private static final String DEFAULT_FLUID = "minecraft:water"; @@ -449,9 +448,9 @@ final class FloatingIslands { this.originZ = context.originZ(); this.output = context.hunk(BlockState.class); this.height = output.getHeight(); - this.blocks = context.resources().blocks(); + this.blocks = context.world().resources().blocks(); this.settings = context.settings(); - this.explosion = PaletteExplosion.of(settings, originX + CHUNK_CENTRE, originZ + CHUNK_CENTRE); + this.explosion = PaletteExplosion.of(settings, context.centreX(), context.centreZ()); TerrainSampler terrain = context.terrain(); this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); this.boundarySampler = new FloatingIslandBoundarySampler(world.host()::surfaceBiome); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index d9d3e7953..1b84810cc 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -50,8 +50,7 @@ public final class FloatingModule implements IrisModule { public void setup(ModuleSetup setup) { log = setup.log(); var registry = setup.registry(); - registry.registerSettings(FloatingChildSettings.class); - registry.registerSettings(MergeFloatingChildrenSettings.class); + registry.registerSettings(FloatingChildSettings.class, MergeFloatingChildrenSettings.class); var graph = setup.stages(); graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE).reach(this::objectReach) diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index e07e6f521..dae38916a 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -44,7 +44,6 @@ import java.util.Map; public final class PerfectionModule implements IrisModule { private static final String VERSION = "built-in"; private static final String HALF = "half"; - private static final int CENTER = 7; private static final BlockState AIR = new BlockState("minecraft:air"); private static final Map ORE_BASES = oreBases(); @@ -63,7 +62,7 @@ public final class PerfectionModule implements IrisModule { if (hidesOres(context)) { hideOres(blocks, new IdentityHashMap<>()); } - Surfaces surfaces = new Surfaces(blocks, context.resources().blocks(), new IdentityHashMap<>()); + Surfaces surfaces = new Surfaces(blocks, context.world().resources().blocks(), new IdentityHashMap<>()); boolean removed; do { removed = surfaces.removeUnsupportedDecorants(); @@ -72,8 +71,8 @@ public final class PerfectionModule implements IrisModule { /** The dimension's {@code hideOresForHiddenOre}, which every column of the chunk shares. */ private static boolean hidesOres(ChunkStageContext context) { - return context.settings().at(HideOresSettings.class, context.originX() + CENTER, context.originZ() + CENTER).stream() - .anyMatch(entry -> entry.value().hide()); + return context.settings().at(HideOresSettings.class, context.centreX(), context.centreZ()).dimension() + .map(HideOresSettings::hide).orElse(false); } /** {@code hidden} remembers per state instance what it is hidden as, itself for a block that is no ore. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index eaef859e4..a28fe3c3b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -38,9 +38,7 @@ public final class PostModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(PostProcessingSettings.class); - registry.registerSettings(PostProcessingSlabsSettings.class); - registry.registerSettings(PostProcessingWallsSettings.class); + registry.registerSettings(PostProcessingSettings.class, PostProcessingSlabsSettings.class, PostProcessingWallsSettings.class); // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. setup.stages().define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index e25ebad01..76129afa0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -32,7 +32,6 @@ import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.hunk.Hunk; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStageContext; import com.volmit.world.TerrainSampler; @@ -54,7 +53,6 @@ final class SurfaceSmoothing { private static final String SLAB_SUFFIX = "_slab"; private static final String WATERLOGGED = "waterlogged"; private static final String TRUE = "true"; - private static final int CENTER = 7; /** A biome without a wall or slab picks no block. */ private static final PaletteLayer NO_LAYER = PaletteLayer.withoutBlocks(); /** Walls and slabs are picked once per column: the first signature of a layer's noise. */ @@ -79,7 +77,7 @@ final class SurfaceSmoothing { private SurfaceSmoothing(ChunkStageContext context) { this.blocks = context.hunk(BlockState.class); - this.registry = context.resources().blocks(); + this.registry = context.world().resources().blocks(); this.terrain = context.terrain(); this.settings = context.settings(); this.layerBlocks = LayerBlocks.of(context.world()); @@ -88,8 +86,8 @@ final class SurfaceSmoothing { this.originZ = context.originZ(); this.planeWidth = blocks.getWidth() + 2; this.heights = heightPlane(); - this.walls = enabled(PostProcessingWallsSettings.class, PostProcessingWallsSettings::enabled, PostProcessingWallsSettings.DEFAULT_ENABLED); - this.slabs = enabled(PostProcessingSlabsSettings.class, PostProcessingSlabsSettings::enabled, PostProcessingSlabsSettings.DEFAULT_ENABLED); + this.walls = enabled(context, PostProcessingWallsSettings.class, PostProcessingWallsSettings::enabled, PostProcessingWallsSettings.DEFAULT_ENABLED); + this.slabs = enabled(context, PostProcessingSlabsSettings.class, PostProcessingSlabsSettings::enabled, PostProcessingSlabsSettings.DEFAULT_ENABLED); this.fluidHeight = terrain.fluidHeight(); } @@ -112,15 +110,13 @@ final class SurfaceSmoothing { * corners are never read, so they are left unresolved. */ /** A switch of the dimension, which every column of the chunk shares. */ - private boolean enabled(Class type, Function enabled, boolean byDefault) { - List> entries = settings.at(type, originX + CENTER, originZ + CENTER); - return entries.isEmpty() ? byDefault : enabled.apply(entries.getFirst().value()); + private static boolean enabled(ChunkStageContext context, Class type, Function enabled, boolean byDefault) { + return context.settings().at(type, context.centreX(), context.centreZ()).dimension().map(enabled).orElse(byDefault); } /** The biome layer of the column's surface biome that {@code type} holds, or none. */ private PaletteLayer biomeLayer(Class type, Function layer, int x, int z) { - List> entries = settings.at(type, x, z); - return entries.isEmpty() ? NO_LAYER : layer.apply(entries.getLast().value()); + return settings.at(type, x, z).mostSpecific().map(layer).orElse(NO_LAYER); } /** The layer's block at the position, picked with the world's post-processing random, or null when it has none. */ @@ -146,7 +142,7 @@ final class SurfaceSmoothing { } private int surfaceHeight(int x, int z) { - return (int) Math.round(terrain.surfaceY(x, z)); + return terrain.surfaceHeight(x, z); } private void post(int localX, int localZ) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 8903fc01b..3180ccae8 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -104,7 +104,7 @@ public final class BlocksModule implements IrisModule { if (!settings.edit().isEmpty()) { ObjectEdits.Edited edited = ObjectEdits.apply(settings.edit(), data, blockEntity, new RNG(context.random().nextLong()), offset.x() + placement.x(), offset.y() + anchorY, offset.z() + placement.z(), - ResolvedReplaces.of(context, prepared.terrain()), placement); + ResolvedReplaces.of(context), placement); data = edited.data(); blockEntity = edited.blockEntity(); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java index 27b9e24dc..4ea3d2723 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ResolvedReplaces.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.builtin.placement.PlacementTerrain; import com.volmit.block.BlockRegistry; import com.volmit.stage.PlacementStageContext; @@ -35,11 +34,8 @@ final class ResolvedReplaces { this.blocks = blocks; } - /** The replacements of the world {@code context} places in, or of the pack alone when the placement has no world. */ - static ResolvedReplaces of(PlacementStageContext context, PlacementTerrain terrain) { - if (!terrain.hasWorld()) { - return new ResolvedReplaces(context.resources().blocks()); - } + /** The replacements of the world {@code context} places in. */ + static ResolvedReplaces of(PlacementStageContext context) { return context.world().state(ResolvedReplaces.class, world -> new ResolvedReplaces(world.resources().blocks())); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 7f2493b83..7880110af 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -150,7 +150,7 @@ public final class StiltModule implements IrisModule { /** The block the settings' palette picks for this placement, the same for every column; null without a palette. */ private BlockState paletteBlock(StiltSettings stilt) { return stilt.palette() - .map(spec -> context.resources().blocks().palette(spec, rng.getSeed())) + .map(spec -> context.world().resources().blocks().palette(spec, rng.getSeed())) .map(picker -> picker.at(placement.x(), anchorY, placement.z())) .orElse(null); } @@ -189,7 +189,7 @@ public final class StiltModule implements IrisModule { return state; } return ObjectEdits.apply(config.edit(), state, Optional.empty(), rng, offset.x() + placement.x(), offset.y() + anchorY, - offset.z() + placement.z(), ResolvedReplaces.of(context, prepared.terrain()), placement).data(); + offset.z() + placement.z(), ResolvedReplaces.of(context), placement).data(); } private void growToSurface(BlockState state, BlockPosition offset, int x, int z) { diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index ad137c0fa..e5b36c9f4 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -22,9 +22,7 @@ import art.arcane.iris.builtin.IrisSeed; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import com.volmit.ModuleLog; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Range; -import com.volmit.FeatureAttachment.Target; import com.volmit.noise.NoiseSampler; import com.volmit.resource.PackResources; import com.volmit.world.PackBiome; @@ -72,13 +70,7 @@ public final class CarvingResolver { } private static List dimensionEntries(PackWorld world) { - List dimensionEntries = new ArrayList<>(); - for (Entry entry : world.settings().declared(CarvingSettings.class)) { - if (entry.level() == Target.DIMENSION) { - dimensionEntries.addAll(entry.value().entries()); - } - } - return dimensionEntries; + return world.settings().declared(CarvingSettings.class).dimension().map(CarvingSettings::entries).orElse(List.of()); } /** Every declared entry, enabled or not. */ diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java index bc0aac7af..dd92f3c57 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredByLevel.java @@ -18,9 +18,10 @@ package art.arcane.iris.engine.object.terrain.carving; -import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; @@ -46,19 +47,17 @@ public final class DeclaredByLevel { } public static DeclaredByLevel of(PackWorld world, Class type) { - F dimension = null; + SettingsStack declared = world.settings().declared(type); Map regions = new HashMap<>(); Map biomes = new HashMap<>(); - for (Entry entry : world.settings().declared(type)) { - if (entry.level() == Target.DIMENSION) { - dimension = entry.value(); - } else if (entry.level() == Target.REGION) { + for (Entry entry : declared) { + if (entry.level() == Level.REGION) { regions.putIfAbsent(sampleId(entry.source()), entry.value()); - } else if (entry.level() == Target.BIOME) { + } else if (entry.level() == Level.BIOME) { biomes.putIfAbsent(sampleId(entry.source()), entry.value()); } } - return new DeclaredByLevel<>(dimension, regions, biomes); + return new DeclaredByLevel<>(declared.dimension().orElse(null), regions, biomes); } /** The dimension's declaration; null when it declares none. */ diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index ef8108107..34d6991c7 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -29,8 +29,6 @@ import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import com.volmit.FeatureAttachment.Target; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.noise.NoiseFactory; import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; @@ -78,10 +76,7 @@ public final class FloatingWorld { } private static List dimensionCarvingOf(PackWorld world) { - return world.settings().declared(CarvingSettings.class).stream() - .filter(entry -> entry.level() == Target.DIMENSION) - .map(Entry::value) - .findFirst() + return world.settings().declared(CarvingSettings.class).dimension() .map(CarvingSettings::entries) .orElse(List.of()); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index 6fb53f4d3..d964b4a0d 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -45,8 +45,7 @@ public final class SpawnModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(SpawnerSettings.class); - registry.registerSettings(EffectSettings.class); + registry.registerSettings(SpawnerSettings.class, EffectSettings.class); registry.registerHeldType(PlacementMarker.class); SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); From 00e1fc1e275cba6b0936b249bcfbc95edc91d3f7 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 00:17:17 +0200 Subject: [PATCH 098/139] Batch 3 of the API review: built-ins reach Iris through extensions - Every facade is asked through IrisApi's extension point: world.extension(...) for IrisSeeds, LiveWorld, ObjectHost, FloatingHost and StructureHost, context.extension(...) for ObjectPlacement and MatterMantle, settings.extension(...) for reaches. The X.of(...) casts, the *.Source interfaces, ObjectPlacement.current() and PlacementBinding are gone; IrisSeed is an enum and IrisSeeds gives the seeds. - Facades that worked from a thread binding take the invocation context instead (ObjectHost.chunk, StructureHost.placeChunk, FloatingHost's placements). - Resources are looked up by kind and id; services, loot, spawns, structures, objects, cave bands and LinkedBiomes use ResourceId. - Value records are built with Optionals, starts are keyed by StartKey, and deposits ask Mantle.isCarved. - README describes the extension point and the chunk stage's matter. --- README.md | 22 +++++--- .../art/arcane/iris/builtin/IrisSeed.java | 17 +------ .../PlacementBinding.java => IrisSeeds.java} | 27 +++------- .../art/arcane/iris/builtin/LiveWorld.java | 16 +----- .../art/arcane/iris/builtin/MatterMantle.java | 24 ++------- .../builtin/carve/CarvingBiomeSettings.java | 6 ++- .../iris/builtin/carve/CarvingSettings.java | 10 ++-- .../floating/FloatingChildSettings.java | 16 ++++-- .../iris/builtin/floating/FloatingHost.java | 44 +++++----------- .../iris/builtin/objects/ObjectHost.java | 32 +++--------- .../builtin/placement/ObjectPlacement.java | 13 +---- .../iris/builtin/structure/StructureHost.java | 32 ++---------- .../iris/builtin/terrain/TerrainPalettes.java | 3 +- .../iris/engine/actuator/OreWarmUp.java | 3 +- .../iris/engine/actuator/TerrainOres.java | 3 +- .../iris/engine/actuator/TerrainShaper.java | 3 +- .../engine/decorator/BiomeDecorators.java | 3 +- .../engine/decorator/DecorationScene.java | 3 +- .../structure/StructureGraphValidation.java | 2 +- .../structure/StructureLocating.java | 49 ++++++++++++++---- .../structure/StructureResources.java | 4 +- .../structure/StructureVanillaStructures.java | 6 +-- .../structure/fit/CarveFootprints.java | 5 +- .../framework/structure/fit/FitStart.java | 3 +- .../framework/structure/fit/RigidSupport.java | 5 +- .../structure/fit/SurfaceFitting.java | 7 ++- .../iris/engine/loot/BlockDropping.java | 2 +- .../arcane/iris/engine/loot/LootGiving.java | 21 ++++---- .../arcane/iris/engine/loot/LootItems.java | 24 ++++++--- .../iris/engine/loot/LootResources.java | 8 ++- .../arcane/iris/engine/loot/LootTables.java | 2 +- .../iris/engine/loot/LootValidator.java | 6 +-- .../iris/engine/loot/PlacementLoot.java | 2 +- .../mantle/components/ChunkObjectPlacing.java | 2 +- .../components/FloatingObjectPlacing.java | 19 ++++--- .../mantle/components/ObjectLocating.java | 30 +++++++---- .../mantle/components/ObjectModule.java | 2 +- .../mantle/components/ObjectPlacing.java | 2 +- .../mantle/components/ObjectWarmUp.java | 5 +- .../mantle/components/StructureModule.java | 4 +- .../engine/mantle/components/TreeGrowing.java | 13 +++-- .../iris/engine/modifier/CarveModule.java | 8 +-- .../iris/engine/modifier/CaveApplying.java | 4 +- .../iris/engine/modifier/CaveBiomeBands.java | 8 +-- .../iris/engine/modifier/DepositPlacer.java | 15 +++--- .../iris/engine/modifier/FloatingIslands.java | 3 +- .../engine/modifier/SurfaceSmoothing.java | 3 +- .../engine/object/placement/AnchorModule.java | 4 +- .../engine/object/placement/BlocksModule.java | 4 +- .../engine/object/placement/BoreModule.java | 2 +- .../object/placement/PrepareModule.java | 4 +- .../engine/object/placement/StiltModule.java | 2 +- .../engine/object/placement/VacuumModule.java | 2 +- .../object/placement/ValidateModule.java | 8 +-- .../terrain/carving/CarvingResolver.java | 3 +- .../terrain/carving/ResolvedCarvingEntry.java | 3 +- .../terrain/floating/FloatingWorld.java | 7 ++- .../object/world/dimension/IrisDimension.java | 6 +-- .../object/world/region/IrisRegion.java | 4 +- .../iris/engine/spawn/AmbientEffecting.java | 12 ++--- .../iris/engine/spawn/EntityResolution.java | 50 +++++++++++-------- .../iris/engine/spawn/EntitySpawning.java | 36 +++++++------ .../iris/engine/spawn/SpawnResources.java | 4 +- 63 files changed, 337 insertions(+), 355 deletions(-) rename src/main/java/art/arcane/iris/builtin/{placement/PlacementBinding.java => IrisSeeds.java} (53%) diff --git a/README.md b/README.md index 23208e07f..35322cf98 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ regions and biomes. The loot tables, spawners, entities and markers are plain mo `EntityDefinition`, `SpawnMarker`). `PlacementLoot` picks the table an object placement gives one of its chests. `iris:decorant`, `iris:terrain` and `iris:deposit` ship in the built-ins jar and keep their per-world workers (`BiomeDecorators`, `TerrainShaper`, `DepositPlacer`) in the world's state store (`context.world().state(...)`); the modules still compiled into Iris reach the same store through -`IrisChunk.state(...)` / `engine.getGeneration().state(...)`. +the `IrisChunk` their invocation offers (`context.extension(IrisChunk.class)`, then `state(...)`) or `engine.getGeneration().state(...)`. Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in @@ -188,24 +188,30 @@ none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps e `builtin-modules.txt`): add a module to the jar and to that list together. `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of -every other class: `IrisSeed` (Iris's per-feature world seeds, a facade Iris's worlds implement, so existing worlds generate the -same) and `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same +every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never +through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`IrisSeeds`, `LiveWorld`, +`ObjectHost`, `FloatingHost`, `StructureHost`), `context.extension(X.class)` for what belongs to one invocation (`ObjectPlacement` +in a placement stage, `MatterMantle` in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out +before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. `IrisSeeds` gives +Iris's per-feature world seeds (`seeds.seed(IrisSeed.CARVE)`), so existing worlds generate the same; `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same layers, and a layer's noise is built once per world by whichever asks first), `LiveWorld` (what the loot and spawn services ask a running world, outside any chunk stage: the layout and settings at a block, the platform's weather and loot tables, the -objects' loot and the spawner cooldowns Iris saves with the world; values only, implemented by Iris's worlds like `IrisSeed`), +objects' loot and the spawner cooldowns Iris saves with the world; values only), `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`, which the modules register as held types, because Iris's `IrisObjectPlacement` holds them). The placement stages need more of the object being -placed than IrisApi describes, so `placement.ObjectPlacement` is the facade Iris implements for each placement and binds to the placing -thread (`ObjectPlacement.current()`): the object's size (`ObjectShape`), the placement's settings (`PlacementSettings`, read from +placed than IrisApi describes, so `placement.ObjectPlacement` is the facade Iris implements for each placement and offers with +its invocation (`context.extension(ObjectPlacement.class)`): the object's size (`ObjectShape`), the placement's settings (`PlacementSettings`, read from Iris's `IrisObjectPlacement`), the terrain questions of its placer and the world around it (`PlacementTerrain`), the surface warp, and the block operations only the platform can do (turning a state with the object, merging two states, matching, traits of the placement's own states). Its types answer with IrisApi, VolmLib and built-in values only. `prepare.PreparedPlacement`, the output of `iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. -`iris:carve` also reads the mantle's matter slices through `MatterMantle` (a facade Iris's mantle implements: the chunk of -`MatterCavern`s and markers it plans and applies, which the platform and the rest of Iris read as slices, not as module layers). What a +`iris:carve` also reads the mantle's matter slices through `MatterMantle` (the chunk of `MatterCavern`s and markers it plans and +applies, which the platform and the rest of Iris read as slices, not as module layers). A mantle stage gets the whole mantle; a +chunk stage gets its own chunk and the neighbors the world already holds in memory, which is all the cave apply stage ever read, +so it writes nothing outside its chunk. What a cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`terrain.BiomeLayers`, `terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeed.java b/src/main/java/art/arcane/iris/builtin/IrisSeed.java index 9f141f2d8..43f79f943 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisSeed.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeed.java @@ -24,21 +24,8 @@ import com.volmit.world.PackWorld; * The seeds Iris derives from a world's seed for its own features. Iris derives them one after another from a shared * random, so they cannot be worked out from the world seed alone. Built-in modules seed their randoms and noise with * them, so worlds generated before the features were modules generate the same; a pack module derives its own seeds - * from {@link PackWorld#seed()}. + * from {@link PackWorld#seed()}. A world Iris generates answers for them through its {@link IrisSeeds} extension. */ public enum IrisSeed { - BIOME, CARVE, COMPLEX, COMPONENT, DECORATOR, DEPOSIT, ENTITY, LOOT, MANTLE, POST, TERRAIN; - - /** This seed of {@code world}, which must be a world Iris generates. */ - public long of(PackWorld world) { - if (world instanceof Source source) { - return source.seed(this); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); - } - - /** Iris's worlds answer for their seeds. */ - public interface Source { - long seed(IrisSeed seed); - } + BIOME, CARVE, COMPLEX, COMPONENT, DECORATOR, DEPOSIT, ENTITY, LOOT, MANTLE, POST, TERRAIN } diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java b/src/main/java/art/arcane/iris/builtin/IrisSeeds.java similarity index 53% rename from src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java rename to src/main/java/art/arcane/iris/builtin/IrisSeeds.java index 899f4b341..a2f6141a0 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/PlacementBinding.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeeds.java @@ -16,25 +16,12 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.placement; +package art.arcane.iris.builtin; -import java.util.function.Supplier; - -/** The placement bound to the placing thread. */ -final class PlacementBinding { - private static final ScopedValue CURRENT = ScopedValue.newInstance(); - - private PlacementBinding() { - } - - static ObjectPlacement current() { - if (!CURRENT.isBound()) { - throw new IllegalStateException("No Iris object placement is running on this thread"); - } - return CURRENT.get(); - } - - static T run(ObjectPlacement placement, Supplier body) { - return ScopedValue.where(CURRENT, placement).call(body::get); - } +/** + * The {@link IrisSeed}s of a world Iris generates, which it offers as an extension of the world: + * {@code world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE)}. + */ +public interface IrisSeeds { + long seed(IrisSeed seed); } diff --git a/src/main/java/art/arcane/iris/builtin/LiveWorld.java b/src/main/java/art/arcane/iris/builtin/LiveWorld.java index d52bc1d0f..64b5bd10e 100644 --- a/src/main/java/art/arcane/iris/builtin/LiveWorld.java +++ b/src/main/java/art/arcane/iris/builtin/LiveWorld.java @@ -24,7 +24,6 @@ import art.arcane.iris.builtin.spawn.SpawnCooldowns; import com.volmit.IrisFeature; import com.volmit.resource.ResourceId; import com.volmit.world.BlockPosition; -import com.volmit.world.PackWorld; import java.util.List; import java.util.Optional; @@ -36,22 +35,9 @@ import java.util.Set; * the layout through its {@link com.volmit.world.TerrainSampler}; a service has no chunk, so it asks here. * *

X and Z are world coordinates; Y is the height above the dimension's bottom, as everywhere in IrisApi. - * Safe to use from any thread. Reached through {@link #of(PackWorld)}. + * Safe to use from any thread. Iris offers it as an extension of its worlds: {@code world.extension(LiveWorld.class)}. */ public interface LiveWorld { - /** The live view of {@code world}, which must be a world Iris generates. */ - static LiveWorld of(PackWorld world) { - if (world instanceof Source source) { - return source.liveWorld(); - } - throw new IllegalArgumentException("Built-in modules work in worlds Iris generates, not " + world); - } - - /** Iris's worlds answer for their live view. */ - interface Source { - LiveWorld liveWorld(); - } - /** The platform's block Y of height 0, the dimension's bottom: a position's height plus this is its Y in the platform. */ int bottomY(); diff --git a/src/main/java/art/arcane/iris/builtin/MatterMantle.java b/src/main/java/art/arcane/iris/builtin/MatterMantle.java index 34ae03f93..4797970ea 100644 --- a/src/main/java/art/arcane/iris/builtin/MatterMantle.java +++ b/src/main/java/art/arcane/iris/builtin/MatterMantle.java @@ -20,34 +20,20 @@ package art.arcane.iris.builtin; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.matter.Matter; -import com.volmit.host.ReadOnlyMantle; -import com.volmit.mantle.Mantle; /** * Iris's mantle as the matter slices it stores, for the built-ins whose data the platform and the rest of Iris read as * slices rather than through a {@link com.volmit.mantle.MantleLayer}: caves ({@code MatterCavern}) and markers. The - * slices are VolmLib's own types, which a pack module may use as well; Iris's worlds implement this next to - * {@link Mantle}, and {@link #of(Mantle)} reaches it from an invocation's mantle. + * slices are VolmLib's own types, which a pack module may use as well. Iris offers it as an extension of its mantle and + * chunk invocations: {@code context.extension(MatterMantle.class)}. + * + *

A chunk invocation's matter mantle holds its own chunk only, which the stage may write, as a chunk stage writes the + * mantle of its own chunk; it reads its neighbours through {@link #loadedChunk} alone. * *

Heights are as the mantle stores them: above the dimension's bottom. A chunk the invocation reaches is pinned for * as long as the invocation runs; callers neither release it nor keep it afterwards. */ public interface MatterMantle { - /** - * The matter side of {@code mantle}, which must be a mantle Iris hands to its stages. A chunk stage's mantle is read-only - * to the stage; the matter behind it is not, and a built-in chunk stage that writes markers into it (the caves' floors and - * ceilings) is why this reaches through. - */ - static MatterMantle of(Mantle mantle) { - if (mantle instanceof ReadOnlyMantle readOnly) { - return of(readOnly.host()); - } - if (mantle instanceof MatterMantle matter) { - return matter; - } - throw new IllegalArgumentException("Built-in modules write Iris's own mantle, not " + mantle); - } - /** The mantle chunk at chunk coordinates {@code chunkX}, {@code chunkZ}, or null outside what the invocation reaches. */ MantleChunk chunk(int chunkX, int chunkZ); diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java index 9ee612265..56c8b50ea 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java @@ -25,6 +25,8 @@ import com.volmit.config.Feature; import com.volmit.config.LinkedBiomes; import com.volmit.config.Ref; import com.volmit.config.Reference; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Set; @@ -48,7 +50,7 @@ public final class CarvingBiomeSettings implements IrisFeature, LinkedBiomes { } @Override - public Set treeBiomes() { - return Set.of(biome()); + public Set treeBiomes(PackResources pack) { + return biome().isBlank() ? Set.of() : Set.of(pack.idOf(biome())); } } diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java index 3408c1cc6..997571a32 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java @@ -24,6 +24,8 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.LinkedBiomes; import com.volmit.config.MinItems; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Collection; import java.util.Collections; @@ -68,11 +70,11 @@ public final class CarvingSettings implements IrisFeature, LinkedBiomes { } @Override - public Set usedBiomes(Collection dimension) { - Set biomes = new LinkedHashSet<>(); + public Set usedBiomes(PackResources pack, Collection dimension) { + Set biomes = new LinkedHashSet<>(); for (CarvingEntry entry : entries()) { - if (entry != null && entry.enabled()) { - biomes.add(entry.biome()); + if (entry != null && entry.enabled() && entry.biome() != null && !entry.biome().isBlank()) { + biomes.add(pack.idOf(entry.biome())); } } return biomes; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java index fdff1ebfe..36a143829 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java @@ -25,6 +25,8 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.LinkedBiomes; import com.volmit.config.MinItems; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Collection; import java.util.Collections; @@ -56,15 +58,21 @@ public final class FloatingChildSettings implements IrisFeature, LinkedBiomes { } @Override - public Set usedBiomes(Collection dimension) { + public Set usedBiomes(PackResources pack, Collection dimension) { CarvingSettings carving = dimension.stream().filter(CarvingSettings.class::isInstance).map(CarvingSettings.class::cast).findFirst().orElse(null); - Set biomes = new LinkedHashSet<>(); + Set biomes = new LinkedHashSet<>(); for (FloatingChildBiome child : children()) { if (child != null) { - biomes.add(child.biome()); - biomes.add(carving == null ? child.carving() : carving.biomeOf(child.carving())); + addBiome(pack, biomes, child.biome()); + addBiome(pack, biomes, carving == null ? child.carving() : carving.biomeOf(child.carving())); } } return biomes; } + + private static void addBiome(PackResources pack, Set biomes, String key) { + if (key != null && !key.isBlank()) { + biomes.add(pack.idOf(key)); + } + } } diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java index e862eb7bd..939981af3 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java @@ -21,34 +21,17 @@ package art.arcane.iris.builtin.floating; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.volmlib.util.math.RNG; -import com.volmit.config.PackSettings; +import com.volmit.generation.InvocationContext; import com.volmit.resource.ResourceId; -import com.volmit.world.PackWorld; import java.util.Optional; /** * What {@code iris:floating} asks of Iris beyond the API: the biome of any column, a biome's own terrain height, the sky - * biome an island paints, and placing Iris objects against an island. Iris's worlds implement it; a module reaches it - * with {@link #of}. + * biome an island paints, and placing Iris objects against an island. Iris offers it as an extension of its worlds and + * of the settings of the pack it loads: {@code world.extension(FloatingHost.class)}. */ public interface FloatingHost { - /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ - static FloatingHost of(PackSettings settings) { - if (settings instanceof Source source) { - return source.floating(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); - } - - /** The host of {@code world}, which must be a world Iris generates. */ - static FloatingHost of(PackWorld world) { - if (world instanceof Source source) { - return source.floating(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); - } - /** The biome of the column's surface, the biome an island grows from; any column, not only the chunk's. */ ResourceId surfaceBiome(int worldX, int worldZ); @@ -70,24 +53,21 @@ public interface FloatingHost { /** {@code object} shrunk by {@code factor} (below 1), the variant picked with {@code random}. */ Optional shrink(PlaceableObject object, double factor, RNG random); - /** Places {@code object} floating free at the column, into the chunk the mantle is generating. */ - void placeFloating(PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, RNG random); + /** Places {@code object} floating free at the column, into the chunk the mantle invocation {@code context} generates. */ + void placeFloating(InvocationContext context, PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, + RNG random); /** - * Places {@code object} on an island's top, its lowest block at {@code y}, into the chunk the mantle is generating; nothing - * is written unless every block it writes is one {@code anchor} lets it write. + * Places {@code object} on an island's top, its lowest block at {@code y}, into the chunk the mantle invocation + * {@code context} generates; nothing is written unless every block it writes is one {@code anchor} lets it write. */ - void placeOnTop(PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement, IslandAnchor anchor, RNG random); + void placeOnTop(InvocationContext context, PlaceableObject object, int worldX, int y, int worldZ, + ObjectPlacement placement, IslandAnchor anchor, RNG random); /** * Places {@code object} upside down under an island, turned {@code yRotation} degrees about Y, as {@link #placeOnTop} does * on top. */ - void placeUnder(PlaceableObject object, int worldX, int y, int worldZ, int yRotation, ObjectPlacement placement, - IslandAnchor anchor, RNG random); - - /** A world that hands out its {@link FloatingHost}. */ - interface Source { - FloatingHost floating(); - } + void placeUnder(InvocationContext context, PlaceableObject object, int worldX, int y, int worldZ, int yRotation, + ObjectPlacement placement, IslandAnchor anchor, RNG random); } diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java index 85a02cd3e..90d41ce2e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java @@ -22,9 +22,8 @@ import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; -import com.volmit.config.PackSettings; +import com.volmit.generation.InvocationContext; import com.volmit.resource.ResourceId; -import com.volmit.world.PackWorld; import java.util.List; import java.util.Optional; @@ -32,25 +31,11 @@ import java.util.function.Function; /** * What {@code iris:objects} asks of Iris: the objects of the pack, how Iris scales and places them, and the layout around - * a world position. Iris's worlds implement it; a module reaches it with {@link #of}. Nothing here hands out the engine. + * a world position. Iris offers it as an extension of its worlds and of the settings of the pack it loads: + * {@code world.extension(ObjectHost.class)}, {@code settings.extension(ObjectHost.class)}. Nothing here hands out the + * engine. */ public interface ObjectHost { - /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ - static ObjectHost of(PackSettings settings) { - if (settings instanceof Source source) { - return source.objects(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); - } - - /** The host of {@code world}, which must be a world Iris generates. */ - static ObjectHost of(PackWorld world) { - if (world instanceof Source source) { - return source.objects(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); - } - /** Whether Iris's debug setting is on. */ boolean debugging(); @@ -66,8 +51,8 @@ public interface ObjectHost { /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ RNG chunkRandom(int chunkX, int chunkZ); - /** The chunk whose objects are being placed on this thread. */ - ObjectChunk chunk(); + /** The chunk whose objects the mantle invocation {@code context} places. */ + ObjectChunk chunk(InvocationContext context); /** The object of the pack that {@code key} names. */ Optional object(String key); @@ -119,11 +104,6 @@ public interface ObjectHost { record UpperObjects(ObjectSettings biome, ObjectSettings region, String biomeKey, String regionKey) { } - /** Iris's worlds answer for their objects. */ - interface Source { - ObjectHost objects(); - } - /** One region's or biome's declaration of settings. */ record Declaration(Level level, String key, F settings) { } diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java index 3e8ded0ac..de8532bbe 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java @@ -26,28 +26,17 @@ import com.volmit.resource.PackResources; import com.volmit.world.BlockPosition; import java.util.Optional; -import java.util.function.Supplier; /** * The object placement being run, as Iris's built-in placement stages see it: what is placed and with which settings, the * terrain it is placed on, and the few block operations that only the platform can do. Iris implements it for each - * placement and binds it to the placing thread while the placement graph runs; the stages read it through {@link #current()}. + * placement and offers it as an extension of the placement invocation: {@code context.extension(ObjectPlacement.class)}. * Heights are in the coordinates of the placement stages: above the dimension's bottom. *

* It never hands out an engine, pack data or a platform type; everything it answers is an IrisApi, VolmLib or * {@code art.arcane.iris.builtin} value. */ public interface ObjectPlacement { - /** The placement running on this thread. */ - static ObjectPlacement current() { - return PlacementBinding.current(); - } - - /** Runs {@code placement} with {@code inputs} as {@link #current()} on this thread. */ - static T runBound(ObjectPlacement inputs, Supplier placement) { - return PlacementBinding.run(inputs, placement); - } - ObjectShape object(); /** The settings as the caller passed them; the stages derive what they change (the rotation) themselves. */ diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java index 3455b23f6..b2bd0d8fe 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java @@ -17,40 +17,18 @@ */ package art.arcane.iris.builtin.structure; -import com.volmit.config.PackSettings; -import com.volmit.world.PackWorld; +import com.volmit.generation.InvocationContext; /** * What {@code iris:structure} asks of Iris: Iris places its jigsaw structures itself. The structure model (structures, * pools, pieces), the assembler that builds a structure from them and the locator that spreads them over the world are - * Iris's, shared with the jigsaw studio and the structure importers and exporters. Iris's worlds implement it; a module - * reaches it with {@link #of}. + * Iris's, shared with the jigsaw studio and the structure importers and exporters. Iris offers it as an extension of its + * worlds and of the settings of the pack it loads: {@code world.extension(StructureHost.class)}. */ public interface StructureHost { - /** The host of the world {@code settings} are the pack's of, which must be a world Iris generates. */ - static StructureHost of(PackSettings settings) { - if (settings instanceof Source source) { - return source.structures(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + settings); - } - - /** The host of {@code world}, which must be a world Iris generates. */ - static StructureHost of(PackWorld world) { - if (world instanceof Source source) { - return source.structures(); - } - throw new IllegalArgumentException("Built-in modules generate Iris's own worlds, not " + world); - } - - /** Places the structures that start in the chunk whose mantle this thread is generating. */ - void placeChunk(); + /** Places the structures that start in the chunk whose mantle the mantle invocation {@code context} generates. */ + void placeChunk(InvocationContext context); /** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */ int reach(); - - /** Iris's worlds answer for their structures. */ - interface Source { - StructureHost structures(); - } } diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java index a415ed931..916bc33fa 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java @@ -18,6 +18,7 @@ package art.arcane.iris.builtin.terrain; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; @@ -61,7 +62,7 @@ public final class TerrainPalettes { TerrainPalettes(PackWorld world) { this.world = world; - this.complexSeed = IrisSeed.COMPLEX.of(world); + this.complexSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPLEX); } /** The palettes of {@code world}. */ diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java index 366b6b415..eb2c3866a 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.terrain.OreSettings; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.FeatureSettings.Entry; @@ -49,7 +50,7 @@ final class OreWarmUp { OreWarmUp(PackWorld world, TerrainOres ores) { this.world = world; this.ores = ores; - this.root = new RNG(IrisSeed.COMPONENT.of(world) + ROOT_SEED_SALT); + this.root = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT) + ROOT_SEED_SALT); } void warm() { diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java index d68bb2432..4691b0ad7 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.terrain.OreSettings; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; @@ -36,7 +37,7 @@ final class TerrainOres { TerrainOres(PackWorld world) { this.resources = world.resources(); - this.terrainSeed = IrisSeed.TERRAIN.of(world); + this.terrainSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.TERRAIN); } /** The ores of {@code world}. */ diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index 2af428c30..03071bb1b 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.terrain.BedrockSettings; import art.arcane.iris.builtin.terrain.HideOresSettings; import art.arcane.iris.builtin.terrain.OreSettings; @@ -66,7 +67,7 @@ final class TerrainShaper { this.palettes = palettes; this.layers = layers; this.ores = ores; - this.rng = new RNG(IrisSeed.TERRAIN.of(world)); + this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.TERRAIN)); this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).entries().stream() .anyMatch(entry -> entry.level() != Level.DIMENSION); } diff --git a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java index 526ccb134..6d55fd58e 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java +++ b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.decorant.Decorator; @@ -59,7 +60,7 @@ public final class BiomeDecorators { this.world = world; this.resources = world.resources(); this.log = world.log(); - this.decoratorSeed = IrisSeed.DECORATOR.of(world); + this.decoratorSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.DECORATOR); } /** The world's decorators, kept in its state store. */ diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java index 272797c76..4f5682981 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; @@ -52,7 +53,7 @@ public final class DecorationScene { public static DecorationScene of(ChunkStageContext context) { Mantle mantle = context.mantle(); return new DecorationScene(context.hunk(BlockState.class), context.world().resources().blocks(), context.terrain(), - mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), IrisSeed.COMPONENT.of(context.world()), + mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), context.world().extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT), context.log()); } 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 index 715215451..a44bba695 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java @@ -77,7 +77,7 @@ public final class StructureGraphValidation { Set replacementOutputStructures = new LinkedHashSet<>(); Map> sampledVerticalEnvelopes = new LinkedHashMap<>(); PackStructureResolver resolver = new PackStructureResolver(data); - for (ResourceId id : data.getPackResources().ids(IrisStructure.class)) { + for (ResourceId id : data.getPackResources().ids(StructureResources.STRUCTURES)) { String structureKey = id.path(); if (structureKey.equals(LEGACY_INDEX_KEY) || (activeStructureKeys != null && !activeStructureKeys.contains(structureKey))) { continue; 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 index a3842ec4f..f65a38ae5 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java @@ -18,15 +18,18 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.core.modules.IrisPackWorld; 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; /** @@ -35,26 +38,32 @@ import java.util.Set; * {@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 new LinkedHashSet<>(StructureResources.structureKeysOf(pack)); + public Set structures(PackResources pack) { + return idsOf(pack, StructureResources.structureKeysOf(pack)); } @Override - public Set locatable(PackWorld world) { - return IrisStructureLocator.locatableEditableKeys(engine(world)); + public Set locatable(PackWorld world) { + return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(engine(world))); } @Override - public Set placed(PackWorld world) { - return IrisStructureLocator.placedKeysAndAliases(engine(world)); + public Set placed(PackWorld world) { + return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine(world))); } @Override - public LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks) { + 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())); @@ -64,6 +73,28 @@ public final class StructureLocating implements StructureLocator { } private static Engine engine(PackWorld world) { - return IrisPackWorld.of(world).engine(); + 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/StructureResources.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java index bb302a93a..a5504fa6c 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -87,7 +87,7 @@ public final class StructureResources { } IrisPackResources resources = data.getPackResources(); try { - return resources.find(kind.key(resources.idOf(key))).orElse(null); + return resources.find(kind, resources.idOf(key)).orElse(null); } catch (IllegalStateException failedToLoad) { return null; } @@ -99,6 +99,6 @@ public final class StructureResources { } private static List keys(PackResources pack, ResourceKind kind) { - return pack.ids(kind.type()).stream().map(ResourceId::path).toList(); + return pack.ids(kind).stream().map(ResourceId::path).toList(); } } 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 index b19815e41..5c7702f88 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java @@ -18,8 +18,6 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.core.modules.IrisPackSettings; -import art.arcane.iris.core.modules.IrisPackWorld; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.StructurePlacementGrid; @@ -64,7 +62,7 @@ public final class StructureVanillaStructures implements VanillaStructures { */ @Override public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { - Engine engine = IrisPackSettings.of(context.settings()).engine(); + 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); @@ -135,7 +133,7 @@ public final class StructureVanillaStructures implements VanillaStructures { } private static Engine engine(PackWorld world) { - return IrisPackWorld.of(world).engine(); + return world.extension(Engine.class).orElseThrow(); } private static Set structureIds(Set keys) { 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 index 04665da60..e2f29c440 100644 --- 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 @@ -19,6 +19,7 @@ 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; @@ -163,8 +164,8 @@ final class CarveFootprints { } } - /** The platform's start has no value equality, so the key pins the exact start a chunk carves against. */ - private record CarveFootprintKey(Object start, int padding) { + /** 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/FitStart.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java index bad24142e..9418d5350 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitStart.java @@ -21,6 +21,7 @@ package art.arcane.iris.engine.framework.structure.fit; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.engine.framework.structure.NativeStructureFit; import com.volmit.vanilla.DecorationStep; +import com.volmit.vanilla.StartKey; import com.volmit.vanilla.StructureFit; import com.volmit.vanilla.TerrainAdaptation; @@ -88,7 +89,7 @@ final class FitStart { return bounds; } - Object key() { + StartKey key() { return start.key(); } } diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java index d0b927e20..95a8df136 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/RigidSupport.java @@ -19,14 +19,13 @@ package art.arcane.iris.engine.framework.structure.fit; import com.volmit.block.BlockState; +import com.volmit.vanilla.StartKey; import com.volmit.vanilla.TemplateCells; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; -import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -52,7 +51,7 @@ final class RigidSupport { try { BatchCellBudget budget = new BatchCellBudget(); List requests = new ArrayList<>(); - Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); + Set seenStarts = new HashSet<>(); for (FitStart start : starts) { if (!SurfaceFitting.requiresSurfaceTerrain(start) || !seenStarts.add(start.key())) { continue; diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java index 9d773383d..f79d87e46 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -22,15 +22,14 @@ import art.arcane.iris.builtin.structure.StructureTerrainMode; import com.volmit.ModuleLog; import com.volmit.block.BlockState; import com.volmit.vanilla.DecorationStep; +import com.volmit.vanilla.StartKey; import com.volmit.vanilla.TemplateCells; import com.volmit.vanilla.TerrainAdaptation; import com.volmit.world.BlockPosition; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -222,7 +221,7 @@ final class SurfaceFitting { int maximumTemplateCells, ModuleLog log) { Box influenceArea = area.widened(SURFACE_TERRAIN_RADIUS); List anchors = new ArrayList<>(); - Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); + Set seenStarts = new HashSet<>(); for (FitStart start : starts) { if (!requiresSourceSurfaceTerrain(start) || !seenStarts.add(start.key())) { continue; @@ -288,7 +287,7 @@ final class SurfaceFitting { Map columnCaps = new HashMap<>(); Set foundationBases = new HashSet<>(); Set occupiedCells = new HashSet<>(); - Set seenStarts = Collections.newSetFromMap(new IdentityHashMap<>()); + Set seenStarts = new HashSet<>(); for (FitStart start : starts) { if (start.terrain().resolvedMode() != StructureTerrainMode.VACUUM || !seenStarts.add(start.key())) { continue; diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index d0c477bde..abaaa53c9 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -41,7 +41,7 @@ import java.util.concurrent.ConcurrentMap; public final class BlockDropping implements BlockDrops { @Override public Result drops(PackWorld world, Broken broken) { - LiveWorld live = LiveWorld.of(world); + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); int x = broken.position().x(); int y = broken.position().y(); int z = broken.position().z(); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 3f245d70a..5907586f4 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -19,12 +19,14 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.LiveWorld; import art.arcane.iris.builtin.LiveWorld.ObjectLoots; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootTable; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; +import com.volmit.resource.ResourceId; import com.volmit.service.Loot; import com.volmit.world.PackWorld; @@ -40,7 +42,7 @@ import java.util.Optional; public final class LootGiving implements Loot { @Override public List tables(PackWorld world, Site site) { - LiveWorld live = LiveWorld.of(world); + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); int x = site.position().x(); int z = site.position().z(); int relativeY = site.position().y(); @@ -49,11 +51,11 @@ public final class LootGiving implements Loot { List sources = new ArrayList<>(); boolean objectLootDefined = site.nativeLootDefined(); - Optional objectLoots = site.container() == null ? Optional.empty() : live.objectLoots(x, relativeY, z); + Optional objectLoots = site.container().isEmpty() ? Optional.empty() : live.objectLoots(x, relativeY, z); if (objectLoots.isPresent()) { objectLootDefined = objectLootDefined || objectLoots.get().defined(); Source picked = placementLoot(world, live).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(), - site.container(), rng, x, worldY, z); + site.container().get(), rng, x, worldY, z); if (picked != null) { sources.add(picked); if (objectLoots.get().overridesGlobalLoot()) { @@ -62,19 +64,20 @@ public final class LootGiving implements Loot { } } - LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined, Table::new); + LootTables.resolveEnvironmentSources(sources, world, rng, x, relativeY, z, objectLootDefined, + key -> new Table(world.resources().idOf(key))); return sources; } @Override - public List items(PackWorld world, Site site, String key) { - LootTable table = LootResources.table(world.resources(), key); + public List items(PackWorld world, Site site, ResourceId tableId) { + LootTable table = LootResources.table(world.resources(), tableId); if (table == null) { return List.of(); } - int worldY = site.position().y() + LiveWorld.of(world).bottomY(); + int worldY = site.position().y() + world.extension(LiveWorld.class).orElseThrow().bottomY(); return new LootItems(world.resources().items(), site.debug()) - .draw(key, table, lootSeed(world), site.position().x(), worldY, site.position().z()); + .draw(tableId.path(), table, lootSeed(world), site.position().x(), worldY, site.position().z()); } private static PlacementLoot placementLoot(PackWorld world, LiveWorld live) { @@ -82,6 +85,6 @@ public final class LootGiving implements Loot { } private static long lootSeed(PackWorld world) { - return IrisSeed.LOOT.of(world); + return world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.LOOT); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java index 3d825273f..366f53d0a 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootItems.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -32,6 +32,10 @@ import com.volmit.item.ItemRegistry; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalDouble; import java.util.OptionalInt; /** @@ -106,10 +110,18 @@ public final class LootItems { int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.minAmount(), entry.maxAmount())); List enchantments = drawEnchantments(entry, rng); List attributes = drawAttributes(entry, rng); - Double damage = maxDurability.getAsInt() > 0 ? 1D - rng.d(entry.minDurability(), entry.maxDurability()) : null; - return new ItemDrop(type, amount, entry.displayName(), entry.lore(), enchantments, attributes, - entry.unbreakable(), entry.itemFlags(), entry.customModel(), damage, entry.leatherColor(), - entry.dyeColor(), entry.customNbt(), debug ? sourceOf(entry, table) : null); + OptionalDouble damage = maxDurability.getAsInt() > 0 + ? OptionalDouble.of(1D - rng.d(entry.minDurability(), entry.maxDurability())) + : OptionalDouble.empty(); + return new ItemDrop(type, amount, Optional.ofNullable(entry.displayName()), entry.lore(), enchantments, attributes, + entry.unbreakable(), entry.itemFlags(), customModelOf(entry), damage, Optional.ofNullable(entry.leatherColor()), + Optional.ofNullable(entry.dyeColor()), Objects.requireNonNullElse(entry.customNbt(), Map.of()), + debug ? Optional.of(sourceOf(entry, table)) : Optional.empty()); + } + + private static OptionalInt customModelOf(LootEntry entry) { + Integer customModel = entry.customModel(); + return customModel == null ? OptionalInt.empty() : OptionalInt.of(customModel); } private static List drawEnchantments(LootEntry entry, RNG rng) { @@ -142,9 +154,9 @@ public final class LootItems { private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table) { if (table == null) { - return new ItemDrop.Source(null, 0, entry.rarity()); + return new ItemDrop.Source(Optional.empty(), 0, entry.rarity()); } - return new ItemDrop.Source(table.name(), table.rarity(), entry.rarity()); + return new ItemDrop.Source(Optional.ofNullable(table.name()), table.rarity(), entry.rarity()); } private static boolean isAir(String type) { diff --git a/src/main/java/art/arcane/iris/engine/loot/LootResources.java b/src/main/java/art/arcane/iris/engine/loot/LootResources.java index d0085a58f..226380a25 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootResources.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootResources.java @@ -49,8 +49,12 @@ public final class LootResources { if (key == null || key.isBlank()) { return null; } + return table(resources, resources.idOf(key)); + } + + public static LootTable table(PackResources resources, ResourceId id) { try { - return resources.find(TABLES.key(resources.idOf(key))).orElse(null); + return resources.find(TABLES, id).orElse(null); } catch (IllegalStateException failedToLoad) { return null; } @@ -58,6 +62,6 @@ public final class LootResources { /** The key of every loot table of the pack, in key order. */ public static List tableKeys(PackResources resources) { - return resources.ids(TABLES.type()).stream().map(ResourceId::path).toList(); + return resources.ids(TABLES).stream().map(ResourceId::path).toList(); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java index d40014994..a85432ac1 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootTables.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -83,7 +83,7 @@ public final class LootTables { boolean objectLootDefined, Function mapper ) { - LiveWorld live = LiveWorld.of(world); + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); boolean belowSurface = relativeY < live.terrainHeight(x, z); boolean distinctContextualBiome = belowSurface && !live.caveBiome(x, relativeY, z).equals(live.surfaceBiome(x, z)); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java index e1c1dc5cc..2bac6afc5 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootValidator.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootValidator.java @@ -55,7 +55,7 @@ public final class LootValidator implements Validator { private static List checkTables(PackResources resources) { List problems = new ArrayList<>(); - for (ResourceId id : resources.ids(LootTable.class)) { + for (ResourceId id : resources.ids(LootResources.TABLES)) { String lootKey = id.path(); List errors = new ArrayList<>(); LootTable table = readTable(resources, id, lootKey, errors); @@ -68,7 +68,7 @@ public final class LootValidator implements Validator { } private static List checkReferences(ValidationContext pack) { - Set lootIds = Set.copyOf(pack.resources().ids(LootTable.class)); + Set lootIds = Set.copyOf(pack.resources().ids(LootResources.TABLES)); List problems = new ArrayList<>(); List> declared = new ArrayList<>(pack.settings().declared(LootSettings.class).entries()); declared.sort(Comparator.comparing(Entry::level).thenComparing(Entry::source)); @@ -93,7 +93,7 @@ public final class LootValidator implements Validator { private static LootTable readTable(PackResources resources, ResourceId id, String key, List errors) { try { - return resources.find(LootResources.TABLES.key(id)).orElse(null); + return resources.find(LootResources.TABLES, id).orElse(null); } catch (IllegalStateException failedToLoad) { errors.add("Loot table '" + key + "' cannot be read: " + failedToLoad.getMessage()); return null; diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index 0e91f6e0f..21249e308 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -86,7 +86,7 @@ final class PlacementLoot { } private Loot.Source packSource(String key) { - return LootResources.table(resources, key) == null ? null : new Loot.Table(key); + return LootResources.table(resources, key) == null ? null : new Loot.Table(resources.idOf(key)); } private Loot.Source platformSource(String name, int x, int worldY, int z) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 950a5eb6d..1c5001d9b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -89,7 +89,7 @@ final class ChunkObjectPlacing { this.host = host; this.log = log; this.context = context; - this.chunk = host.chunk(); + this.chunk = host.chunk(context); this.terrain = context.terrain(); this.chunkX = context.chunkX(); this.chunkZ = context.chunkZ(); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 43b2ccf66..37e7878bf 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.FloatingHost; @@ -87,7 +88,8 @@ public final class FloatingObjectPlacing { /** The floating object placing of {@code world}. */ public static FloatingObjectPlacing of(PackWorld world, ModuleLog log) { return world.state(FloatingObjectPlacing.class, - generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), IrisSeed.MANTLE.of(generating), log)); + generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), + generating.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.MANTLE), log)); } /** Places what originates in the chunk of {@code context} into the mantle. */ @@ -101,7 +103,7 @@ public final class FloatingObjectPlacing { new FloatingIslandBoundarySampler(host::surfaceBiome), log); FloatingIslandSample.clearChunkMemo(); - Chunk chunk = new Chunk(minX, minZ, worldHeight, chunkRng, samples, sampleColumns(samples, minX, minZ)); + Chunk chunk = new Chunk(context, minX, minZ,worldHeight, chunkRng, samples, sampleColumns(samples, minX, minZ)); // The maps are lookup indices only. Iteration MUST follow the encounter order of the deterministic 0..255 column // scan: identity-hash order changes per JVM run, and the shared chunk random makes placement output depend on order. @@ -204,7 +206,7 @@ public final class FloatingObjectPlacing { continue; } int key = columns.get(rng.i(columns.size())); - host.placeFloating(picked.get(), chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng); + host.placeFloating(chunk.context, picked.get(),chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng); } } @@ -239,7 +241,7 @@ public final class FloatingObjectPlacing { int x = pickedX - footprint.tallestX(); int z = pickedZ - footprint.tallestZ(); int y = pickTopY + 1 - footprint.lowestSolidY(); - host.placeOnTop(object, x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng); + host.placeOnTop(chunk.context, object,x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng); } } @@ -266,7 +268,7 @@ public final class FloatingObjectPlacing { int x = invertedBaseX(chunk.minX, pickedXf, footprint, turn); int z = invertedBaseZ(chunk.minZ, pickedZf, footprint, turn); int y = invertedBaseY(pickBottomY, footprint, turn); - host.placeUnder(object, x, y, z, turn.yRotation(), placement, + host.placeUnder(chunk.context, object,x, y, z, turn.yRotation(), placement, IslandFace.bottom(chunk.resolver, entry, pickBottomY, chunk.worldHeight), rng); } } @@ -386,7 +388,8 @@ public final class FloatingObjectPlacing { /** How far, in blocks along X and Z, the floating objects of the pack {@code settings} describe may write beyond their chunk. */ public static int reach(PackSettings settings, ModuleLog log) { - Reach reach = new Reach(FloatingHost.of(settings), ObjectHost.of(settings), log); + Reach reach = new Reach(settings.extension(FloatingHost.class).orElseThrow(), + settings.extension(ObjectHost.class).orElseThrow(), log); int maxObjectExtent = MIN_REACH_BLOCKS; try { for (Entry declared : settings.declared(FloatingChildSettings.class)) { @@ -476,7 +479,7 @@ public final class FloatingObjectPlacing { } /** What one chunk's placements share: where it is, its random, and its columns' island samples. */ - private record Chunk(int minX, int minZ, int worldHeight, RNG rng, FloatingIslandSampleResolver resolver, - FloatingIslandSample[] samples) { + private record Chunk(MantleStageContext context, int minX, int minZ, int worldHeight, RNG rng, + FloatingIslandSampleResolver resolver, FloatingIslandSample[] samples) { } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index f058dd1d7..adc6abf81 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -23,12 +23,15 @@ import art.arcane.iris.builtin.objects.ObjectHost.Declaration; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import com.volmit.config.Level; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.service.ObjectsAt; import com.volmit.world.PackWorld; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; /** * How {@code iris:objects} tells Iris where its objects are: the objects the biome and region of a chunk would place, @@ -36,29 +39,36 @@ import java.util.Set; */ public final class ObjectLocating implements ObjectsAt { @Override - public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return ObjectPlacing.of(world).guess(chunkX, chunkZ); + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + return ObjectPlacing.of(world).guess(chunkX, chunkZ).stream() + .map(world.resources()::idOf) + .collect(Collectors.toCollection(LinkedHashSet::new)); } @Override - public PlacedBy placedBy(PackWorld world, String objectKey) { - Set biomes = new LinkedHashSet<>(); - Set regions = new LinkedHashSet<>(); - for (Declaration declaration : ObjectHost.of(world).declarations(ObjectSettings.class)) { - if (!placesObject(declaration.settings().objects(), objectKey)) { + public PlacedBy placedBy(PackWorld world, ResourceId object) { + PackResources resources = world.resources(); + Set biomes = new LinkedHashSet<>(); + Set regions = new LinkedHashSet<>(); + for (Declaration declaration : world.extension(ObjectHost.class).orElseThrow().declarations(ObjectSettings.class)) { + if (!placesObject(declaration.settings().objects(), resources, object)) { continue; } - (declaration.level() == Level.BIOME ? biomes : regions).add(declaration.key()); + (declaration.level() == Level.BIOME ? biomes : regions).add(resources.idOf(declaration.key())); } return new PlacedBy(biomes, regions); } - private static boolean placesObject(List placements, String objectKey) { + private static boolean placesObject(List placements, PackResources resources, ResourceId object) { for (ObjectPlacement placement : placements) { - if (placement != null && placement.carvingSupport().supportsSurface() && placement.place().contains(objectKey)) { + if (placement != null && placement.carvingSupport().supportsSurface() && names(placement, resources, object)) { return true; } } return false; } + + private static boolean names(ObjectPlacement placement, PackResources resources, ResourceId object) { + return placement.place().stream().anyMatch(key -> key != null && resources.idOf(key).equals(object)); + } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 8000bbced..63e55c13a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -79,6 +79,6 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { } private static int reach(PackSettings settings, ModuleLog log) { - return new PlacementReach(ObjectHost.of(settings), log).ofPack(settings); + return new PlacementReach(settings.extension(ObjectHost.class).orElseThrow(), log).ofPack(settings); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 53cae24f7..e4152abe8 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -56,7 +56,7 @@ public final class ObjectPlacing { /** The object placing of {@code world}. */ public static ObjectPlacing of(PackWorld world) { - return world.state(ObjectPlacing.class, generating -> new ObjectPlacing(ObjectHost.of(generating), generating.log())); + return world.state(ObjectPlacing.class, generating -> new ObjectPlacing(generating.extension(ObjectHost.class).orElseThrow(), generating.log())); } /** Places what originates in the chunk {@code context} generates. */ diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 5501701e0..529ff7dec 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -25,6 +25,7 @@ import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; @@ -48,8 +49,8 @@ final class ObjectWarmUp { private int warmed; ObjectWarmUp(PackWorld world) { - this.host = ObjectHost.of(world); - this.root = new RNG(IrisSeed.COMPONENT.of(world) + ROOT_SEED_SALT); + this.host = world.extension(ObjectHost.class).orElseThrow(); + this.root = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT) + ROOT_SEED_SALT); } void warm() { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 278492a78..ce5958210 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -51,10 +51,10 @@ public final class StructureModule implements IrisModule { } private static void place(MantleStageContext context) { - StructureHost.of(context.world()).placeChunk(); + context.world().extension(StructureHost.class).orElseThrow().placeChunk(context); } private static int reach(PackSettings settings) { - return StructureHost.of(settings).reach(); + return settings.extension(StructureHost.class).orElseThrow().reach(); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 2214ec445..98cfe5e30 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -41,6 +41,7 @@ import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; /** * How {@code iris:objects} grows trees: when a sapling grows, the tree comes from the tree placements of the biome and @@ -53,7 +54,7 @@ public final class TreeGrowing implements SaplingGrowth { @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { - ObjectHost host = ObjectHost.of(world); + ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); BlockPosition at = sapling.at(); TreeGrowthSettings growth = treeGrowth(host, at); if (!growth.enabled()) { @@ -72,12 +73,12 @@ public final class TreeGrowing implements SaplingGrowth { GrowthSink sink = new GrowthSink(surroundings, host); BlockPosition center = sapling.center(); host.placeInto(object, center.x(), center.y() + object.height() / 2, center.z(), placement.get(), sink, RNG.r); - return Optional.of(new Growth(object.key(), sink.placed())); + return Optional.of(new Growth(world.resources().idOf(object.key()), sink.placed())); } @Override public TreeObjects treeObjects(PackWorld world) { - ObjectHost host = ObjectHost.of(world); + ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); Set objects = new HashSet<>(); Set procedural = new HashSet<>(); for (Declaration declaration : host.declarations(ObjectSettings.class)) { @@ -86,7 +87,11 @@ public final class TreeGrowing implements SaplingGrowth { for (Declaration declaration : host.declarations(ProceduralObjectSettings.class)) { collectProceduralTrees(declaration.settings().trees(), procedural); } - return new TreeObjects(objects, procedural); + return new TreeObjects(idsOf(world, objects), idsOf(world, procedural)); + } + + private static Set idsOf(PackWorld world, Set keys) { + return keys.stream().map(world.resources()::idOf).collect(Collectors.toSet()); } private static TreeGrowthSettings treeGrowth(ObjectHost host, BlockPosition at) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 062ce3ad8..a6e850f3b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CarvingBiomeSettings; @@ -81,12 +82,12 @@ public final class CarveModule implements IrisModule { if (!carves(context)) { return; } - MatterMantle mantle = MatterMantle.of(context.mantle()); + MatterMantle mantle = context.extension(MatterMantle.class).orElseThrow(); caveCarving(context).carve(mantle, context.terrain(), context.chunkX(), context.chunkZ()); } private static void applyCaves(ChunkStageContext context) { - MatterMantle mantle = MatterMantle.of(context.mantle()); + MatterMantle mantle = context.extension(MatterMantle.class).orElseThrow(); Hunk blocks = context.hunk(BlockState.class); caveApplying(context).apply(mantle, context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context)); } @@ -114,7 +115,8 @@ public final class CarveModule implements IrisModule { /** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */ private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) { int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); - return new CarveWorld(world.resources().noise(), IrisSeed.CARVE.of(world), terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, + return new CarveWorld(world.resources().noise(), world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE), + terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, world.minHeight()); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 2ac4475fe..1230bf1f6 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -34,8 +34,6 @@ import com.volmit.block.BlockState; import com.volmit.hunk.Hunk; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; -import com.volmit.resource.ResourceKey; -import com.volmit.world.PackBiome; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; import lombok.Data; @@ -666,7 +664,7 @@ public class CaveApplying { private ResourceId existingBiomeId(String key) { ResourceId id = resources.idOf(key); try { - return resources.find(new ResourceKey<>(id, PackBiome.class)).isPresent() ? id : null; + return resources.find(PackResources.BIOMES, id).isPresent() ? id : null; } catch (IllegalStateException unreadable) { return null; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java index bae9f392d..587b9bdd0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java @@ -34,7 +34,7 @@ import java.util.Optional; */ public final class CaveBiomeBands implements CaveBiomes { @Override - public Optional overriddenBiome(PackWorld world, int x, int y, int z) { + public Optional overriddenBiome(PackWorld world, int x, int y, int z) { CarvingResolver resolver = CarvingResolver.of(world); ResolvedCarvingEntry rootEntry = resolver.rootEntryAt(y); if (rootEntry == null) { @@ -44,12 +44,12 @@ public final class CaveBiomeBands implements CaveBiomes { if (resolver.entryBiome(entry) == null) { return Optional.empty(); } - return Optional.of(entry.biomeKey().trim()); + return Optional.of(world.resources().idOf(entry.biomeKey().trim())); } @Override - public int minDepthBelowSurface(PackWorld world, String biomeKey) { - return Depths.of(world).minDepthBelowSurface(world.resources().idOf(biomeKey)); + public int minDepthBelowSurface(PackWorld world, ResourceId biome) { + return Depths.of(world).minDepthBelowSurface(biome); } /** The minimum depths the world's biomes declare ({@code caveMinDepthBelowSurface}), found by biome id. */ diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index c582696e7..646bcfd65 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositHeightDistribution; import art.arcane.iris.builtin.deposit.DepositPlacementScope; @@ -36,13 +37,11 @@ import com.volmit.config.FeatureSettings; import com.volmit.config.Level; import com.volmit.config.SettingsStack; import com.volmit.hunk.Hunk; -import com.volmit.mantle.MantleLayer; +import com.volmit.mantle.Mantle; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; -import com.volmit.resource.ResourceKey; import com.volmit.stage.ChunkStageContext; import com.volmit.world.BiomeSample; -import com.volmit.world.PackBiome; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; @@ -78,7 +77,7 @@ final class DepositPlacer { private final Map> biomeIdentities = new ConcurrentHashMap<>(); DepositPlacer(PackWorld world) { - this.rng = new RNG(IrisSeed.DEPOSIT.of(world)); + this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.DEPOSIT)); this.resources = world.resources(); this.registry = resources.blocks(); this.log = world.log(); @@ -112,7 +111,7 @@ final class DepositPlacer { } private Optional identityOf(ResourceId biome) { - return biomeIdentities.computeIfAbsent(biome, id -> resources.find(new ResourceKey<>(id, PackBiome.class)) + return biomeIdentities.computeIfAbsent(biome, id -> resources.find(PackResources.BIOMES, id) .map(found -> new BiomeIdentity(id.path(), found.platformBiome().toString(), found.vanillaBiome().toString()))); } @@ -121,7 +120,7 @@ final class DepositPlacer { private final Hunk blocks; private final TerrainSampler terrain; private final FeatureSettings settings; - private final MantleLayer caverns; + private final Mantle mantle; private final int originX; private final int originZ; private final int worldHeight; @@ -136,7 +135,7 @@ final class DepositPlacer { this.blocks = context.hunk(BlockState.class); this.terrain = context.terrain(); this.settings = context.settings(); - this.caverns = context.mantle().caverns(); + this.mantle = context.mantle(); this.originX = context.originX(); this.originZ = context.originZ(); this.worldHeight = blocks.getHeight(); @@ -250,7 +249,7 @@ final class DepositPlacer { continue; } - if (caverns.get(originX + nx, ny, originZ + nz) == null) { + if (!mantle.isCarved(originX + nx, ny, originZ + nz)) { BlockState ore = clump.blocks().get(j); BlockState remapped = remapped(nx, ny, nz, ore); BlockState finalBlock = remapped != null diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 7feaf2408..ab2469ccb 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; @@ -81,7 +82,7 @@ final class FloatingIslands { FloatingIslands(PackWorld world, ModuleLog log) { this.world = FloatingWorld.of(world); - this.rng = new RNG(IrisSeed.TERRAIN.of(world) ^ ISLAND_RANDOM_SALT); + this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.TERRAIN) ^ ISLAND_RANDOM_SALT); this.biomeLayers = BiomeLayers.of(world); this.log = log; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 76129afa0..40842aebe 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; import art.arcane.iris.builtin.post.PostProcessingWallsSettings; import art.arcane.iris.builtin.terrain.LayerBlocks; @@ -81,7 +82,7 @@ final class SurfaceSmoothing { this.terrain = context.terrain(); this.settings = context.settings(); this.layerBlocks = LayerBlocks.of(context.world()); - this.postRandom = new RNG(IrisSeed.POST.of(context.world())); + this.postRandom = new RNG(context.world().extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.POST)); this.originX = context.originX(); this.originZ = context.originZ(); this.planeWidth = blocks.getWidth() + 2; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index 8420cbebf..946b40478 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -62,7 +62,7 @@ public final class AnchorModule implements IrisModule { } private static AnchorHeight height(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); @@ -89,7 +89,7 @@ public final class AnchorModule implements IrisModule { private static AnchorHeight finalHeight(PlacementStageContext context) { int y = context.output(IrisStages.Anchor.HEIGHT).y() + context.output(IrisStages.Prepare.TRANSFORMS).randomY(); - ObjectPlacement.current().anchoredAt(y); + context.extension(ObjectPlacement.class).orElseThrow().anchoredAt(y); return new AnchorHeight(y); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 3180ccae8..b49124a67 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -92,7 +92,7 @@ public final class BlocksModule implements IrisModule { } private static void write(BlockStageContext context, WrittenBlocks written) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); @@ -198,7 +198,7 @@ public final class BlocksModule implements IrisModule { * where the marker either allows anything above or finds two blocks of air. */ private static void placeMarkers(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.markers().isEmpty() || !prepared.terrain().hasWorld()) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java index 660a49e4a..c795f2086 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -50,7 +50,7 @@ public final class BoreModule implements IrisModule { if (!settings.bore()) { return; } - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.FINAL).y()); PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); for (int x = volume.minX(); x <= volume.maxX(); x++) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 2ebe5d86b..3479bfc8a 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -72,7 +72,7 @@ public final class PrepareModule implements IrisModule { } private static ObjectRotation slope(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PlacementSettings settings = placement.settings(); ObjectRotation requested = settings.rotation(); boolean checksSlope = !settings.forcePlace() && !settings.slopeCondition().isDefault(); @@ -112,7 +112,7 @@ public final class PrepareModule implements IrisModule { } private static PreparedPlacement transforms(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PlacementSettings settings = placement.settings(); ObjectRotation rotation = context.output(IrisStages.Prepare.SLOPE); ObjectShape object = placement.object(); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 7880110af..6ea72b878 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -133,7 +133,7 @@ public final class StiltModule implements IrisModule { private final ErodeShape erode; private StiltColumns(PlacementStageContext context, PreparedPlacement prepared, StiltLayers layers) { - this.placement = ObjectPlacement.current(); + this.placement = context.extension(ObjectPlacement.class).orElseThrow(); this.prepared = prepared; this.context = context; this.config = prepared.settings(); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 90f9506f1..1b9723e71 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -91,7 +91,7 @@ public final class VacuumModule implements IrisModule { private Bend(PlacementStageContext context, PreparedPlacement prepared) { VacuumProfile vacuum = prepared.mode().vacuum(); - this.placement = ObjectPlacement.current(); + this.placement = context.extension(ObjectPlacement.class).orElseThrow(); this.prepared = prepared; this.terrain = prepared.terrain(); this.world = new PlacementWorld(context.access(), prepared.traits()); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 315cc4b89..38285335c 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -76,7 +76,7 @@ public final class ValidateModule implements IrisModule { } private static void checkSurface(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.forcePlace() || settings.fromBottom() || prepared.mode().has(PlaceTrait.FREE_HEIGHT)) { @@ -110,7 +110,7 @@ public final class ValidateModule implements IrisModule { } private static void checkLimits(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP)) { @@ -139,7 +139,7 @@ public final class ValidateModule implements IrisModule { return; } int y = context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY(); - if (meetsNativeStructure(context, ObjectPlacement.current(), prepared, y)) { + if (meetsNativeStructure(context, context.extension(ObjectPlacement.class).orElseThrow(), prepared, y)) { context.reject("native-structure"); } } @@ -198,7 +198,7 @@ public final class ValidateModule implements IrisModule { } private static void checkCollisions(PlacementStageContext context) { - ObjectPlacement placement = ObjectPlacement.current(); + ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP) diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index e5b36c9f4..30aa62036 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import com.volmit.ModuleLog; @@ -59,7 +60,7 @@ public final class CarvingResolver { this.resources = world.resources(); this.log = world.log(); this.minHeight = world.minHeight(); - this.childSeed = IrisSeed.CARVE.of(world) ^ CHILD_SEED_SALT; + this.childSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE) ^ CHILD_SEED_SALT; this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); this.index = indexById(entries); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index 9248d49bb..87ab09e23 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -24,7 +24,6 @@ import com.volmit.ModuleLog; import com.volmit.config.Range; import com.volmit.noise.NoiseSampler; import com.volmit.resource.PackResources; -import com.volmit.resource.ResourceKey; import com.volmit.world.PackBiome; import java.util.List; @@ -82,7 +81,7 @@ public final class ResolvedCarvingEntry { } try { - return resources.find(new ResourceKey<>(resources.idOf(biomeKey.trim()), PackBiome.class)).orElse(null); + return resources.find(PackResources.BIOMES, resources.idOf(biomeKey.trim())).orElse(null); } catch (IllegalStateException unreadable) { log.warnOnce("carving-biome:" + biomeKey, "The biome " + biomeKey + " of a carving entry cannot be loaded: " + unreadable.getMessage()); return null; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index 34d6991c7..aeb31e026 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveProfile; @@ -71,8 +72,10 @@ public final class FloatingWorld { } private static FloatingWorld create(PackWorld world) { - return new FloatingWorld(FloatingHost.of(world), ObjectHost.of(world), world.resources().noise(), IrisSeed.TERRAIN.of(world), - IrisSeed.CARVE.of(world), world.minHeight(), dimensionCarvingOf(world)); + IrisSeeds seeds = world.extension(IrisSeeds.class).orElseThrow(); + return new FloatingWorld(world.extension(FloatingHost.class).orElseThrow(), world.extension(ObjectHost.class).orElseThrow(), + world.resources().noise(), seeds.seed(IrisSeed.TERRAIN), seeds.seed(IrisSeed.CARVE), world.minHeight(), + dimensionCarvingOf(world)); } private static List dimensionCarvingOf(PackWorld world) { 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 index 916cfd828..24f593cf1 100644 --- 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 @@ -347,7 +347,7 @@ public class IrisDimension extends IrisRegistrant { } } - addReachableBiomeKeys(pending, getModuleSettings().usedBiomes(getModuleSettings())); + addReachableBiomeKeys(pending, getModuleSettings().usedBiomes(data.getPackResources(), getModuleSettings())); Set visited = new HashSet<>(); while (!pending.isEmpty()) { @@ -369,8 +369,8 @@ public class IrisDimension extends IrisRegistrant { visited.add(loadKey); biomes.put(loadKey, biome); addReachableBiomeKeys(pending, biome.getChildren()); - addReachableBiomeKeys(pending, biome.getModuleSettings().treeBiomes()); - addReachableBiomeKeys(pending, biome.getModuleSettings().usedBiomes(getModuleSettings())); + addReachableBiomeKeys(pending, biome.getModuleSettings().treeBiomes(data.getPackResources())); + addReachableBiomeKeys(pending, biome.getModuleSettings().usedBiomes(data.getPackResources(), getModuleSettings())); } return biomes.v(); 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 index 9cc5f0dc4..584ace764 100644 --- 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 @@ -153,7 +153,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { continue; } - names.addAll(biome.getModuleSettings().treeBiomes()); + names.addAll(biome.getModuleSettings().treeBiomes(g.getData().getPackResources())); b.put(biome.getLoadKey(), biome); names.addAll(biome.getChildren()); } @@ -250,7 +250,7 @@ public class IrisRegion extends IrisRegistrant implements IRare { continue; } - names.addAll(biome.getModuleSettings().treeBiomes()); + names.addAll(biome.getModuleSettings().treeBiomes(biome.getLoader().getPackResources())); b.put(biome.getLoadKey(), biome); names.addAll(biome.getChildren()); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java index 370847e79..678353b33 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -42,7 +42,7 @@ import java.util.Optional; public final class AmbientEffecting implements AmbientEffects { @Override public List due(PackWorld world, BlockPosition at) { - LiveWorld live = LiveWorld.of(world); + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers()); Optional sky = live.sky(); @@ -65,8 +65,8 @@ public final class AmbientEffecting implements AmbientEffects { } private static Effect play(AmbientEffect effect, Optional sky) { - Sound sound = effect.sound() == null ? null : soundOf(effect); - Particles particles = effect.particleEffect() == null ? null : particlesOf(effect); + Optional sound = effect.sound() == null ? Optional.empty() : Optional.of(soundOf(effect)); + Optional particles = effect.particleEffect() == null ? Optional.empty() : Optional.of(particlesOf(effect)); return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect)); } @@ -115,14 +115,14 @@ public final class AmbientEffecting implements AmbientEffects { return commands; } - private static Potion potionOf(AmbientEffect effect) { + private static Optional potionOf(AmbientEffect effect) { if (effect.potionStrength() <= -1) { - return null; + return Optional.empty(); } int shortest = Math.min(effect.potionTicksMax(), effect.potionTicksMin()); int longest = Math.max(effect.potionTicksMax(), effect.potionTicksMin()); - return new Potion(effect.potionEffect(), effect.potionStrength(), RNG.r.i(shortest, longest)); + return Optional.of(new Potion(effect.potionEffect(), effect.potionStrength(), RNG.r.i(shortest, longest))); } private static double commandOffset(double offset, boolean random) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index e934f61c3..b17b5a4e3 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -30,6 +30,8 @@ import art.arcane.volmlib.util.math.RNG; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.ArrayList; import java.util.List; @@ -43,12 +45,17 @@ final class EntityResolution { private static final long PASSENGER_STREAM_BASE = 234858L; private static final long LEASH_HOLDER_STREAM = 234548L; + private final PackResources resources; private final LootItems items; private final Optional sky; private final EffectTimers timers; - /** @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world */ - EntityResolution(LootItems items, Optional sky, EffectTimers timers) { + /** + * @param resources names the entity's loot tables by id + * @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world + */ + EntityResolution(PackResources resources, LootItems items, Optional sky, EffectTimers timers) { + this.resources = resources; this.items = items; this.sky = sky; this.timers = timers; @@ -62,21 +69,24 @@ final class EntityResolution { } List attributes = drawAttributes(entity, rng); - List lootTables = List.copyOf(entity.loot().tables()); + List lootTables = entity.loot().tables().stream().map(resources::idOf).toList(); long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong(); - EntitySpec leashHolder = entity.leashHolder() == null ? null : resolve(entity.leashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); + Optional leashHolder = entity.leashHolder() == null + ? Optional.empty() + : Optional.of(resolve(entity.leashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM))); EntitySpec.Equipment equipment = new EntitySpec.Equipment( equip(entity.helmet(), rng), equip(entity.chestplate(), rng), equip(entity.leggings(), rng), equip(entity.boots(), rng), equip(entity.mainHand(), rng), equip(entity.offHand(), rng)); - return new EntitySpec( - entity.type() == null ? "" : entity.type(), - entity.specialType() == null ? "" : entity.specialType(), - entity.reason(), - entity.customName() == null ? "" : entity.customName(), - flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, leashHolder, - spawnEffectOf(entity), entity.spawnEffectRiseOutOfGround(), entity.pandaMainGene(), - entity.pandaHiddenGene(), entity.applySettingsToCustomMobAnyways(), commandsOf(entity)); + return new EntitySpec(textOf(entity.type()), textOf(entity.specialType()), textOf(entity.reason()), + textOf(entity.customName()), flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, + leashHolder, spawnEffectOf(entity), entity.spawnEffectRiseOutOfGround(), textOf(entity.pandaMainGene()), + textOf(entity.pandaHiddenGene()), entity.applySettingsToCustomMobAnyways(), commandsOf(entity)); + } + + /** A text the pack may leave out or blank, as absent then. */ + private static Optional textOf(String text) { + return text == null || text.isBlank() ? Optional.empty() : Optional.of(text); } private static EntitySpec.Flags flagsOf(EntityDefinition entity) { @@ -100,23 +110,23 @@ final class EntityResolution { return attributes; } - private ItemDrop equip(LootEntry piece, RNG rng) { + private Optional equip(LootEntry piece, RNG rng) { if (piece == null || !LootResolver.oneIn(rng, piece.rarity())) { - return null; + return Optional.empty(); } - return items.give(piece, rng); + return Optional.ofNullable(items.give(piece, rng)); } /** The entity's spawn effect when it shows this time: an effect only shows now and then, as its interval and chance say. */ - private EntitySpec.SpawnEffect spawnEffectOf(EntityDefinition entity) { + private Optional spawnEffectOf(EntityDefinition entity) { AmbientEffect effect = entity.spawnEffect(); if (effect == null || !timers.shouldPlayNow(effect)) { - return null; + return Optional.empty(); } - return new EntitySpec.SpawnEffect(effect.sound(), effect.soundDistance(), effect.minPitch(), - effect.maxPitch(), effect.volume(), effect.particleEffect(), effect.particleOffset(), + return Optional.of(new EntitySpec.SpawnEffect(textOf(effect.sound()), effect.soundDistance(), effect.minPitch(), + effect.maxPitch(), effect.volume(), textOf(effect.particleEffect()), effect.particleOffset(), effect.particleCount(), effect.particleAltX(), effect.particleAltY(), effect.particleAltZ(), - effect.randomAltX(), effect.randomAltY(), effect.randomAltZ(), effect.extra()); + effect.randomAltX(), effect.randomAltY(), effect.randomAltZ(), effect.extra())); } private List commandsOf(EntityDefinition entity) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index f5ba8f655..29b3a4827 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.IrisSeed; +import art.arcane.iris.builtin.IrisSeeds; import art.arcane.iris.builtin.LiveWorld; import art.arcane.iris.builtin.LiveWorld.Level; import art.arcane.iris.builtin.loot.LootResolver; @@ -37,6 +38,7 @@ import art.arcane.volmlib.util.scheduling.ChronoLatch; import com.volmit.config.Range; import com.volmit.entity.EntitySpec; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.service.EntitySpawns; import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; @@ -76,15 +78,16 @@ public final class EntitySpawning implements EntitySpawns { if (count <= 0) { return; } - Spawner spawner = SpawnResources.spawner(world.resources(), plan.spawner()); + String spawnerKey = plan.spawner().path(); + Spawner spawner = SpawnResources.spawner(world.resources(), spawnerKey); if (spawner != null) { - SpawnerGate.spawned(plan.spawner(), spawner, LiveWorld.of(world), plan.chunkX(), plan.chunkZ()); + SpawnerGate.spawned(spawnerKey, spawner, world.extension(LiveWorld.class).orElseThrow(), plan.chunkX(), plan.chunkZ()); } } @Override - public Optional entity(PackWorld world, String key) { - EntityDefinition entity = SpawnResources.entity(world.resources(), key); + public Optional entity(PackWorld world, ResourceId id) { + EntityDefinition entity = SpawnResources.entity(world.resources(), id.path()); if (entity == null) { return Optional.empty(); } @@ -101,13 +104,13 @@ public final class EntitySpawning implements EntitySpawns { return Optional.empty(); } - List spawners = new ArrayList<>(); + List spawners = new ArrayList<>(); for (String key : marker.spawners()) { if (SpawnResources.spawner(world.resources(), key) == null) { world.log().error("Cannot load spawner: " + key + " for marker " + tag, null); continue; } - spawners.add(key); + spawners.add(world.resources().idOf(key)); } return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange())); } @@ -119,14 +122,14 @@ public final class EntitySpawning implements EntitySpawns { return; } PackResources resources = world.resources(); - LiveWorld.of(world).spawnCooldowns().forgetExpired(key -> { + world.extension(LiveWorld.class).orElseThrow().spawnCooldowns().forgetExpired(key -> { Spawner spawner = SpawnResources.spawner(resources, key); return spawner == null ? -1L : spawner.maximumRate().interval(); }); } private Optional planChunk(PackWorld world, Chunk chunk) { - LiveWorld live = LiveWorld.of(world); + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); Predicate canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), live, chunk.chunkX(), chunk.chunkZ()); int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); @@ -161,7 +164,7 @@ public final class EntitySpawning implements EntitySpawns { addAttempt(attempts, world, chosen, at, true); } } - return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(chosen.key(), chunk.chunkX(), chunk.chunkZ(), false, attempts)); + return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(world.resources().idOf(chosen.key()), chunk.chunkX(), chunk.chunkZ(), false, attempts)); } /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ @@ -182,7 +185,8 @@ public final class EntitySpawning implements EntitySpawns { } private Optional planMarker(PackWorld world, Marker marker) { - Spawner spawner = SpawnResources.spawner(world.resources(), marker.spawner()); + String spawnerKey = marker.spawner().path(); + Spawner spawner = SpawnResources.spawner(world.resources(), spawnerKey); SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker()); if (spawner == null) { return Optional.empty(); @@ -197,8 +201,8 @@ public final class EntitySpawning implements EntitySpawns { BlockPosition position = marker.position(); int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); - LiveWorld live = LiveWorld.of(world); - if (!SpawnerGate.canSpawn(marker.spawner(), spawner, live, chunkX, chunkZ)) { + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); + if (!SpawnerGate.canSpawn(spawnerKey, spawner, live, chunkX, chunkZ)) { return Optional.empty(); } @@ -210,7 +214,7 @@ public final class EntitySpawning implements EntitySpawns { List attempts = new ArrayList<>(); BlockPosition above = new BlockPosition(position.x(), position.y() + AIR_ABOVE_MARKER, position.z()); for (int i = 0; i < count; i++) { - addAttempt(attempts, world, new Candidate(marker.spawner(), spawner, spawn), above, false); + addAttempt(attempts, world, new Candidate(spawnerKey, spawner, spawn), above, false); } return attempts.isEmpty() ? Optional.empty() : Optional.of(new Plan(marker.spawner(), chunkX, chunkZ, exhaustsMarker, attempts)); } @@ -233,9 +237,9 @@ public final class EntitySpawning implements EntitySpawns { } private static EntityResolution resolution(PackWorld world) { - LiveWorld live = LiveWorld.of(world); + LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); LootItems items = new LootItems(world.resources().items(), live.studio()); - return new EntityResolution(items, live.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers())); + return new EntityResolution(world.resources(), items, live.sky(),world.state(EffectTimers.class, ignored -> new EffectTimers())); } private static EntityRandom entityRandom(PackWorld world) { @@ -270,7 +274,7 @@ public final class EntitySpawning implements EntitySpawns { private final RNG rng; private EntityRandom(PackWorld world) { - this.rng = new RNG(IrisSeed.ENTITY.of(world)); + this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.ENTITY)); } private RNG rng() { diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java index b90cd5232..9daa05eb6 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnResources.java @@ -100,7 +100,7 @@ public final class SpawnResources { return null; } try { - return resources.find(kind.key(resources.idOf(key))).orElse(null); + return resources.find(kind, resources.idOf(key)).orElse(null); } catch (IllegalStateException failedToLoad) { return null; } @@ -108,6 +108,6 @@ public final class SpawnResources { /** 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(PackResources resources, ResourceKind kind) { - return resources.ids(kind.type()).stream().map(ResourceId::path).toList(); + return resources.ids(kind).stream().map(ResourceId::path).toList(); } } From 9b94eecae3b7895c2dd351385a4da793fbfb6aa5 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 04:19:40 +0200 Subject: [PATCH 099/139] Move the built-in modules to the batch 4 API - BlocksModule writes through PlacementAccess.set(x, y, z, state) when a block has no block entity; WrittenBlocks keeps positions and states. - Hunk getters renamed to width(), height(), depth(). --- .../iris/builtin/blocks/WrittenBlocks.java | 35 ++++++++++++++----- .../iris/engine/actuator/DecorantModule.java | 8 ++--- .../iris/engine/actuator/TerrainShaper.java | 10 +++--- .../engine/decorator/DecorationScene.java | 2 +- .../iris/engine/decorator/DecoratorCore.java | 20 +++++------ .../decorator/IrisSeaSurfaceDecorator.java | 2 +- .../decorator/IrisShoreLineDecorator.java | 6 ++-- .../iris/engine/modifier/CaveApplying.java | 4 +-- .../iris/engine/modifier/DepositPlacer.java | 8 ++--- .../iris/engine/modifier/FloatingIslands.java | 2 +- .../iris/engine/modifier/MatterModule.java | 2 +- .../engine/modifier/PerfectionModule.java | 12 +++---- .../engine/modifier/SurfaceSmoothing.java | 14 ++++---- .../engine/object/placement/BlocksModule.java | 16 ++++----- .../object/placement/PlacementWorld.java | 15 ++++---- .../engine/object/placement/SnowModule.java | 4 +-- .../engine/object/placement/VacuumModule.java | 5 +-- 17 files changed, 93 insertions(+), 72 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java b/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java index df0c6d515..b7b9bec87 100644 --- a/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java +++ b/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java @@ -18,25 +18,44 @@ package art.arcane.iris.builtin.blocks; -import com.volmit.placement.PlacedBlock; +import com.volmit.block.BlockState; +import com.volmit.world.BlockPosition; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.function.BiConsumer; -/** The object's own blocks a placement wrote, in world positions, in the order they were written. */ +/** + * The object's own blocks a placement wrote, in world positions, in the order they were written. Positions and states + * are kept side by side, so recording a block allocates nothing beyond the position the placement already has. + */ public final class WrittenBlocks { - private final List blocks = new ArrayList<>(); + private final List positions = new ArrayList<>(); + private final List states = new ArrayList<>(); - public void add(PlacedBlock block) { - blocks.add(block); + public void add(BlockPosition position, BlockState state) { + positions.add(position); + states.add(state); } - public List blocks() { - return Collections.unmodifiableList(blocks); + public List positions() { + return Collections.unmodifiableList(positions); + } + + /** The written states, each at the index of its position in {@link #positions()}. */ + public List states() { + return Collections.unmodifiableList(states); + } + + /** Each written block's position and state, in the order they were written. */ + public void forEach(BiConsumer action) { + for (int index = 0; index < positions.size(); index++) { + action.accept(positions.get(index), states.get(index)); + } } public boolean isEmpty() { - return blocks.isEmpty(); + return positions.isEmpty(); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 6848c4fa6..2837c98ca 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -92,9 +92,9 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { int fluidHeight = scene.fluidHeight(); int worldHeight = scene.worldHeight(); - for (int i = 0; i < output.getWidth(); i++) { + for (int i = 0; i < output.width(); i++) { int realX = Math.round(x + i); - for (int j = 0; j < output.getDepth(); j++) { + for (int j = 0; j < output.depth(); j++) { int realZ = Math.round(z + j); DecoratedBiome biome = BiomeDecorators.biomeOf(settings, realX, realZ, terrain.surfaceKind(realX, realZ)); if (!decorators.hasDecorators(biome)) { @@ -103,7 +103,7 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { int height = terrain.surfaceHeight(realX, realZ); if (height >= 0 && height < fluidHeight && scene.isSolid(output.get(i, height, j)) - && height + 1 < output.getHeight() && scene.isWater(output.get(i, height + 1, j))) { + && height + 1 < output.height() && scene.isWater(output.get(i, height + 1, j))) { seaSurfaceDecorator.decorate(i, j, realX, Math.round(i + 1), Math.round(x + i - 1), realZ, Math.round(z + j + 1), Math.round(z + j - 1), @@ -120,7 +120,7 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { biome, height, worldHeight); } - if (height >= 0 && height < output.getHeight()) { + if (height >= 0 && height < output.height()) { surfaceDecorator.decorate(i, j, realX, realZ, biome, height, worldHeight - height); } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index 03071bb1b..22dc64da6 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -75,7 +75,7 @@ final class TerrainShaper { /** Fills the 16 x 16 columns of the chunk, one slice along x at a time. */ void shape(ChunkStageContext context) { Chunk chunk = new Chunk(context); - for (int sliceX = 0; sliceX < chunk.blocks.getWidth(); sliceX++) { + for (int sliceX = 0; sliceX < chunk.blocks.width(); sliceX++) { shapeSliver(chunk, sliceX); } } @@ -83,8 +83,8 @@ final class TerrainShaper { /** One plane from the sky to bedrock, one block thick along x. */ private void shapeSliver(Chunk chunk, int xf) { Hunk h = chunk.blocks; - int chunkHeight = h.getHeight(); - int chunkDepth = h.getDepth(); + int chunkHeight = h.height(); + int chunkDepth = h.depth(); int realX = xf + chunk.originX; for (int zf = 0; zf < chunkDepth; zf++) { @@ -192,7 +192,7 @@ final class TerrainShaper { /** The upper dimension's ground, filled in from the top of the column down to where it ends. */ private void fillUpperDimension(Chunk chunk, UpperDimension upper, int xf, int zf, int realX, int realZ) { Hunk h = chunk.blocks; - int chunkHeight = h.getHeight(); + int chunkHeight = h.height(); OptionalInt upperY = chunk.terrain.upperDimensionY(realX, realZ); if (upperY.isEmpty()) { return; @@ -273,7 +273,7 @@ final class TerrainShaper { this.settings = context.settings(); this.originX = context.originX(); this.originZ = context.originZ(); - this.clampedFluidHeight = Math.min(blocks.getHeight(), terrain.fluidHeight()); + this.clampedFluidHeight = Math.min(blocks.height(), terrain.fluidHeight()); int centreX = context.centreX(); int centreZ = context.centreZ(); this.bedrockEnabled = settings.at(BedrockSettings.class, centreX, centreZ).dimension().map(BedrockSettings::bedrock).orElse(true); diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java index 4f5682981..a62a71add 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -95,7 +95,7 @@ public final class DecorationScene { /** The height of the chunk's volume. */ public int worldHeight() { - return blocks.getHeight(); + return blocks.height(); } public int fluidHeight() { diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java index 0dee08c3f..bdd365d71 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -109,7 +109,7 @@ final class DecoratorCore { int x, int z, int realX, int height, int realZ, boolean underwater, boolean caveSkipFluid) { Hunk data = scene.blocks(); - if (height < 0 || height >= data.getHeight()) { + if (height < 0 || height >= data.height()) { return; } @@ -154,7 +154,7 @@ final class DecoratorCore { } int targetY = height + 1; - if (bd != null && targetY < data.getHeight() && scene.isAir(data.get(x, targetY, z))) { + if (bd != null && targetY < data.height() && scene.isAir(data.get(x, targetY, z))) { data.set(x, targetY, z, fixFacesForHunk(scene, bd, x, z, realX, targetY, realZ)); } } @@ -174,7 +174,7 @@ final class DecoratorCore { static void placeStackUp(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ, int height, int max, PlaceOpts opts) { Hunk data = scene.blocks(); - if (height < 0 || height >= data.getHeight()) { + if (height < 0 || height >= data.height()) { return; } @@ -187,7 +187,7 @@ final class DecoratorCore { if (stack == 1) { int targetY = height + 1; - if (targetY >= data.getHeight()) { + if (targetY >= data.height()) { return; } @@ -227,7 +227,7 @@ final class DecoratorCore { break; } - if (height + 1 + i >= data.getHeight()) { + if (height + 1 + i >= data.height()) { break; } @@ -249,7 +249,7 @@ final class DecoratorCore { static void placeStackDown(ResolvedDecorator decorator, DecorationScene scene, int x, int z, int realX, int realZ, int height, int minHeight, int max, PlaceOpts opts) { Hunk data = scene.blocks(); - if (height < 0 || height >= data.getHeight()) { + if (height < 0 || height >= data.height()) { return; } @@ -323,7 +323,7 @@ final class DecoratorCore { return; } - if (max > 1 && height + 1 < data.getHeight()) { + if (max > 1 && height + 1 < data.height()) { data.set(xf, height + 1, zf, bd); } } @@ -342,7 +342,7 @@ final class DecoratorCore { int placed = 0; for (int i = 0; i < stack; i++) { int h = height + 1 + i; - if (h >= height + max || h >= data.getHeight()) { + if (h >= height + max || h >= data.height()) { break; } double threshold = stack == 1 ? 0.0 : ((double) i) / (stack - 1); @@ -393,7 +393,7 @@ final class DecoratorCore { int xx = rX + face.dx(); int zz = rZ + face.dz(); - if (xx < 0 || xx > CHUNK_LAST || zz < 0 || zz > CHUNK_LAST || yy < 0 || yy >= hunk.getHeight()) { + if (xx < 0 || xx > CHUNK_LAST || zz < 0 || zz > CHUNK_LAST || yy < 0 || yy >= hunk.height()) { continue; } @@ -430,7 +430,7 @@ final class DecoratorCore { private static boolean canPlaceTwoBlockPlant(DecorationScene scene, int x, int z, int lowerY, int upperY, boolean caveSkipFluid) { Hunk data = scene.blocks(); - if (lowerY < 0 || upperY >= data.getHeight()) { + if (lowerY < 0 || upperY >= data.height()) { return false; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java index 42f7574a2..e5b1fd4e6 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisSeaSurfaceDecorator.java @@ -56,7 +56,7 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { if (stack == 1) { int targetY = height + 1; - if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { return; } diff --git a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java index 667807d2e..36218b994 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/IrisShoreLineDecorator.java @@ -60,7 +60,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { if (!decorator.isStacking()) { int targetY = height + 1; - if (targetY >= data.getHeight() + if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { return; } @@ -80,7 +80,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { if (stack == 1) { int targetY = height + 1; - if (targetY >= data.getHeight() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { + if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { return; } @@ -94,7 +94,7 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator { for (int i = 0; i < stack; i++) { int h = height + i; int targetY = h + 1; - if (targetY >= data.getHeight() + if (targetY >= data.height() || !DecoratorCore.canReplaceStackTarget(scene, data.get(x, targetY, z), false)) { break; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 1230bf1f6..5d0f54a6f 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -273,7 +273,7 @@ public class CaveApplying { // Surface-break carving must not leave an ore cap suspended across the opening. for (int columnIndex = 0; columnIndex < surfaceHeights.length; columnIndex++) { int surfaceY = surfaceHeights[columnIndex]; - if (surfaceY <= 0 || surfaceY >= output.getHeight()) { + if (surfaceY <= 0 || surfaceY >= output.height()) { continue; } @@ -540,7 +540,7 @@ public class CaveApplying { } private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map customBiomeCache) { - int maxY = output.getHeight(); + int maxY = output.height(); if (zone.ceiling + 1 < maxY && classes.isDecorant(output.get(rx, zone.ceiling + 1, rz))) { output.set(rx, zone.ceiling + 1, rz, caveAir); diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 646bcfd65..e1d5cf66e 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -138,7 +138,7 @@ final class DepositPlacer { this.mantle = context.mantle(); this.originX = context.originX(); this.originZ = context.originZ(); - this.worldHeight = blocks.getHeight(); + this.worldHeight = blocks.height(); this.minWorldY = terrain.minWorldY(); } @@ -413,9 +413,9 @@ final class DepositPlacer { } private static boolean isAirAt(Hunk data, int x, int y, int z, Predicate isAir) { - if (x < 0 || x >= data.getWidth() - || y < 0 || y >= data.getHeight() - || z < 0 || z >= data.getDepth()) { + if (x < 0 || x >= data.width() + || y < 0 || y >= data.height() + || z < 0 || z >= data.depth()) { return false; } return isAir.test(data.get(x, y, z)); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index ab2469ccb..5d67f800a 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -448,7 +448,7 @@ final class FloatingIslands { this.originX = context.originX(); this.originZ = context.originZ(); this.output = context.hunk(BlockState.class); - this.height = output.getHeight(); + this.height = output.height(); this.blocks = context.world().resources().blocks(); this.settings = context.settings(); this.explosion = PaletteExplosion.of(settings, context.centreX(), context.centreZ()); diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java index d8f8af0ad..467fc1e61 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -57,7 +57,7 @@ public final class MatterModule implements IrisModule { int originZ = context.originZ(); Hunk blocks = context.hunk(BlockState.class); int[] limits = upperLimits(context.terrain(), originX, originZ); - BlockBox chunk = new BlockBox(originX, 0, originZ, originX + CHUNK_WIDTH, blocks.getHeight(), originZ + CHUNK_WIDTH); + BlockBox chunk = new BlockBox(originX, 0, originZ, originX + CHUNK_WIDTH, blocks.height(), originZ + CHUNK_WIDTH); context.mantle().blocks().visit(chunk, (x, y, z, block) -> { int localX = x - originX; int localZ = z - originZ; diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index dae38916a..cfe52366b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -77,9 +77,9 @@ public final class PerfectionModule implements IrisModule { /** {@code hidden} remembers per state instance what it is hidden as, itself for a block that is no ore. */ private static void hideOres(Hunk blocks, Map hidden) { - for (int x = 0; x < blocks.getWidth(); x++) { - for (int z = 0; z < blocks.getDepth(); z++) { - for (int y = blocks.getHeight() - 1; y >= 0; y--) { + for (int x = 0; x < blocks.width(); x++) { + for (int z = 0; z < blocks.depth(); z++) { + for (int y = blocks.height() - 1; y >= 0; y--) { BlockState block = blocks.get(x, y, z); BlockState shown = hidden.computeIfAbsent(block, state -> ORE_BASES.getOrDefault(state.material(), state)); if (shown != block) { @@ -98,8 +98,8 @@ public final class PerfectionModule implements IrisModule { /** One pass over every column; whether it removed anything. */ boolean removeUnsupportedDecorants() { boolean removed = false; - for (int x = 0; x < blocks.getWidth(); x++) { - for (int z = 0; z < blocks.getDepth(); z++) { + for (int x = 0; x < blocks.width(); x++) { + for (int z = 0; z < blocks.depth(); z++) { for (int surface : surfaces(x, z)) { removed |= removeIfUnsupported(x, surface, z); } @@ -149,7 +149,7 @@ public final class PerfectionModule implements IrisModule { } private int topSolid(int x, int z) { - for (int y = blocks.getHeight() - 1; y >= 0; y--) { + for (int y = blocks.height() - 1; y >= 0; y--) { if (isSolid(blocks.get(x, y, z))) { return y; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 40842aebe..f098cabdd 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -85,7 +85,7 @@ final class SurfaceSmoothing { this.postRandom = new RNG(context.world().extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.POST)); this.originX = context.originX(); this.originZ = context.originZ(); - this.planeWidth = blocks.getWidth() + 2; + this.planeWidth = blocks.width() + 2; this.heights = heightPlane(); this.walls = enabled(context, PostProcessingWallsSettings.class, PostProcessingWallsSettings::enabled, PostProcessingWallsSettings.DEFAULT_ENABLED); this.slabs = enabled(context, PostProcessingSlabsSettings.class, PostProcessingSlabsSettings::enabled, PostProcessingSlabsSettings.DEFAULT_ENABLED); @@ -98,8 +98,8 @@ final class SurfaceSmoothing { } private void smoothColumns() { - for (int i = 0; i < blocks.getWidth(); i++) { - for (int j = 0; j < blocks.getDepth(); j++) { + for (int i = 0; i < blocks.width(); i++) { + for (int j = 0; j < blocks.depth(); j++) { post(i, j); } } @@ -127,8 +127,8 @@ final class SurfaceSmoothing { } private int[] heightPlane() { - int width = blocks.getWidth(); - int depth = blocks.getDepth(); + int width = blocks.width(); + int depth = blocks.depth(); int[] plane = new int[planeWidth * (depth + 2)]; for (int j = -1; j <= depth; j++) { boolean edge = j == -1 || j == depth; @@ -346,7 +346,7 @@ final class SurfaceSmoothing { private void set(int x, int y, int z, BlockState block) { int localX = x - originX; int localZ = z - originZ; - if (localX < 0 || localZ < 0 || localX >= blocks.getWidth() || localZ >= blocks.getDepth() || y < 0 || y >= blocks.getHeight()) { + if (localX < 0 || localZ < 0 || localX >= blocks.width() || localZ >= blocks.depth() || y < 0 || y >= blocks.height()) { return; } blocks.set(localX, y, localZ, block); @@ -358,7 +358,7 @@ final class SurfaceSmoothing { * opposite edge. */ private BlockState get(int x, int y, int z) { - return blocks.get(clamp(x - originX, blocks.getWidth()), clamp(y, blocks.getHeight()), clamp(z - originZ, blocks.getDepth())); + return blocks.get(clamp(x - originX, blocks.width()), clamp(y, blocks.height()), clamp(z - originZ, blocks.depth())); } private static int clamp(int value, int size) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index b49124a67..5dde7efcd 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -40,7 +40,6 @@ import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.object.BlockEntityData; import com.volmit.object.ObjectBlock; -import com.volmit.placement.PlacedBlock; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; import com.volmit.world.BlockPosition; @@ -133,9 +132,10 @@ public final class BlocksModule implements IrisModule { if (!shouldWrite(world, data, x, y, z, structurePiece)) { return; } - PlacedBlock placed = world.set(x, y, z, data, blockEntity); - placement.objectBlockWritten(placed.position()); - written.add(placed); + world.set(x, y, z, data, blockEntity); + BlockPosition position = new BlockPosition(x, y, z); + placement.objectBlockWritten(position); + written.add(position, data); } /** The object block as Iris places it: debug air shows where smart boring bored, and leaves never decay where the placer prevents it. */ @@ -230,11 +230,11 @@ public final class BlocksModule implements IrisModule { private static KList candidates(WrittenBlocks written, MarkerRule rule, ObjectPlacement placement) { KList candidates = new KList<>(); - for (PlacedBlock block : written.blocks()) { - if (rule.targets().stream().anyMatch(target -> marks(placement, rule, target, block.state()))) { - candidates.add(block.position()); + written.forEach((position, state) -> { + if (rule.targets().stream().anyMatch(target -> marks(placement, rule, target, state))) { + candidates.add(position); } - } + }); return candidates; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java index 3e06a34f5..bcb736486 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java @@ -50,13 +50,16 @@ final class PlacementWorld { return has(get(x, y, z), BlockTrait.SOLID); } - PlacedBlock set(int x, int y, int z, BlockState state) { - return set(x, y, z, state, Optional.empty()); + void set(int x, int y, int z, BlockState state) { + access.set(x, y, z, state); } - PlacedBlock set(int x, int y, int z, BlockState state, Optional blockEntity) { - PlacedBlock block = new PlacedBlock(new BlockPosition(x, y, z), state, blockEntity); - access.set(block); - return block; + /** A block entity needs the record; a plain block takes the write that allocates nothing. */ + void set(int x, int y, int z, BlockState state, Optional blockEntity) { + if (blockEntity.isEmpty()) { + access.set(x, y, z, state); + return; + } + access.set(new PlacedBlock(new BlockPosition(x, y, z), state, blockEntity)); } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java index 4bba49b6f..29dd41c01 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -26,7 +26,6 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; import com.volmit.block.BlockState; -import com.volmit.placement.PlacedBlock; import com.volmit.stage.PlacementStageContext; import com.volmit.world.BlockPosition; @@ -76,8 +75,7 @@ public final class SnowModule implements IrisModule { /** The highest written block of each column, columns in the order they were first written. */ private static Map columnTops(WrittenBlocks written) { Map tops = new LinkedHashMap<>(); - for (PlacedBlock block : written.blocks()) { - BlockPosition position = block.position(); + for (BlockPosition position : written.positions()) { tops.merge(columnKey(position), position, (current, next) -> next.y() > current.y() ? next : current); } return tops; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 1b9723e71..0e450ea51 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -33,6 +33,7 @@ import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.stage.PlacementStageContext; +import com.volmit.world.BlockPosition; /** * Module {@code iris:vacuum}: bends the terrain around an object of a vacuum mode so it meets the object's @@ -68,8 +69,8 @@ public final class VacuumModule implements IrisModule { if (!prepared.mode().bendsTerrain() || written.isEmpty() || !prepared.terrain().hasWorld()) { return; } - int baseY = written.blocks().stream().mapToInt(block -> block.position().y()).min().orElseThrow(); - int topY = written.blocks().stream().mapToInt(block -> block.position().y()).max().orElseThrow(); + int baseY = written.positions().stream().mapToInt(BlockPosition::y).min().orElseThrow(); + int topY = written.positions().stream().mapToInt(BlockPosition::y).max().orElseThrow(); new Bend(context, prepared).apply(baseY, topY); } From 136f57fa73db464e678590bb3373ef378e5c9206 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 04:46:44 +0200 Subject: [PATCH 100/139] Batch 5 of the API review: build the built-ins against the Iris API alone IrisModule is a Gradle Java build of its own. Its compile classpath is com.volmit:iris-api (never iris-host), VolmLib (sibling checkout or the published coordinate, as Iris resolves it), Gson, Lombok and the JDK, all compileOnly, with Iris's compiler options and Lombok config. check compiles every source and builds build/libs/iris-builtins.jar from these classes with IrisApi's ModuleJarCheck; the jar is byte-identical to the one Iris built before. Iris consumes it through the capability art.arcane:iris-builtins. The 111 sources that need Iris itself move to Iris core: the layout model (biomes, regions, dimensions and their types, generators, noise styles, expressions, images and image maps), the pack's objects, blocks and matter objects, mods and compat filters, the structure model with its assembler, locator, fitting and placer (behind StructureHost), and the object placers behind ObjectHost and FloatingHost. Nothing left here reaches Iris core, engine, platform or util. source-patterns.txt and the tasks that ran Iris's build (checkBuiltins, packageBuiltinModulesInIris, builtinSourcesJar) are gone. --- README.md | 52 +- build.gradle.kts | 193 ++- gradle.properties | 3 + lombok.config | 5 +- settings.gradle.kts | 42 +- source-patterns.txt | 19 - .../framework/IrisStructureLocator.java | 1322 ---------------- .../iris/engine/framework/PlacedObject.java | 37 - .../framework/PlacedStructurePiece.java | 54 - .../engine/framework/StructureAssembler.java | 1358 ----------------- .../StructureCaveAnchorResolver.java | 360 ----- .../framework/StructurePlacementScope.java | 115 -- .../structure/CompiledStructureGraph.java | 101 -- .../structure/IrisObjectFrameReader.java | 386 ----- .../structure/JigsawPoolSelection.java | 104 -- .../NativeReplacementValidation.java | 392 ----- .../structure/NativeStartPlanner.java | 172 --- .../PlanarJigsawWorkcellResolver.java | 139 -- .../structure/StructureAssemblyResult.java | 71 - .../structure/StructureGraphCatalog.java | 97 -- .../structure/StructureGraphCompilation.java | 242 --- .../structure/StructureGraphCompiler.java | 1264 --------------- .../structure/StructureGraphResolver.java | 74 - .../structure/StructureGraphValidation.java | 324 ---- .../structure/StructureLocating.java | 100 -- .../StructureResourceBundleGraphCompiler.java | 201 --- .../structure/StructureResources.java | 104 -- .../structure/StructureValidator.java | 92 -- .../structure/StructureVanillaStructures.java | 163 -- .../structure/fit/CarveFootprints.java | 173 --- .../structure/fit/StructureFitting.java | 129 -- .../structure/fit/TerrainIntegration.java | 633 -------- .../engine/image/CompiledIrisImageMap.java | 424 ----- .../engine/image/IrisImageMapCompiler.java | 825 ---------- .../engine/image/IrisImageMapMaskSampler.java | 113 -- .../engine/image/IrisImageMapRuntime.java | 386 ----- .../CaveObjectPlacementTransaction.java | 286 ---- .../FloatingObjectPlacementTransaction.java | 211 --- .../components/GoldenDebugObjectPlacer.java | 161 -- .../mantle/components/IslandAnchorPlacer.java | 128 -- .../components/StructureCarveEnvelope.java | 147 -- .../components/StructureCarvingFootprint.java | 456 ------ .../StructureFoundationPlanner.java | 79 - .../mantle/components/StructurePlacing.java | 685 --------- .../annotations/RegistryListFunction.java | 18 - .../functions/ComponentFlagFunction.java | 30 - .../functions/LootTableKeyFunction.java | 23 - .../object/compatibility/IrisCompat.java | 381 ----- .../IrisCompatabilityBlockFilter.java | 72 - .../IrisCompatabilityItemFilter.java | 69 - .../iris/engine/object/image/IrisImage.java | 168 -- .../engine/object/image/IrisImageMap.java | 120 -- .../object/image/IrisImageMapBinding.java | 29 - .../material/BlockDataMergeSupport.java | 75 - .../engine/object/material/IrisBlockData.java | 237 --- .../object/material/IrisMaterialPalette.java | 203 --- .../iris/engine/object/mod/IrisMod.java | 120 -- .../object/mod/IrisModBiomeInjector.java | 51 - .../object/mod/IrisModBiomeReplacer.java | 50 - .../object/mod/IrisModNoiseStyleReplacer.java | 49 - .../IrisModObjectPlacementBiomeInjector.java | 50 - .../IrisModObjectPlacementRegionInjector.java | 50 - .../object/mod/IrisModObjectReplacer.java | 50 - .../object/mod/IrisModRegionReplacer.java | 50 - .../object/noise/IrisGeneratorStyle.java | 278 ---- .../engine/object/noise/IrisInterpolator.java | 84 - .../object/noise/IrisNoiseGenerator.java | 212 --- .../noise/IrisShapedGeneratorStyle.java | 85 -- .../engine/object/noise/IrisStyledRange.java | 72 - .../iris/engine/object/noise/NoiseStyle.java | 566 ------- .../noise/expression/IrisExpression.java | 138 -- .../expression/IrisExpressionFunction.java | 110 -- .../noise/expression/IrisExpressionLoad.java | 187 --- .../object/placement/DecayControlPlacer.java | 108 -- .../placement/FloatingObjectFootprint.java | 171 --- .../object/placement/IObjectPlacer.java | 63 - .../object/placement/IPostBlockAccess.java | 38 - .../object/placement/IrisObjectPlacement.java | 325 ---- .../object/placement/ObjectPlacements.java | 128 -- .../iris/engine/object/prefab/IrisObject.java | 409 ----- .../engine/object/prefab/IrisObjectIO.java | 394 ----- .../object/prefab/IrisObjectRotation.java | 518 ------- .../engine/object/prefab/IrisObjectScale.java | 380 ----- .../object/prefab/IrisObjectShaping.java | 316 ---- .../object/prefab/IrisObjectTransforms.java | 370 ----- .../object/prefab/IrisObjectTranslate.java | 79 - .../engine/object/prefab/LegacyTileData.java | 476 ------ .../iris/engine/object/prefab/TileData.java | 278 ---- .../prefab/matter/IrisMatterObject.java | 59 - .../object/runtime/IrisEngineStreamType.java | 55 - .../object/runtime/IrisEngineValueType.java | 50 - .../engine/object/runtime/StudioMode.java | 67 - .../object/structure/IrisStructure.java | 156 -- .../structure/jigsaw/IrisJigsawConnector.java | 96 -- .../structure/jigsaw/IrisJigsawPiece.java | 94 -- .../jigsaw/IrisJigsawPieceEntry.java | 66 - .../structure/jigsaw/IrisJigsawPool.java | 63 - .../structure/jigsaw/IrisJigsawWorkcell.java | 40 - .../jigsaw/IrisJigsawWorkcellArchetype.java | 88 -- .../engine/object/terrain/IrisGenerator.java | 258 ---- .../iris/engine/object/value/IRare.java | 97 -- .../iris/engine/object/value/IrisColor.java | 111 -- .../engine/object/value/IrisDirection.java | 392 ----- .../iris/engine/object/world/IrisWorld.java | 65 - .../engine/object/world/biome/IrisBiome.java | 422 ----- .../world/biome/IrisBiomeColorRenderer.java | 111 -- .../world/biome/IrisBiomeDerivatives.java | 153 -- .../object/world/biome/IrisBiomeGenLinks.java | 137 -- .../world/biome/IrisBiomeGeneratorLink.java | 90 -- .../world/biome/custom/IrisBiomeCustom.java | 234 --- .../biome/custom/IrisBiomeCustomParticle.java | 69 - .../biome/custom/IrisBiomeCustomSpawn.java | 85 -- .../object/world/dimension/IrisDimension.java | 723 --------- .../IrisDimensionRuntimeContract.java | 133 -- .../world/dimension/IrisDimensionType.java | 104 -- .../dimension/IrisDimensionTypeOptions.java | 324 ---- .../object/world/region/IrisRegion.java | 312 ---- 117 files changed, 228 insertions(+), 24528 deletions(-) create mode 100644 gradle.properties delete mode 100644 source-patterns.txt delete mode 100644 src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/PlacedObject.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java delete mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java delete mode 100644 src/main/java/art/arcane/iris/engine/image/CompiledIrisImageMap.java delete mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapCompiler.java delete mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapMaskSampler.java delete mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapRuntime.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveObjectPlacementTransaction.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacementTransaction.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugObjectPlacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/IslandAnchorPlacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java delete mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFunction.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/functions/ComponentFlagFunction.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/functions/LootTableKeyFunction.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompat.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityBlockFilter.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/compatibility/IrisCompatabilityItemFilter.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImage.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMap.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapBinding.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/material/BlockDataMergeSupport.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/material/IrisBlockData.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/material/IrisMaterialPalette.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisMod.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeInjector.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModBiomeReplacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModNoiseStyleReplacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementBiomeInjector.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectPlacementRegionInjector.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModObjectReplacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/mod/IrisModRegionReplacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisGeneratorStyle.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisInterpolator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisNoiseGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisShapedGeneratorStyle.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/IrisStyledRange.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/NoiseStyle.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpression.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionFunction.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/noise/expression/IrisExpressionLoad.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/DecayControlPlacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/FloatingObjectFootprint.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IPostBlockAccess.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/IrisObjectPlacement.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/placement/ObjectPlacements.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectIO.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectRotation.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectScale.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectShaping.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTransforms.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectTranslate.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/LegacyTileData.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/TileData.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/matter/IrisMatterObject.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStreamType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineValueType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/StudioMode.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/terrain/IrisGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/value/IRare.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisColor.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWorld.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiome.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeColorRenderer.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeDerivatives.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGenLinks.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/IrisBiomeGeneratorLink.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustom.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomParticle.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawn.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimension.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionRuntimeContract.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionTypeOptions.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/region/IrisRegion.java 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"; - } -} From 32703269a3c6f6af9de75366e80438372720751d Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 05:19:11 +0200 Subject: [PATCH 101/139] Batch 6 part 1: build against the geometry package, find(key), blocks() and minWorldY() Block lookups by key use BlockRegistry.find and decide themselves what an unknown block means, as they did when resolve threw. Chunk stages take context.blocks(); world.minHeight() and start.bottomY() read minWorldY(). --- src/main/java/art/arcane/iris/builtin/LiveWorld.java | 2 +- .../art/arcane/iris/builtin/blocks/ObjectMarkers.java | 2 +- .../art/arcane/iris/builtin/blocks/WrittenBlocks.java | 2 +- .../iris/builtin/placement/ObjectPlacement.java | 2 +- .../iris/builtin/prepare/PreparedPlacement.java | 2 +- .../arcane/iris/engine/actuator/TerrainShaper.java | 2 +- .../arcane/iris/engine/decorator/DecorationScene.java | 4 ++-- .../arcane/iris/engine/decorator/DecoratorCore.java | 2 +- .../iris/engine/framework/structure/fit/Box.java | 2 +- .../engine/framework/structure/fit/FitBlocks.java | 2 +- .../iris/engine/framework/structure/fit/FitPiece.java | 2 +- .../engine/framework/structure/fit/StartLayouts.java | 6 +++--- .../framework/structure/fit/SurfaceFitting.java | 2 +- .../art/arcane/iris/engine/loot/BlockDropping.java | 2 +- .../art/arcane/iris/engine/loot/PlacementLoot.java | 2 +- .../mantle/components/FloatingObjectPlacing.java | 4 ++-- .../iris/engine/mantle/components/TreeGrowing.java | 2 +- .../iris/engine/mantle/components/UndersideTurn.java | 2 +- .../art/arcane/iris/engine/modifier/CarveModule.java | 4 ++-- .../art/arcane/iris/engine/modifier/CaveApplying.java | 6 +++--- .../arcane/iris/engine/modifier/DepositPlacer.java | 2 +- .../arcane/iris/engine/modifier/FloatingIslands.java | 8 ++------ .../art/arcane/iris/engine/modifier/MatterModule.java | 4 ++-- .../arcane/iris/engine/modifier/PerfectionModule.java | 2 +- .../arcane/iris/engine/modifier/ResolvedDeposit.java | 6 +----- .../iris/engine/modifier/ResolvedDepositVariant.java | 11 ++++------- .../arcane/iris/engine/modifier/SurfaceSmoothing.java | 2 +- .../iris/engine/object/placement/BlocksModule.java | 2 +- .../iris/engine/object/placement/PlacementWorld.java | 2 +- .../iris/engine/object/placement/SnowModule.java | 2 +- .../iris/engine/object/placement/StiltModule.java | 2 +- .../iris/engine/object/placement/VacuumModule.java | 2 +- .../iris/engine/object/placement/ValidateModule.java | 2 +- .../object/procedural/IrisProceduralBlocks.java | 2 +- .../procedural/tree/ProceduralTreeGenerator.java | 2 +- .../object/terrain/carving/CarvingResolver.java | 2 +- .../engine/object/terrain/floating/FloatingWorld.java | 2 +- .../arcane/iris/engine/spawn/AmbientEffecting.java | 2 +- .../art/arcane/iris/engine/spawn/EntitySpawning.java | 2 +- 39 files changed, 51 insertions(+), 62 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/LiveWorld.java b/src/main/java/art/arcane/iris/builtin/LiveWorld.java index 64b5bd10e..ba10ed4c9 100644 --- a/src/main/java/art/arcane/iris/builtin/LiveWorld.java +++ b/src/main/java/art/arcane/iris/builtin/LiveWorld.java @@ -23,7 +23,7 @@ import art.arcane.iris.builtin.loot.ObjectVanillaLoot; import art.arcane.iris.builtin.spawn.SpawnCooldowns; import com.volmit.IrisFeature; import com.volmit.resource.ResourceId; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.List; import java.util.Optional; diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java index 624e1f3b8..447f40726 100644 --- a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java +++ b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java @@ -20,7 +20,7 @@ package art.arcane.iris.builtin.blocks; import com.volmit.placement.PlacedMarker; import com.volmit.resource.ResourceId; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java b/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java index b7b9bec87..4f185a321 100644 --- a/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java +++ b/src/main/java/art/arcane/iris/builtin/blocks/WrittenBlocks.java @@ -19,7 +19,7 @@ package art.arcane.iris.builtin.blocks; import com.volmit.block.BlockState; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.ArrayList; import java.util.Collections; diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java index de8532bbe..950ad0013 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java @@ -23,7 +23,7 @@ import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.resource.PackResources; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.Optional; diff --git a/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java b/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java index a518639f1..e973a53a8 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java @@ -27,7 +27,7 @@ import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.SurfaceWarp; import art.arcane.volmlib.util.math.IrisBlockVector; import com.volmit.block.BlockState; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; /** * What one placement chose before it is anchored: the settings it uses, the rotation it ended up with, the terrain diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index 22dc64da6..ce7c6c545 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -268,7 +268,7 @@ final class TerrainShaper { private PaletteExplosion upperExplosion; Chunk(ChunkStageContext context) { - this.blocks = context.hunk(BlockState.class); + this.blocks = context.blocks(); this.terrain = context.terrain(); this.settings = context.settings(); this.originX = context.originX(); diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java index a62a71add..8d7df896b 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -52,7 +52,7 @@ public final class DecorationScene { /** The chunk of {@code context}, decorated with the world's decorators. */ public static DecorationScene of(ChunkStageContext context) { Mantle mantle = context.mantle(); - return new DecorationScene(context.hunk(BlockState.class), context.world().resources().blocks(), context.terrain(), + return new DecorationScene(context.blocks(),context.world().resources().blocks(), context.terrain(), mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), context.world().extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT), context.log()); } @@ -145,6 +145,6 @@ public final class DecorationScene { boolean canGoOn(BlockState decoration, BlockState surface) { return supports.computeIfAbsent(decoration, ignored -> new IdentityHashMap<>()) .computeIfAbsent(surface, known -> registry.canPlaceOn(decoration, known) - && registry.canAttach(decoration, known, com.volmit.block.BlockFace.UP)); + && registry.canAttach(decoration, known, com.volmit.geometry.BlockFace.UP)); } } diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java index bdd365d71..7e3dc450c 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecoratorCore.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.decorator; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; -import com.volmit.block.BlockFace; +import com.volmit.geometry.BlockFace; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.hunk.Hunk; diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java index dd068ff8f..201cfaf0f 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/Box.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.framework.structure.fit; -import com.volmit.mantle.BlockBox; +import com.volmit.geometry.BlockBox; /** A box of world blocks, every bound inclusive and Y in world heights, the way the platform's structures measure. */ record Box(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java index d13254c43..00dd3214c 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitBlocks.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.framework.structure.fit; -import com.volmit.block.BlockFace; +import com.volmit.geometry.BlockFace; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.resource.ResourceId; diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java index 13389c1e0..c9f74fc3b 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/FitPiece.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.framework.structure.fit; import com.volmit.vanilla.PieceKind; import com.volmit.vanilla.StructureFit; import com.volmit.vanilla.TemplateCells; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java index 7ef0c5255..ad7b5a12f 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/StartLayouts.java @@ -22,7 +22,7 @@ import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureYBand; import art.arcane.iris.engine.framework.structure.NativeStructureFit; import art.arcane.volmlib.util.math.RNG; -import com.volmit.mantle.BlockBox; +import com.volmit.geometry.BlockBox; import com.volmit.vanilla.PlatformStart; import com.volmit.vanilla.StartReach; @@ -67,8 +67,8 @@ public final class StartLayouts { private static int bandShift(PlatformStart start, StructureYBand band) { BlockBox bounds = start.bounds(); - int minY = bounds.minY() + start.bottomY(); - int maxY = bounds.maxY() - 1 + start.bottomY(); + int minY = bounds.minY() + start.minWorldY(); + int maxY = bounds.maxY() - 1 + start.minWorldY(); int target = bandTargetMidpointY(minY, maxY, band.resolvedMin(), band.resolvedMax(), start.chunkX(), start.chunkZ()); return Math.subtractExact(target, minY + (maxY - minY) / 2); } diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java index f79d87e46..925946720 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/fit/SurfaceFitting.java @@ -25,7 +25,7 @@ import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.StartKey; import com.volmit.vanilla.TemplateCells; import com.volmit.vanilla.TerrainAdaptation; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index abaaa53c9..bad9044f1 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -45,7 +45,7 @@ public final class BlockDropping implements BlockDrops { int x = broken.position().x(); int y = broken.position().y(); int z = broken.position().z(); - String brokenKey = world.resources().blocks().resolve(broken.block()).key(); + String brokenKey = world.resources().blocks().find(broken.block().key()).orElse(broken.block()).key(); ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops()); List providers = dropsFor(live, Level.BIOME, x, y, z, brokenKey, resolved, world); diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index 21249e308..ab43a34d5 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -63,7 +63,7 @@ final class PlacementLoot { */ Loot.Source pick(List platformLoot, List packLoot, BlockState container, RNG rng, int x, int worldY, int z) { - Candidates candidates = new Candidates(resources.blocks().resolve(container)); + Candidates candidates = new Candidates(resources.blocks().find(container.key()).orElse(container)); add(candidates, platformLoot, name -> platformSource(name, x, worldY, z)); add(candidates, packLoot, this::packSource); List pool = candidates.pool(); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 37e7878bf..91de7d6c2 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -39,10 +39,10 @@ import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Level; import com.volmit.config.PackSettings; -import com.volmit.mantle.BlockBox; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; import com.volmit.resource.ResourceId; import com.volmit.stage.MantleStageContext; -import com.volmit.world.BlockPosition; import com.volmit.world.PackWorld; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 98cfe5e30..43de0d718 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -33,7 +33,7 @@ import com.volmit.block.BlockState; import com.volmit.placement.PlacedBlock; import com.volmit.resource.ResourceId; import com.volmit.service.SaplingGrowth; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; import java.util.ArrayList; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java b/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java index 5900dfb9f..79c9c6f7c 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/UndersideTurn.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; /** * How Iris turns an object it hangs under an island: upside down about X, then a quarter turn about Y of {@code yRotation} diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index a6e850f3b..da05ee80d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -88,7 +88,7 @@ public final class CarveModule implements IrisModule { private static void applyCaves(ChunkStageContext context) { MatterMantle mantle = context.extension(MatterMantle.class).orElseThrow(); - Hunk blocks = context.hunk(BlockState.class); + Hunk blocks = context.blocks(); caveApplying(context).apply(mantle, context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context)); } @@ -117,7 +117,7 @@ public final class CarveModule implements IrisModule { int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); return new CarveWorld(world.resources().noise(), world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE), terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, - world.minHeight()); + world.minWorldY()); } private static boolean upperDimensionCarving(ChunkContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 5d0f54a6f..9b72022d2 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -75,9 +75,9 @@ public class CaveApplying { this.blocks = resources.blocks(); this.upperDimensionCarving = upperDimensionCarving; this.rng = new RNG(world.carveSeed()); - this.caveAir = blocks.resolve("minecraft:cave_air"); - this.plainAir = blocks.resolve("minecraft:air"); - this.lava = blocks.resolve("minecraft:lava"); + this.caveAir = blocks.find("minecraft:cave_air").orElseThrow(); + this.plainAir = blocks.find("minecraft:air").orElseThrow(); + this.lava = blocks.find("minecraft:lava").orElseThrow(); } /** diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index e1d5cf66e..72422ba98 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -132,7 +132,7 @@ final class DepositPlacer { private final Map> suitedOres = new IdentityHashMap<>(); Placing(ChunkStageContext context) { - this.blocks = context.hunk(BlockState.class); + this.blocks = context.blocks(); this.terrain = context.terrain(); this.settings = context.settings(); this.mantle = context.mantle(); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 5d67f800a..dd5d8e3ea 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -167,11 +167,7 @@ final class FloatingIslands { } private static BlockState fluidOf(BlockRegistry blocks, String key) { - try { - return blocks.resolve(key); - } catch (IllegalArgumentException unknown) { - return blocks.resolve(DEFAULT_FLUID); - } + return blocks.find(key).or(() -> blocks.find(DEFAULT_FLUID)).orElseThrow(); } private static boolean hasSolidBelow(FloatingIslandSample sample, int k) { @@ -447,7 +443,7 @@ final class FloatingIslands { Chunk(ChunkStageContext context) { this.originX = context.originX(); this.originZ = context.originZ(); - this.output = context.hunk(BlockState.class); + this.output = context.blocks(); this.height = output.height(); this.blocks = context.world().resources().blocks(); this.settings = context.settings(); diff --git a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java index 467fc1e61..7cdfd7591 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/MatterModule.java @@ -24,7 +24,7 @@ import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.hunk.Hunk; -import com.volmit.mantle.BlockBox; +import com.volmit.geometry.BlockBox; import com.volmit.stage.ChunkStageContext; import com.volmit.world.TerrainSampler; @@ -55,7 +55,7 @@ public final class MatterModule implements IrisModule { private static void insert(ChunkStageContext context) { int originX = context.originX(); int originZ = context.originZ(); - Hunk blocks = context.hunk(BlockState.class); + Hunk blocks = context.blocks(); int[] limits = upperLimits(context.terrain(), originX, originZ); BlockBox chunk = new BlockBox(originX, 0, originZ, originX + CHUNK_WIDTH, blocks.height(), originZ + CHUNK_WIDTH); context.mantle().blocks().visit(chunk, (x, y, z, block) -> { diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index cfe52366b..057669ff0 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -58,7 +58,7 @@ public final class PerfectionModule implements IrisModule { } private static void perfect(ChunkStageContext context) { - Hunk blocks = context.hunk(BlockState.class); + Hunk blocks = context.blocks(); if (hidesOres(context)) { hideOres(blocks, new IdentityHashMap<>()); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java index 4ca78c01b..e3d542703 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java @@ -372,11 +372,7 @@ final class ResolvedDeposit { private static Set replaceableMaterials(BlockRegistry registry, List keys) { Set materials = new HashSet<>(); for (String key : keys) { - try { - materials.add(registry.resolve(key).material()); - } catch (IllegalArgumentException unknownBlock) { - continue; - } + registry.find(key).ifPresent(block -> materials.add(block.material())); } return materials; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java index 86da0bc29..5fd4d549d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java @@ -71,13 +71,10 @@ final class ResolvedDepositVariant { /** The block the platform has under {@code key}; a replacement it lacks is reported once. */ private Optional known(String key, boolean reportMissing) { - try { - return Optional.of(registry.resolve(key)); - } catch (IllegalArgumentException unknownBlock) { - if (reportMissing) { - log.warnOnce("deposit-variant-block:" + key, "Deposit variant replaces ores with " + key + ", which this server does not have"); - } - return Optional.empty(); + Optional block = registry.find(key); + if (block.isEmpty() && reportMissing) { + log.warnOnce("deposit-variant-block:" + key, "Deposit variant replaces ores with " + key + ", which this server does not have"); } + return block; } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index f098cabdd..011ed8a08 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -77,7 +77,7 @@ final class SurfaceSmoothing { private final int fluidHeight; private SurfaceSmoothing(ChunkStageContext context) { - this.blocks = context.hunk(BlockState.class); + this.blocks = context.blocks(); this.registry = context.world().resources().blocks(); this.terrain = context.terrain(); this.settings = context.settings(); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 5dde7efcd..efc33ebaa 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -42,7 +42,7 @@ import com.volmit.object.BlockEntityData; import com.volmit.object.ObjectBlock; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.Map; import java.util.Optional; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java index bcb736486..fcc10c1cb 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java @@ -24,7 +24,7 @@ import com.volmit.block.BlockTrait; import com.volmit.object.BlockEntityData; import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacementAccess; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.Optional; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java index 29dd41c01..e3d4a4ed8 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -27,7 +27,7 @@ import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.stage.PlacementStageContext; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.LinkedHashMap; import java.util.Map; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 6ea72b878..a1ee111bd 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -34,7 +34,7 @@ import com.volmit.block.BlockTrait; import com.volmit.object.ObjectBlock; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.List; import java.util.Optional; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 0e450ea51..8b0006989 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -33,7 +33,7 @@ import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.stage.PlacementStageContext; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; /** * Module {@code iris:vacuum}: bends the terrain around an object of a vacuum mode so it meets the object's diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 38285335c..a55407cea 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -36,7 +36,7 @@ import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.object.ObjectBlock; import com.volmit.stage.PlacementStageContext; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.Optional; import java.util.Set; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java index 8bd7f34db..df094fa56 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java @@ -24,7 +24,7 @@ import art.arcane.volmlib.util.math.Vector3i; import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; import com.volmit.object.ObjectBlock; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java index bf40fa8b9..32565c3b2 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -24,7 +24,7 @@ import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; import com.volmit.object.ObjectBlock; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index 30aa62036..7b2e26468 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -59,7 +59,7 @@ public final class CarvingResolver { CarvingResolver(PackWorld world, List declared) { this.resources = world.resources(); this.log = world.log(); - this.minHeight = world.minHeight(); + this.minHeight = world.minWorldY(); this.childSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE) ^ CHILD_SEED_SALT; this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); this.index = indexById(entries); diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index aeb31e026..11ccf245c 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -74,7 +74,7 @@ public final class FloatingWorld { private static FloatingWorld create(PackWorld world) { IrisSeeds seeds = world.extension(IrisSeeds.class).orElseThrow(); return new FloatingWorld(world.extension(FloatingHost.class).orElseThrow(), world.extension(ObjectHost.class).orElseThrow(), - world.resources().noise(), seeds.seed(IrisSeed.TERRAIN), seeds.seed(IrisSeed.CARVE), world.minHeight(), + world.resources().noise(), seeds.seed(IrisSeed.TERRAIN), seeds.seed(IrisSeed.CARVE), world.minWorldY(), dimensionCarvingOf(world)); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java index 678353b33..69ae7b4c9 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -28,7 +28,7 @@ import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.volmlib.util.math.RNG; import com.volmit.entity.EntitySpec; import com.volmit.service.AmbientEffects; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; import java.util.ArrayList; diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 29b3a4827..9b9097a00 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -40,7 +40,7 @@ import com.volmit.entity.EntitySpec; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.service.EntitySpawns; -import com.volmit.world.BlockPosition; +import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; import java.util.ArrayList; From 06b3f10220ada2a372bd6a6aa73fc54c910c5d33 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 06:06:52 +0200 Subject: [PATCH 102/139] Hand the API typed keys and grouped item and entity values Batch 6, findings 41 and 42. - PlatformKeys turns pack keys into ResourceIds and ContentKeys, dropping a key that cannot be one with a warning once; random draws keep their order, so loot and entities stay the same. - Loot items and entities build the grouped ItemDrop and EntitySpec; Iris-only entity knobs travel as the IrisEntityExtras extension. - Settings name pack resources with @Ref(kind = ...); Iris structure-model keys use the Iris extension @IrisStructureRef. - Markers, sapling species and the upper dimension are ids. --- .../builtin/carve/CarvingBiomeSettings.java | 4 +- .../iris/builtin/carve/CarvingEntry.java | 4 +- .../builtin/floating/FloatingChildBiome.java | 3 +- .../iris/builtin/loot/LootSettings.java | 4 +- .../arcane/iris/builtin/loot/ObjectLoot.java | 4 +- .../iris/builtin/objects/ObjectPlacement.java | 8 +- .../iris/builtin/spawn/EntitySpawn.java | 4 +- .../iris/builtin/spawn/IrisEntityExtras.java | 46 +++++++ .../iris/builtin/spawn/PlacementMarker.java | 4 +- .../iris/builtin/spawn/SpawnMarker.java | 4 +- .../iris/builtin/spawn/SpawnerSettings.java | 4 +- .../builtin/structure/IrisStructureRef.java | 34 +++++ .../builtin/structure/StructurePlacement.java | 6 +- .../iris/builtin/terrain/TerrainPalettes.java | 8 +- .../iris/engine/loot/BlockDropping.java | 2 +- .../arcane/iris/engine/loot/LootGiving.java | 2 +- .../arcane/iris/engine/loot/LootItems.java | 81 ++++++----- .../iris/engine/loot/PlacementLoot.java | 3 +- .../arcane/iris/engine/loot/PlatformKeys.java | 130 ++++++++++++++++++ .../engine/mantle/components/TreeGrowing.java | 5 +- .../iris/engine/spawn/AmbientEffecting.java | 42 +++--- .../iris/engine/spawn/EntityResolution.java | 79 ++++++----- .../iris/engine/spawn/EntitySpawning.java | 20 +-- 23 files changed, 370 insertions(+), 131 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java create mode 100644 src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java index 56c8b50ea..a5748eaed 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java @@ -24,7 +24,7 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.LinkedBiomes; import com.volmit.config.Ref; -import com.volmit.config.Reference; +import com.volmit.world.PackBiome; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; @@ -34,7 +34,7 @@ import java.util.Set; @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") @Feature(id = "iris:carve/biome", name = "Carving biome", key = "carvingBiome", root = "biome", targets = Level.BIOME) public final class CarvingBiomeSettings implements IrisFeature, LinkedBiomes { - @Ref(Reference.PACK_BIOME) + @Ref(kind = PackBiome.class) @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") private String biome = ""; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java index 7508832a7..e04543669 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java @@ -21,7 +21,7 @@ package art.arcane.iris.builtin.carve; import com.volmit.config.Desc; import com.volmit.config.Range; import com.volmit.config.Ref; -import com.volmit.config.Reference; +import com.volmit.world.PackBiome; import com.volmit.config.Snippet; import com.volmit.noise.NoiseStyle; @@ -47,7 +47,7 @@ public final class CarvingEntry { @Desc("Enable or disable this carving entry") private boolean enabled = true; - @Ref(Reference.PACK_BIOME) + @Ref(kind = PackBiome.class) @Desc("Cave biome to apply when world Y falls within worldYRange") private String biome = ""; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java index 3702ab55f..edc39a5f6 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java @@ -27,6 +27,7 @@ import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; import com.volmit.config.Snippet; +import com.volmit.world.PackBiome; import com.volmit.noise.NoiseStyle; import java.util.Collections; @@ -51,7 +52,7 @@ public final class FloatingChildBiome { private static final NoiseStyle DEFAULT_EDGE_TAPER_VARIATION_STYLE = NoiseStyle.of("SIMPLEX").withZoom(0.18D); private static final NoiseStyle DEFAULT_FOOTPRINT_STYLE = NoiseStyle.of("SIMPLEX"); - @Ref(Reference.PACK_BIOME) + @Ref(kind = PackBiome.class) @Desc("The target biome whose visual design (layers, palette, decorators, surface objects, derivative, and — when topShapeMode=BIOME — generator profile) drives the floating island. Leave empty to reuse the parent biome (self).") private String biome = ""; diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java index 1d6fff05b..bee988938 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java @@ -24,7 +24,7 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; -import com.volmit.config.ResourceRef; +import com.volmit.config.Ref; import com.volmit.config.Snippet; import java.util.Collections; @@ -44,7 +44,7 @@ public final class LootSettings implements IrisFeature { @Desc("ADD = add on top of parent tables. REPLACE = clear parent tables, then add these. CLEAR = clear parent tables and add nothing, even if tables are listed. FALLBACK = only used when nothing else defined a table.") private LootMode mode = LootMode.ADD; - @ResourceRef(LootTable.class) + @Ref(kind = LootTable.class) @Desc("Add loot table registries here") private List tables = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java index 95ca8dae0..c83c52464 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -23,7 +23,7 @@ import com.volmit.config.Desc; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; -import com.volmit.config.ResourceRef; +import com.volmit.config.Ref; import com.volmit.config.Snippet; import java.util.Collections; @@ -39,7 +39,7 @@ public final class ObjectLoot implements ObjectLootEntry { private boolean exact = false; @Desc("The loot table name") @Required - @ResourceRef(LootTable.class) + @Ref(kind = LootTable.class) private String name; @Desc("The weight of this loot table being chosen") @MinNumber(1) diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index 04479458a..faf5429a6 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -45,11 +45,11 @@ import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; -import com.volmit.config.Reference; import com.volmit.config.Required; import com.volmit.config.Snippet; import com.volmit.noise.NoiseStyle; import com.volmit.noise.StyledRange; +import com.volmit.object.GeneratedObject; import java.io.IOException; import java.util.Collections; @@ -71,7 +71,7 @@ public final class ObjectPlacement implements PlacementSource { @Required @MinItems(1) - @Ref(Reference.PACK_OBJECT) + @Ref(kind = GeneratedObject.class) @Desc("List of objects to place") private List place = List.of(); @Desc("Rotate this objects placement") @@ -168,11 +168,11 @@ public final class ObjectPlacement implements PlacementSource { @Desc("This object / these objects override the following trees when they grow...") private List trees = List.of(); @MinItems(1) - @Ref(Reference.PACK_OBJECT) + @Ref(kind = GeneratedObject.class) @Desc("List of objects to this object is allowed to collied with") private List allowedCollisions = List.of(); @MinItems(1) - @Ref(Reference.PACK_OBJECT) + @Ref(kind = GeneratedObject.class) @Desc("List of objects to this object is forbidden to collied with") private List forbiddenCollisions = List.of(); @Desc("Ignore any placement restrictions for this object") diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java index 34acbcae5..b775563fc 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java @@ -21,13 +21,13 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.MinNumber; import com.volmit.config.Required; -import com.volmit.config.ResourceRef; +import com.volmit.config.Ref; import com.volmit.config.Snippet; @Snippet("entity-spawn") @Desc("Represents an entity spawn during initial chunk generation") public final class EntitySpawn { - @ResourceRef(EntityDefinition.class) + @Ref(kind = EntityDefinition.class) @Required @Desc("The entity") private String entity = ""; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java b/src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java new file mode 100644 index 000000000..5919e1475 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java @@ -0,0 +1,46 @@ +/* + * 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.builtin.spawn; + +import java.util.Objects; +import java.util.Optional; + +/** + * Iris extension of an {@link com.volmit.entity.EntitySpec}, read by Iris's Bukkit host with + * {@code spec.extension(IrisEntityExtras.class)}: what Iris packs set on an entity that only Bukkit has a name for or + * only Iris does. Other hosts ignore it. + * + * @param reason Bukkit's spawn reason by name, such as {@code COMMAND}; empty for a natural spawn + * @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near + * @param pandaMainGene for pandas the main gene by Bukkit's name; empty to leave it to the platform + * @param pandaHiddenGene for pandas the hidden gene by Bukkit's name; empty to leave it to the platform + * @param applySettingsToProvidedMob whether the rest of the spec also applies to a mob of a content provider, which is + * otherwise left as the provider set it up + */ +public record IrisEntityExtras(Optional reason, boolean riseOutOfGround, Optional pandaMainGene, + Optional pandaHiddenGene, boolean applySettingsToProvidedMob) { + /** What an entity without the extension gets: a natural spawn, standing, with the platform's genes. */ + public static final IrisEntityExtras NONE = new IrisEntityExtras(Optional.empty(), false, Optional.empty(), Optional.empty(), false); + + public IrisEntityExtras { + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(pandaMainGene, "pandaMainGene"); + Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene"); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java index 435cc4af5..fae838c59 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -24,7 +24,7 @@ import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; -import com.volmit.config.ResourceRef; +import com.volmit.config.Ref; import com.volmit.config.Snippet; import java.util.Collections; @@ -45,7 +45,7 @@ public final class PlacementMarker { @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") private boolean exact = false; @Required - @ResourceRef(SpawnMarker.class) + @Ref(kind = SpawnMarker.class) @Desc("The marker to add") private String marker; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java index 249b8fb5a..c8ebf044a 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java @@ -20,7 +20,7 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.MinItems; -import com.volmit.config.ResourceRef; +import com.volmit.config.Ref; import java.util.Collections; import java.util.List; @@ -29,7 +29,7 @@ import java.util.List; @Desc("Represents a marker") public final class SpawnMarker { @Desc("A list of spawners to add to anywhere this marker is.") - @ResourceRef(Spawner.class) + @Ref(kind = Spawner.class) @MinItems(1) private List spawners = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java index a8a628c3c..e2a2725cb 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java @@ -23,7 +23,7 @@ import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MinItems; -import com.volmit.config.ResourceRef; +import com.volmit.config.Ref; import java.util.Collections; import java.util.List; @@ -36,7 +36,7 @@ import java.util.List; @Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class SpawnerSettings implements IrisFeature { @MinItems(1) - @ResourceRef(Spawner.class) + @Ref(kind = Spawner.class) @Desc("Entity spawners to add to this area") private List spawners = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java b/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java new file mode 100644 index 000000000..c7b3164d4 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java @@ -0,0 +1,34 @@ +/* + * 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.builtin.structure; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Iris extension: says that a text option names structures of Iris's structure model by key, which Iris completes in + * studio and carries along when it exports the pack. The structure model is Iris's own resource kind, whose class a + * module cannot see, so {@code @Ref(kind = ...)} cannot name it; to another host the option is plain text. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface IrisStructureRef { +} diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java index 1f8f7f5a4..11c2d13e2 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java @@ -23,7 +23,7 @@ import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; -import com.volmit.config.Reference; +import com.volmit.world.PackBiome; import java.util.Collections; import java.util.List; @@ -37,7 +37,7 @@ import java.util.Optional; @Desc("Attaches structures to a biome, region or dimension and controls where and how often they generate. This is independent of a structure's own native generation, so you can add custom placements in tandem with native generation or instead of it.") public final class StructurePlacement { @MinItems(1) - @Ref(Reference.PACK_STRUCTURE) + @IrisStructureRef @Desc("Editable Iris assembly resources offered by this placement. Leave empty when nativeStructures supplies the source.") private List structures = List.of(); @@ -96,7 +96,7 @@ public final class StructurePlacement { private StructureAnchorMode anchor = StructureAnchorMode.LEGACY; @MinItems(1) - @Ref(Reference.PACK_BIOME) + @Ref(kind = PackBiome.class) @Desc("Optional cave-biome allowlist for cave anchor modes. Empty accepts the cave biome resolved at the selected anchor. Entries match by load key, including prefix matches.") private List caveBiomes = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java index 916bc33fa..6ba518f2d 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java @@ -26,6 +26,7 @@ import com.volmit.block.PaletteSpec; import com.volmit.config.SettingsStack; import com.volmit.noise.NoiseSampler; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import com.volmit.world.UpperDimension; @@ -58,7 +59,7 @@ public final class TerrainPalettes { private final long complexSeed; private final AtomicCache rock = new AtomicCache<>(); private final AtomicCache fluid = new AtomicCache<>(); - private final Map upperRocks = new ConcurrentHashMap<>(); + private final Map upperRocks = new ConcurrentHashMap<>(); TerrainPalettes(PackWorld world) { this.world = world; @@ -88,7 +89,7 @@ public final class TerrainPalettes { /** The rock at the column of the upper dimension: the world's own when the upper dimension is the dimension itself. */ public BlockState upperRockAt(UpperDimension upper, double x, double z) { - return upperRocks.computeIfAbsent(upper.key(), key -> upperRock(upper, x, z)).at(x, z); + return upperRocks.computeIfAbsent(upper.id(), id -> upperRock(upper, x, z)).at(x, z); } private ColumnBlocks rock() { @@ -110,7 +111,8 @@ public final class TerrainPalettes { return rock(); } - long seedOffset = upper.key().hashCode(); + // Iris seeded this from the dimension's key; the id's path is that key for every key an id can hold unchanged. + long seedOffset = upper.id().path().hashCode(); RNG rng = new RNG(complexSeed ^ seedOffset); SettingsStack declared = upper.settings().at(RockPaletteSettings.class, (int) x, (int) z); return columns(rockPalette(declared), rng.nextParallelRNG(ROCK_SIGNATURE), upper.resources()); diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index bad9044f1..25da5e360 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -54,7 +54,7 @@ public final class BlockDropping implements BlockDrops { providers.addAll(dropsFor(live, Level.DIMENSION, x, y, z, brokenKey, resolved, world)); } - LootItems items = new LootItems(world.resources().items(), false); + LootItems items = new LootItems(world.resources().items(), false, world.log()); List drops = new ArrayList<>(); providers.forEach(provider -> fillDrops(provider.drop(), items, drops)); return new Result(drops, providers.stream().anyMatch(provider -> provider.drop().replaceVanillaDrops())); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 5907586f4..46e314993 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -76,7 +76,7 @@ public final class LootGiving implements Loot { return List.of(); } int worldY = site.position().y() + world.extension(LiveWorld.class).orElseThrow().bottomY(); - return new LootItems(world.resources().items(), site.debug()) + return new LootItems(world.resources().items(), site.debug(), world.log()) .draw(tableId.path(), table, lootSeed(world), site.position().x(), worldY, site.position().z()); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java index 366f53d0a..815c5280c 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootItems.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -25,10 +25,13 @@ import art.arcane.iris.builtin.loot.LootSlot; import art.arcane.iris.builtin.loot.LootTable; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; import com.volmit.item.ItemEnchantment; import com.volmit.item.ItemRegistry; +import com.volmit.resource.ContentKey; +import com.volmit.resource.ResourceId; import java.util.ArrayList; import java.util.List; @@ -44,17 +47,21 @@ import java.util.OptionalInt; * must do with the result is the host's. */ public final class LootItems { - private static final String AIR = "air"; - private static final String MINECRAFT_PREFIX = "minecraft:"; + private static final ContentKey AIR = new ContentKey.Registered(ResourceId.parse("minecraft:air")); private static final int MIN_AMOUNT = 1; private final ItemRegistry items; private final boolean debug; + private final ModuleLog log; - /** @param debug whether the items say where they came from */ - public LootItems(ItemRegistry items, boolean debug) { + /** + * @param debug whether the items say where they came from + * @param log hears of keys that name nothing the platform could have + */ + public LootItems(ItemRegistry items, boolean debug, ModuleLog log) { this.items = items; this.debug = debug; + this.log = log; } /** @@ -92,6 +99,24 @@ public final class LootItems { return resolve(entry, rng, null); } + /** The attribute modifiers that pass their chances, with their amounts drawn, as for an item or an entity. */ + public List attributes(List modifiers, RNG rng) { + List attributes = new ArrayList<>(); + for (ItemAttributeModifier modifier : modifiers) { + if (rng.nextDouble() >= modifier.chance()) { + continue; + } + String attribute = modifier.attribute(); + if (attribute == null || attribute.isBlank()) { + continue; + } + double amount = rng.d(modifier.minAmount(), modifier.maxAmount()); + PlatformKeys.id(attribute, log).ifPresent(id -> attributes.add( + new ItemAttribute(id, modifier.name(), PlatformKeys.operation(modifier.operation()), amount))); + } + return attributes; + } + private ItemDrop drawEntry(LootEntry entry, LootTable table, String identity, RNG rng, long lootSeed, int index, int x, int y, int z) { long combinedRarity = LootResolver.combinedRarity(entry.rarity(), table.rarity()); if (!LootTables.spatialOneIn(lootSeed, identity, index, x, y, z, combinedRarity)) { @@ -101,66 +126,50 @@ public final class LootItems { } private ItemDrop resolve(LootEntry entry, RNG rng, LootTable table) { - String type = entry.type(); - OptionalInt maxDurability = items.maxDurability(type); - if (maxDurability.isEmpty() || isAir(type)) { + Optional item = PlatformKeys.item(entry.type(), log); + if (item.isEmpty() || item.get().equals(AIR)) { + return null; + } + OptionalInt maxDurability = items.maxDurability(item.get()); + if (maxDurability.isEmpty()) { return null; } int amount = Math.max(MIN_AMOUNT, LootResolver.inclusive(rng, entry.minAmount(), entry.maxAmount())); List enchantments = drawEnchantments(entry, rng); - List attributes = drawAttributes(entry, rng); + List attributes = attributes(entry.attributes(), rng); OptionalDouble damage = maxDurability.getAsInt() > 0 ? OptionalDouble.of(1D - rng.d(entry.minDurability(), entry.maxDurability())) : OptionalDouble.empty(); - return new ItemDrop(type, amount, Optional.ofNullable(entry.displayName()), entry.lore(), enchantments, attributes, - entry.unbreakable(), entry.itemFlags(), customModelOf(entry), damage, Optional.ofNullable(entry.leatherColor()), - Optional.ofNullable(entry.dyeColor()), Objects.requireNonNullElse(entry.customNbt(), Map.of()), + return new ItemDrop(item.get(), amount, lookOf(entry), enchantments, attributes, new ItemDrop.Wear(entry.unbreakable(), damage), + new ItemDrop.PlatformExtras(entry.itemFlags(), Objects.requireNonNullElse(entry.customNbt(), Map.of())), debug ? Optional.of(sourceOf(entry, table)) : Optional.empty()); } - private static OptionalInt customModelOf(LootEntry entry) { + private ItemDrop.Look lookOf(LootEntry entry) { Integer customModel = entry.customModel(); - return customModel == null ? OptionalInt.empty() : OptionalInt.of(customModel); + return new ItemDrop.Look(Optional.ofNullable(entry.displayName()), entry.lore(), + customModel == null ? OptionalInt.empty() : OptionalInt.of(customModel), + PlatformKeys.rgb(entry.leatherColor(), log), PlatformKeys.dye(entry.dyeColor(), log)); } - private static List drawEnchantments(LootEntry entry, RNG rng) { + private List drawEnchantments(LootEntry entry, RNG rng) { List enchantments = new ArrayList<>(); for (LootEnchantment enchantment : entry.enchantments()) { String key = enchantment.enchantment(); if (key == null || key.isBlank() || rng.nextDouble() >= enchantment.chance()) { continue; } - int level = LootResolver.inclusive(rng, enchantment.minLevel(), enchantment.maxLevel()); - enchantments.add(new ItemEnchantment(key, Math.max(1, level))); + int level = Math.max(1, LootResolver.inclusive(rng, enchantment.minLevel(), enchantment.maxLevel())); + PlatformKeys.id(key, log).ifPresent(id -> enchantments.add(new ItemEnchantment(id, level))); } return enchantments; } - private static List drawAttributes(LootEntry entry, RNG rng) { - List attributes = new ArrayList<>(); - for (ItemAttributeModifier modifier : entry.attributes()) { - if (rng.nextDouble() >= modifier.chance()) { - continue; - } - String attribute = modifier.attribute(); - if (attribute == null || attribute.isBlank()) { - continue; - } - attributes.add(new ItemAttribute(attribute, modifier.name(), modifier.operation(), rng.d(modifier.minAmount(), modifier.maxAmount()))); - } - return attributes; - } - private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table) { if (table == null) { return new ItemDrop.Source(Optional.empty(), 0, entry.rarity()); } return new ItemDrop.Source(Optional.ofNullable(table.name()), table.rarity(), entry.rarity()); } - - private static boolean isAir(String type) { - String key = type.startsWith(MINECRAFT_PREFIX) ? type.substring(MINECRAFT_PREFIX.length()) : type; - return AIR.equalsIgnoreCase(key); - } } diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index ab43a34d5..7f39aaa0b 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -25,6 +25,7 @@ import com.volmit.ModuleLog; import com.volmit.block.BlockSpec; import com.volmit.block.BlockState; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.service.Loot; import java.util.ArrayList; @@ -94,7 +95,7 @@ final class PlacementLoot { if (key == null || !platformTables.get().contains(key)) { return null; } - return new Loot.PlatformTable(key, LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z)); + return new Loot.PlatformTable(ResourceId.parse(key), LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z)); } /** A placement's name for a platform table as the platform's key for it, or null for a name that cannot be one. */ diff --git a/src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java b/src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java new file mode 100644 index 000000000..82972017d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/PlatformKeys.java @@ -0,0 +1,130 @@ +/* + * 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.loot; + +import com.volmit.ModuleLog; +import com.volmit.item.ItemAttribute; +import com.volmit.item.DyeColor; +import com.volmit.resource.ContentKey; +import com.volmit.resource.ResourceId; + +import java.util.Locale; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * The platform things packs name, as they write them, turned into what IrisApi hands the host: ids, items and mobs, + * attribute operations and colours. A blank key names nothing; a key that names nothing the host could look up is left + * out with a warning, once per key. + */ +public final class PlatformKeys { + private static final String PLATFORM_NAMESPACE = "minecraft"; + private static final char NAMESPACE_SEPARATOR = ':'; + private static final String WARNING_KEY = "iris:platform-key/"; + + private PlatformKeys() { + } + + /** {@code key} as an id, such as {@code minecraft:sharpness} for {@code Sharpness}; see {@link ResourceId#ofPlatformKey}. */ + public static Optional id(String key, ModuleLog log) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(ResourceId.ofPlatformKey(key)); + } catch (IllegalArgumentException invalid) { + log.warnOnce(WARNING_KEY + key, "Ignoring '" + key + "': it names nothing the platform could have"); + return Optional.empty(); + } + } + + /** + * The item {@code key} names. A key of the platform's own namespace, or of none, is a registered item; so is a key of + * another namespace an id can hold as written, such as {@code itemsadder:ruby}, which the host routes to its owner. + * Any other namespaced key is a provider's item, kept as written. + */ + public static Optional item(String key, ModuleLog log) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + String written = key.trim(); + int separator = written.indexOf(NAMESPACE_SEPARATOR); + if (separator < 0 || PLATFORM_NAMESPACE.equalsIgnoreCase(written.substring(0, separator))) { + return id(written, log).map(ContentKey.Registered::new); + } + try { + return Optional.of(new ContentKey.Registered(ResourceId.parse(written))); + } catch (IllegalArgumentException notAnId) { + return provided(written, log); + } + } + + /** A provider's mob or item, written {@code provider:name}, such as {@code mythicmobs:SkeletonKing}. */ + public static Optional provided(String key, ModuleLog log) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + String written = key.trim(); + int separator = written.indexOf(NAMESPACE_SEPARATOR); + if (separator <= 0 || separator == written.length() - 1) { + log.warnOnce(WARNING_KEY + key, "Ignoring '" + key + "': a provider's content is written provider:name"); + return Optional.empty(); + } + return Optional.of(new ContentKey.Provided(written.substring(0, separator), written.substring(separator + 1))); + } + + /** + * The attribute operation packs name by Bukkit's names, {@code ADD_NUMBER}, {@code ADD_SCALAR} and + * {@code MULTIPLY_SCALAR_1}, or by the platform's own; adding the amount for a name it does not know. + */ + public static ItemAttribute.Operation operation(String name) { + String normalized = name == null ? "" : name.trim().toUpperCase(Locale.ROOT); + return switch (normalized) { + case "ADD_SCALAR", "ADD_MULTIPLIED_BASE" -> ItemAttribute.Operation.ADD_MULTIPLIED_BASE; + case "MULTIPLY_SCALAR_1", "ADD_MULTIPLIED_TOTAL" -> ItemAttribute.Operation.ADD_MULTIPLIED_TOTAL; + default -> ItemAttribute.Operation.ADD_VALUE; + }; + } + + /** The colour {@code text} writes, {@code #rrggbb}, {@code 0xrrggbb} or a number; empty, with a warning, for anything else. */ + public static OptionalInt rgb(String text, ModuleLog log) { + if (text == null || text.isBlank()) { + return OptionalInt.empty(); + } + try { + return OptionalInt.of(Integer.decode(text.trim()) & 0xFFFFFF); + } catch (NumberFormatException notAColour) { + log.warnOnce(WARNING_KEY + text, "Ignoring the colour '" + text + "': write it as #rrggbb"); + return OptionalInt.empty(); + } + } + + /** The dye colour {@code name} names, such as {@code RED} or {@code light_blue}; empty, with a warning, for anything else. */ + public static Optional dye(String name, ModuleLog log) { + if (name == null || name.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(DyeColor.valueOf(name.trim().toUpperCase(Locale.ROOT))); + } catch (IllegalArgumentException unknown) { + log.warnOnce(WARNING_KEY + name, "Ignoring the dye colour '" + name + "', which is none of the sixteen dyes"); + return Optional.empty(); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 43de0d718..e4e1d5beb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -114,10 +114,11 @@ public final class TreeGrowing implements SaplingGrowth { return Optional.of(placements.get(RNG.r.i(placements.size()))); } - private static List matching(ObjectSettings settings, String species) { + /** The placements whose trees override {@code species}, which packs name by the path of its id, ignoring case. */ + private static List matching(ObjectSettings settings, ResourceId species) { List matches = new ArrayList<>(); for (ObjectPlacement placement : settings.objects()) { - if (placement.trees().stream().anyMatch(tree -> tree.matches(SAPLING_WIDTH, SAPLING_DEPTH, species))) { + if (placement.trees().stream().anyMatch(tree -> tree.matches(SAPLING_WIDTH, SAPLING_DEPTH, species.path()))) { matches.add(placement); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java index 69ae7b4c9..cb46dd0fc 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -25,8 +25,11 @@ import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EffectCommands; import art.arcane.iris.builtin.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.SpawnCommand; +import art.arcane.iris.engine.loot.PlatformKeys; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import com.volmit.entity.EntitySpec; +import com.volmit.resource.ResourceId; import com.volmit.service.AmbientEffects; import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; @@ -47,8 +50,8 @@ public final class AmbientEffecting implements AmbientEffects { Optional sky = live.sky(); List due = new ArrayList<>(); - addDue(due, effectsOf(live, Level.REGION, at), timers, sky); - addDue(due, effectsOf(live, Level.BIOME, at), timers, sky); + addDue(due, effectsOf(live, Level.REGION, at), timers, sky, world.log()); + addDue(due, effectsOf(live, Level.BIOME, at), timers, sky, world.log()); return due; } @@ -56,40 +59,36 @@ public final class AmbientEffecting implements AmbientEffects { return live.settings(EffectSettings.class, level, at.x(), at.y(), at.z()).map(EffectSettings::effects).orElse(List.of()); } - private static void addDue(List due, List effects, EffectTimers timers, Optional sky) { + private static void addDue(List due, List effects, EffectTimers timers, Optional sky, ModuleLog log) { for (AmbientEffect effect : effects) { if (timers.shouldPlayNow(effect)) { - due.add(play(effect, sky)); + due.add(play(effect, sky, log)); } } } - private static Effect play(AmbientEffect effect, Optional sky) { - Optional sound = effect.sound() == null ? Optional.empty() : Optional.of(soundOf(effect)); - Optional particles = effect.particleEffect() == null ? Optional.empty() : Optional.of(particlesOf(effect)); - return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect)); + private static Effect play(AmbientEffect effect, Optional sky, ModuleLog log) { + Optional sound = PlatformKeys.id(effect.sound(), log).map(key -> soundOf(key, effect)); + Optional particles = PlatformKeys.id(effect.particleEffect(), log).map(key -> particlesOf(key, effect)); + return new Effect(sound, particles, commandsOf(effect.commandRegistry(), sky), potionOf(effect, log)); } - private static Sound soundOf(AmbientEffect effect) { + private static Sound soundOf(ResourceId key, AmbientEffect effect) { int distance = effect.soundDistance(); int offsetX = RNG.r.i(-distance, distance); int offsetY = RNG.r.i(-distance, distance); int offsetZ = RNG.r.i(-distance, distance); float pitch = (float) RNG.r.d(effect.minPitch(), effect.maxPitch()); - return new Sound(effect.sound(), offsetX, offsetY, offsetZ, (float) effect.volume(), pitch); + return new Sound(key, offsetX, offsetY, offsetZ, (float) effect.volume(), pitch); } - private static Particles particlesOf(AmbientEffect effect) { + private static Particles particlesOf(ResourceId key, AmbientEffect effect) { double forward = RNG.r.i(effect.particleDistance()) + effect.particleAway(); double sideways = RNG.r.d(-effect.particleDistanceWidth(), effect.particleDistanceWidth()); - double jitterX = RNG.r.d(); - double jitterZ = RNG.r.d(); - int lift = RNG.r.i(effect.particleOffset()); - double altX = randomized(effect.particleAltX(), effect.randomAltX()); - double altY = randomized(effect.particleAltY(), effect.randomAltY()); - double altZ = randomized(effect.particleAltZ(), effect.randomAltZ()); - return new Particles(effect.particleEffect(), forward, sideways, jitterX, jitterZ, lift, effect.particleCount(), - altX, altY, altZ, effect.extra()); + Spot spot = new Spot(forward, sideways, RNG.r.d(), RNG.r.d(), RNG.r.i(effect.particleOffset())); + Spread spread = new Spread(randomized(effect.particleAltX(), effect.randomAltX()), + randomized(effect.particleAltY(), effect.randomAltY()), randomized(effect.particleAltZ(), effect.randomAltZ())); + return new Particles(key, spot, effect.particleCount(), spread, effect.extra()); } private static List commandsOf(EffectCommands registry, Optional sky) { @@ -115,14 +114,15 @@ public final class AmbientEffecting implements AmbientEffects { return commands; } - private static Optional potionOf(AmbientEffect effect) { + private static Optional potionOf(AmbientEffect effect, ModuleLog log) { if (effect.potionStrength() <= -1) { return Optional.empty(); } int shortest = Math.min(effect.potionTicksMax(), effect.potionTicksMin()); int longest = Math.max(effect.potionTicksMax(), effect.potionTicksMin()); - return Optional.of(new Potion(effect.potionEffect(), effect.potionStrength(), RNG.r.i(shortest, longest))); + int ticks = RNG.r.i(shortest, longest); + return PlatformKeys.id(effect.potionEffect(), log).map(key -> new Potion(key, effect.potionStrength(), ticks)); } private static double commandOffset(double offset, boolean random) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index b17b5a4e3..af6d5a3f7 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -19,17 +19,20 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.LiveWorld.Sky; -import art.arcane.iris.builtin.loot.ItemAttributeModifier; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EntityDefinition; +import art.arcane.iris.builtin.spawn.IrisEntityExtras; import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.loot.LootItems; +import art.arcane.iris.engine.loot.PlatformKeys; import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; import com.volmit.entity.EntitySpec; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; +import com.volmit.resource.ContentKey; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; @@ -39,7 +42,9 @@ import java.util.Optional; /** * Turns an entity of the pack into the {@link EntitySpec} the host spawns, making every random choice in the order Iris - * always made them: the passengers, the attribute modifiers, the leash holder and then the six pieces of equipment. + * always made them: the passengers, the attribute modifiers, the leash holder and then the six pieces of equipment. An + * entity that names no type the host could spawn resolves to nothing, after its random choices, so that the ones after + * it stay what they were. */ final class EntityResolution { private static final long PASSENGER_STREAM_BASE = 234858L; @@ -49,39 +54,50 @@ final class EntityResolution { private final LootItems items; private final Optional sky; private final EffectTimers timers; + private final ModuleLog log; /** * @param resources names the entity's loot tables by id * @param sky the sky of the world the entity appears in, whose time and weather decide which of its commands run; none while the world has no platform world + * @param log hears of keys that name nothing the platform could have */ - EntityResolution(PackResources resources, LootItems items, Optional sky, EffectTimers timers) { + EntityResolution(PackResources resources, LootItems items, Optional sky, EffectTimers timers, ModuleLog log) { this.resources = resources; this.items = items; this.sky = sky; this.timers = timers; + this.log = log; } - EntitySpec resolve(EntityDefinition entity, RNG rng) { + Optional resolve(EntityDefinition entity, RNG rng) { List passengers = new ArrayList<>(); long passengerIndex = 0; for (EntityDefinition passenger : entity.passengers()) { - passengers.add(resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++))); + resolve(passenger, rng.nextParallelRNG(PASSENGER_STREAM_BASE + passengerIndex++)).ifPresent(passengers::add); } - List attributes = drawAttributes(entity, rng); + List attributes = items.attributes(entity.attributes(), rng); List lootTables = entity.loot().tables().stream().map(resources::idOf).toList(); long lootShuffleSeed = lootTables.isEmpty() ? 0L : rng.nextLong(); Optional leashHolder = entity.leashHolder() == null ? Optional.empty() - : Optional.of(resolve(entity.leashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM))); + : resolve(entity.leashHolder(), rng.nextParallelRNG(LEASH_HOLDER_STREAM)); EntitySpec.Equipment equipment = new EntitySpec.Equipment( equip(entity.helmet(), rng), equip(entity.chestplate(), rng), equip(entity.leggings(), rng), equip(entity.boots(), rng), equip(entity.mainHand(), rng), equip(entity.offHand(), rng)); - return new EntitySpec(textOf(entity.type()), textOf(entity.specialType()), textOf(entity.reason()), - textOf(entity.customName()), flagsOf(entity), equipment, passengers, attributes, lootTables, lootShuffleSeed, - leashHolder, spawnEffectOf(entity), entity.spawnEffectRiseOutOfGround(), textOf(entity.pandaMainGene()), - textOf(entity.pandaHiddenGene()), entity.applySettingsToCustomMobAnyways(), commandsOf(entity)); + return typeOf(entity).map(type -> new EntitySpec(type, appearanceOf(entity), behaviourOf(entity), equipment, attributes, + new EntitySpec.Company(passengers, leashHolder), new EntitySpec.Drops(lootTables, lootShuffleSeed), + new EntitySpec.Arrival(spawnEffectOf(entity), commandsOf(entity)), List.of(extrasOf(entity)))); + } + + /** The provider's mob when the pack names one, otherwise the entity type. */ + private Optional typeOf(EntityDefinition entity) { + Optional provided = textOf(entity.specialType()); + if (provided.isPresent()) { + return PlatformKeys.provided(provided.get(), log); + } + return PlatformKeys.id(entity.type(), log).map(ContentKey.Registered::new); } /** A text the pack may leave out or blank, as absent then. */ @@ -89,25 +105,18 @@ final class EntityResolution { return text == null || text.isBlank() ? Optional.empty() : Optional.of(text); } - private static EntitySpec.Flags flagsOf(EntityDefinition entity) { - return new EntitySpec.Flags(entity.customNameVisible(), entity.aware(), entity.ai(), entity.glowing(), - entity.gravity(), entity.invulnerable(), entity.silent(), entity.pickupItems(), entity.removable(), - entity.keepEntity(), entity.baby()); + private static EntitySpec.Appearance appearanceOf(EntityDefinition entity) { + return new EntitySpec.Appearance(textOf(entity.customName()), entity.customNameVisible(), entity.glowing(), entity.baby()); } - private static List drawAttributes(EntityDefinition entity, RNG rng) { - List attributes = new ArrayList<>(); - for (ItemAttributeModifier modifier : entity.attributes()) { - if (rng.nextDouble() >= modifier.chance()) { - continue; - } - String attribute = modifier.attribute(); - if (attribute == null || attribute.isBlank()) { - continue; - } - attributes.add(new ItemAttribute(attribute, modifier.name(), modifier.operation(), rng.d(modifier.minAmount(), modifier.maxAmount()))); - } - return attributes; + private static EntitySpec.Behaviour behaviourOf(EntityDefinition entity) { + return new EntitySpec.Behaviour(entity.aware(), entity.ai(), entity.gravity(), entity.invulnerable(), entity.silent(), + entity.pickupItems(), entity.removable(), entity.keepEntity()); + } + + private static IrisEntityExtras extrasOf(EntityDefinition entity) { + return new IrisEntityExtras(textOf(entity.reason()), entity.spawnEffectRiseOutOfGround(), textOf(entity.pandaMainGene()), + textOf(entity.pandaHiddenGene()), entity.applySettingsToCustomMobAnyways()); } private Optional equip(LootEntry piece, RNG rng) { @@ -123,10 +132,16 @@ final class EntityResolution { if (effect == null || !timers.shouldPlayNow(effect)) { return Optional.empty(); } - return Optional.of(new EntitySpec.SpawnEffect(textOf(effect.sound()), effect.soundDistance(), effect.minPitch(), - effect.maxPitch(), effect.volume(), textOf(effect.particleEffect()), effect.particleOffset(), - effect.particleCount(), effect.particleAltX(), effect.particleAltY(), effect.particleAltZ(), - effect.randomAltX(), effect.randomAltY(), effect.randomAltZ(), effect.extra())); + Optional sound = PlatformKeys.id(effect.sound(), log).map(key -> + new EntitySpec.SpawnEffect.Sound(key, effect.soundDistance(), effect.minPitch(), effect.maxPitch(), effect.volume())); + Optional particles = PlatformKeys.id(effect.particleEffect(), log).map(key -> + new EntitySpec.SpawnEffect.Burst(key, effect.particleOffset(), effect.particleCount(), motionOf(effect), effect.extra())); + return Optional.of(new EntitySpec.SpawnEffect(sound, particles)); + } + + private static EntitySpec.SpawnEffect.Motion motionOf(AmbientEffect effect) { + return new EntitySpec.SpawnEffect.Motion(effect.particleAltX(), effect.particleAltY(), effect.particleAltZ(), + effect.randomAltX(), effect.randomAltY(), effect.randomAltZ()); } private List commandsOf(EntityDefinition entity) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 9b9097a00..c32f591c6 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -91,15 +91,15 @@ public final class EntitySpawning implements EntitySpawns { if (entity == null) { return Optional.empty(); } - return Optional.of(resolution(world).resolve(entity, entityRandom(world).rng())); + return resolution(world).resolve(entity, entityRandom(world).rng()); } @Override - public Optional marker(PackWorld world, String tag) { - if (tag.equals(CAVE_FLOOR_MARKER) || tag.equals(CAVE_CEILING_MARKER)) { + public Optional marker(PackWorld world, ResourceId tag) { + if (tag.path().equals(CAVE_FLOOR_MARKER) || tag.path().equals(CAVE_CEILING_MARKER)) { return Optional.empty(); } - SpawnMarker marker = SpawnResources.marker(world.resources(), tag); + SpawnMarker marker = SpawnResources.marker(world.resources(), tag.path()); if (marker == null) { return Optional.empty(); } @@ -187,7 +187,7 @@ public final class EntitySpawning implements EntitySpawns { private Optional planMarker(PackWorld world, Marker marker) { String spawnerKey = marker.spawner().path(); Spawner spawner = SpawnResources.spawner(world.resources(), spawnerKey); - SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker()); + SpawnMarker spawnMarker = SpawnResources.marker(world.resources(), marker.marker().path()); if (spawner == null) { return Optional.empty(); } @@ -231,15 +231,15 @@ public final class EntitySpawning implements EntitySpawns { } Range light = candidate.spawner().allowedLightLevels(); - EntitySpec spec = resolution(world).resolve(entity, entityRandom(world).rng()); - attempts.add(new Attempt(at, spec, surfaceOf(entity.surface()), - (int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface)); + resolution(world).resolve(entity, entityRandom(world).rng()).ifPresent(spec -> attempts.add(new Attempt(at, spec, + surfaceOf(entity.surface()), (int) Math.ceil(light.min()), (int) Math.floor(light.max()), checkSurface))); } private static EntityResolution resolution(PackWorld world) { LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); - LootItems items = new LootItems(world.resources().items(), live.studio()); - return new EntityResolution(world.resources(), items, live.sky(),world.state(EffectTimers.class, ignored -> new EffectTimers())); + LootItems items = new LootItems(world.resources().items(), live.studio(), world.log()); + return new EntityResolution(world.resources(), items, live.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers()), + world.log()); } private static EntityRandom entityRandom(PackWorld world) { From 7be7c311e310e3d9a61e1954dd1eb4071e2f174b Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 09:24:14 +0200 Subject: [PATCH 103/139] Batch 6 part 3: one-text start memo, LinkedBiomes in world The structure fit memo is one JSON object of terrain and stilts. Carving and floating settings implement world.LinkedBiomes and read the dimension's bands through PackSettings. --- .../builtin/carve/CarvingBiomeSettings.java | 2 +- .../iris/builtin/carve/CarvingSettings.java | 6 ++--- .../floating/FloatingChildSettings.java | 8 +++--- .../structure/NativeStructureFit.java | 25 ++++++++++++------- 4 files changed, 24 insertions(+), 17 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java index a5748eaed..3e4398221 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java @@ -22,8 +22,8 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.LinkedBiomes; import com.volmit.config.Ref; +import com.volmit.world.LinkedBiomes; import com.volmit.world.PackBiome; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java index 997571a32..16bc33f71 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java +++ b/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java @@ -22,12 +22,12 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.LinkedBiomes; import com.volmit.config.MinItems; +import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import com.volmit.world.LinkedBiomes; -import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; @@ -70,7 +70,7 @@ public final class CarvingSettings implements IrisFeature, LinkedBiomes { } @Override - public Set usedBiomes(PackResources pack, Collection dimension) { + public Set usedBiomes(PackResources pack, PackSettings dimension) { Set biomes = new LinkedHashSet<>(); for (CarvingEntry entry : entries()) { if (entry != null && entry.enabled() && entry.biome() != null && !entry.biome().isBlank()) { diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java index 36a143829..072629fdb 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java @@ -23,12 +23,12 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.LinkedBiomes; import com.volmit.config.MinItems; +import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import com.volmit.world.LinkedBiomes; -import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; @@ -58,8 +58,8 @@ public final class FloatingChildSettings implements IrisFeature, LinkedBiomes { } @Override - public Set usedBiomes(PackResources pack, Collection dimension) { - CarvingSettings carving = dimension.stream().filter(CarvingSettings.class::isInstance).map(CarvingSettings.class::cast).findFirst().orElse(null); + public Set usedBiomes(PackResources pack, PackSettings dimension) { + CarvingSettings carving = dimension.declared(CarvingSettings.class).dimension().orElse(null); Set biomes = new LinkedHashSet<>(); for (FloatingChildBiome child : children()) { if (child != null) { diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java index 1add43a90..7f46b949d 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeStructureFit.java @@ -22,13 +22,14 @@ import art.arcane.iris.builtin.structure.StructureStilts; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureYBand; import com.google.gson.Gson; +import com.google.gson.JsonObject; import com.volmit.vanilla.StartMemo; /** * How {@code iris:structure} places and fits one platform structure, or one start: how far it moves the platform's own * starts and into which band of world heights, whether they keep the platform's height, the foundation columns built - * under their pieces and how they meet the terrain. A start the module places itself carries its fit as a memo, the - * JSON of its terrain and stilts, which ownership records keep, so its later chunks use the fit it began with. + * under their pieces and how they meet the terrain. A start the module places itself carries its fit as a memo, one + * JSON object of its terrain and stilts, which the host keeps with the start, so its later chunks use the fit it began with. * * @param yBand null for no band * @param stilts null for no foundation columns @@ -40,22 +41,28 @@ public record NativeStructureFit(int yShift, StructureYBand yBand, boolean keeps public static final NativeStructureFit NONE = new NativeStructureFit(0, null, false, null, null); private static final Gson MEMO_JSON = new Gson(); - private static final String NO_STILTS = "null"; + private static final String MEMO_TERRAIN = "terrain"; + private static final String MEMO_STILTS = "stilts"; /** The fit a start's memo records: its terrain and stilts, with no vertical adjustment. */ public static NativeStructureFit of(StartMemo memo) { - StructureStilts stilts = NO_STILTS.equals(memo.foundation()) - ? null : MEMO_JSON.fromJson(memo.foundation(), StructureStilts.class); - StructureTerrain terrain = MEMO_JSON.fromJson(memo.terrain(), StructureTerrain.class); - if (terrain == null) { + JsonObject text = MEMO_JSON.fromJson(memo.text(), JsonObject.class); + if (text == null || !text.has(MEMO_TERRAIN)) { throw new IllegalStateException("A start's memo has no terrain fit: " + memo); } + StructureTerrain terrain = MEMO_JSON.fromJson(text.get(MEMO_TERRAIN), StructureTerrain.class); + StructureStilts stilts = text.has(MEMO_STILTS) ? MEMO_JSON.fromJson(text.get(MEMO_STILTS), StructureStilts.class) : null; return new NativeStructureFit(0, null, false, stilts, terrain); } - /** The memo of a start placed with this fit's terrain and stilts. */ + /** The memo of a start placed with this fit's terrain and stilts: one JSON object holding both. */ public StartMemo memo() { - return new StartMemo(MEMO_JSON.toJson(resolvedTerrain()), MEMO_JSON.toJson(stilts)); + JsonObject text = new JsonObject(); + text.add(MEMO_TERRAIN, MEMO_JSON.toJsonTree(resolvedTerrain())); + if (stilts != null) { + text.add(MEMO_STILTS, MEMO_JSON.toJsonTree(stilts)); + } + return new StartMemo(MEMO_JSON.toJson(text)); } /** The terrain fitting; the structure's own adaptation (SOURCE) when none is set. */ From 45cb5e4bcf3fbf8f3b5b18eb462b0d920f4cff13 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 10:09:13 +0200 Subject: [PATCH 104/139] Batch 6 part 4a: built-ins on purpose seeds and the running world Finding 40, first step. IrisSeeds and LiveWorld are gone: seeds are world.seed(IrisSeedPurposes.X), which Iris answers with its legacy seeds, and the loot, spawn, effect and tree services read world.running() (TerrainSampler, FeatureSettings, sky, highest block). The block-biome rule is the module's BlockBiomes. ObjectHost loses its layout and settings lookups (columnSettings, regionAt, biome and region declarations, cave lava and fluid heights, upper objects, procedural): object placing reads the chunk's terrain, settings and upper dimension, and caches procedural objects in world state. Object loot moved to ObjectHost.placedLoot; spawner cooldowns stay an Iris extension because Iris persists them with the world. FloatingHost loses surfaceBiome and biome(key) to the running layout and PackResources. --- README.md | 21 +-- .../art/arcane/iris/builtin/IrisSeed.java | 31 ----- .../arcane/iris/builtin/IrisSeedPurposes.java | 51 ++++++++ .../art/arcane/iris/builtin/IrisSeeds.java | 27 ---- .../art/arcane/iris/builtin/LiveWorld.java | 122 ------------------ .../iris/builtin/floating/FloatingHost.java | 12 +- .../iris/builtin/objects/ObjectHost.java | 80 ++++++------ .../art/arcane/iris/builtin/package-info.java | 3 +- .../iris/builtin/spawn/SpawnCooldowns.java | 4 +- .../iris/builtin/terrain/TerrainPalettes.java | 5 +- .../iris/engine/actuator/OreWarmUp.java | 5 +- .../iris/engine/actuator/TerrainOres.java | 5 +- .../iris/engine/actuator/TerrainShaper.java | 5 +- .../engine/decorator/BiomeDecorators.java | 5 +- .../engine/decorator/DecorationScene.java | 5 +- .../arcane/iris/engine/loot/BlockBiomes.java | 52 ++++++++ .../iris/engine/loot/BlockDropping.java | 24 ++-- .../arcane/iris/engine/loot/LootGiving.java | 23 ++-- .../arcane/iris/engine/loot/LootTables.java | 39 ++++-- .../iris/engine/loot/PlacementLoot.java | 20 ++- .../mantle/components/ChunkObjectPlacing.java | 35 +++-- .../components/FloatingObjectPlacing.java | 42 ++++-- .../mantle/components/ObjectLocating.java | 2 +- .../mantle/components/ObjectPlacing.java | 12 +- .../mantle/components/ObjectWarmUp.java | 11 +- .../mantle/components/PlacementReach.java | 2 +- .../engine/mantle/components/TreeGrowing.java | 31 +++-- .../iris/engine/modifier/CarveModule.java | 5 +- .../iris/engine/modifier/DepositPlacer.java | 5 +- .../iris/engine/modifier/FloatingIslands.java | 7 +- .../engine/modifier/SurfaceSmoothing.java | 5 +- .../procedural/ResolvedProceduralObjects.java | 20 ++- .../terrain/carving/CarvingResolver.java | 5 +- .../floating/FloatingIslandSample.java | 2 +- .../terrain/floating/FloatingWorld.java | 63 +++++---- .../floating/ResolvedFloatingChild.java | 8 +- .../iris/engine/spawn/AmbientEffecting.java | 19 +-- .../iris/engine/spawn/EntityResolution.java | 2 +- .../iris/engine/spawn/EntitySpawning.java | 63 ++++----- .../iris/engine/spawn/SpawnConditions.java | 2 +- .../arcane/iris/engine/spawn/SpawnerGate.java | 38 +++--- 41 files changed, 459 insertions(+), 459 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/IrisSeed.java create mode 100644 src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java delete mode 100644 src/main/java/art/arcane/iris/builtin/IrisSeeds.java delete mode 100644 src/main/java/art/arcane/iris/builtin/LiveWorld.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java diff --git a/README.md b/README.md index 864038fa2..ae8a17454 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,8 @@ the same JSON as Iris's `IrisObjectPlacement` and keeps the JSON it was read fro a placement as their own class (`ObjectPlacements.host`). What a jar cannot do, Iris does through the facades `ObjectHost` and `ObjectChunk` in `art.arcane.iris.builtin.objects`: loading and scaling the pack's objects, placing one with the placement stages into the chunk's mantle (on the surface, in a cave inside the cave's bounds, or hung from the terrain above), reading the -carved space the cave carver planned, and the layout around a position. `ObjectPlacing` and its helpers (`ChunkObjectPlacing`, +carved space the cave carver planned, and the loot an object placed at a block defines; the layout, the settings of a column and +the upper dimension's objects come from IrisApi (`TerrainSampler`, `FeatureSettings`, `UpperDimension`). `ObjectPlacing` and its helpers (`ChunkObjectPlacing`, `CaveAnchors`, `PlacementReach`) decide what to place and where. The procedural generators (`engine/object/procedural`) stay compiled in, behind `ProceduralPlacement`, until they build `GeneratedObject`s instead of Iris objects. `iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to @@ -183,7 +184,7 @@ The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot`, `iris: written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks; the placement stages read the placement being run through the `ObjectPlacement` facade, and the loot and -spawn services, which have no chunk to ask, ask `LiveWorld` (both below). Without the jar a pack's world has no caves, vanilla +spawn services, which have no chunk to ask, ask the running world (`world.running()`, IrisApi's `RunningWorld`). Without the jar a pack's world has no caves, vanilla placed features, loot, block drops, entity spawns or ambient effects, and its biomes' `loot`, `blockDrops`, `entitySpawners` and `effects` are not read. Iris no longer compiles them in (`IrisModuleHost.generationModules()`); every pack gets them from the bundled jar. A pack @@ -193,14 +194,14 @@ none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps e `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never -through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`IrisSeeds`, `LiveWorld`, -`ObjectHost`, `FloatingHost`, `StructureHost`), `context.extension(X.class)` for what belongs to one invocation (`ObjectPlacement` +through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`ObjectHost`, +`FloatingHost`, `StructureHost`, `spawn.SpawnCooldowns`), `context.extension(X.class)` for what belongs to one invocation (`ObjectPlacement` in a placement stage, `MatterMantle` in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out -before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. `IrisSeeds` gives -Iris's per-feature world seeds (`seeds.seed(IrisSeed.CARVE)`), so existing worlds generate the same; `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same -layers, and a layer's noise is built once per world by whichever asks first), `LiveWorld` (what the loot and spawn services ask a -running world, outside any chunk stage: the layout and settings at a block, the platform's weather and loot tables, the -objects' loot and the spawner cooldowns Iris saves with the world; values only), +before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are +IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), which Iris answers with the seeds its worlds always +had, so existing worlds generate the same; `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same +layers, and a layer's noise is built once per world by whichever asks first), `spawn.SpawnCooldowns` (the spawner cooldowns +Iris saves with the world's data, so they survive a restart), `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`, which the modules register as held types, because Iris's `IrisObjectPlacement` holds them). The placement stages need more of the object being @@ -219,5 +220,5 @@ so it writes nothing outside its chunk. What a cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`terrain.BiomeLayers`, `terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its -absolute world Y bands convert with `PackWorld.minHeight()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read) +absolute world Y bands convert with `PackWorld.minWorldY()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read) and `scaled(...)`. `caveLavaHeight` and `upperDimensionCarving` are its dimension settings. diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeed.java b/src/main/java/art/arcane/iris/builtin/IrisSeed.java deleted file mode 100644 index 43f79f943..000000000 --- a/src/main/java/art/arcane/iris/builtin/IrisSeed.java +++ /dev/null @@ -1,31 +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.builtin; - -import com.volmit.world.PackWorld; - -/** - * The seeds Iris derives from a world's seed for its own features. Iris derives them one after another from a shared - * random, so they cannot be worked out from the world seed alone. Built-in modules seed their randoms and noise with - * them, so worlds generated before the features were modules generate the same; a pack module derives its own seeds - * from {@link PackWorld#seed()}. A world Iris generates answers for them through its {@link IrisSeeds} extension. - */ -public enum IrisSeed { - BIOME, CARVE, COMPLEX, COMPONENT, DECORATOR, DEPOSIT, ENTITY, LOOT, MANTLE, POST, TERRAIN -} diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java new file mode 100644 index 000000000..eb048f802 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java @@ -0,0 +1,51 @@ +/* + * 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.builtin; + +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +/** + * The purposes Iris's built-in modules ask {@link PackWorld#seed(ResourceId)} for. Iris answers each with the seed its + * worlds always used for that feature, derived one after another from a shared random rather than by the API's rule, + * so worlds generated before the features were modules generate the same. + */ +public final class IrisSeedPurposes { + public static final ResourceId BIOME = purpose("biome"); + public static final ResourceId CARVE = purpose("carve"); + public static final ResourceId COMPLEX = purpose("complex"); + public static final ResourceId COMPONENT = purpose("component"); + public static final ResourceId DECORATOR = purpose("decorator"); + public static final ResourceId DEPOSIT = purpose("deposit"); + public static final ResourceId ENTITY = purpose("entity"); + public static final ResourceId LOOT = purpose("loot"); + public static final ResourceId MANTLE = purpose("mantle"); + public static final ResourceId POST = purpose("post"); + public static final ResourceId TERRAIN = purpose("terrain"); + + private static final String NAMESPACE = "iris"; + private static final String PATH_PREFIX = "seed/"; + + private IrisSeedPurposes() { + } + + private static ResourceId purpose(String name) { + return new ResourceId(NAMESPACE, PATH_PREFIX + name); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeeds.java b/src/main/java/art/arcane/iris/builtin/IrisSeeds.java deleted file mode 100644 index a2f6141a0..000000000 --- a/src/main/java/art/arcane/iris/builtin/IrisSeeds.java +++ /dev/null @@ -1,27 +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.builtin; - -/** - * The {@link IrisSeed}s of a world Iris generates, which it offers as an extension of the world: - * {@code world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE)}. - */ -public interface IrisSeeds { - long seed(IrisSeed seed); -} diff --git a/src/main/java/art/arcane/iris/builtin/LiveWorld.java b/src/main/java/art/arcane/iris/builtin/LiveWorld.java deleted file mode 100644 index ba10ed4c9..000000000 --- a/src/main/java/art/arcane/iris/builtin/LiveWorld.java +++ /dev/null @@ -1,122 +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.builtin; - -import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.builtin.loot.ObjectVanillaLoot; -import art.arcane.iris.builtin.spawn.SpawnCooldowns; -import com.volmit.IrisFeature; -import com.volmit.resource.ResourceId; -import com.volmit.geometry.BlockPosition; - -import java.util.List; -import java.util.Optional; -import java.util.Set; - -/** - * What Iris's own services ask a world that is running, outside any chunk stage: the layout and the objects at a block - * as they are now, the platform's weather and loot tables, and the data Iris keeps with the world. A chunk stage reads - * the layout through its {@link com.volmit.world.TerrainSampler}; a service has no chunk, so it asks here. - * - *

X and Z are world coordinates; Y is the height above the dimension's bottom, as everywhere in IrisApi. - * Safe to use from any thread. Iris offers it as an extension of its worlds: {@code world.extension(LiveWorld.class)}. - */ -public interface LiveWorld { - /** The platform's block Y of height 0, the dimension's bottom: a position's height plus this is its Y in the platform. */ - int bottomY(); - - /** The pack biome at the column's surface. */ - ResourceId surfaceBiome(int x, int z); - - /** The pack biome at the block when it lies in a cave biome, else the surface biome. */ - ResourceId caveBiome(int x, int y, int z); - - /** What the surface biome of the column is for: land, sea, shore or cave. */ - BiomeKind surfaceKind(int x, int z); - - /** The terrain's height at the column, before anything was placed on it. */ - double terrainHeight(int x, int z); - - /** The height of the highest block placed in the column, with the terrain and what objects and structures added. */ - int highestBlock(int x, int z, boolean ignoreFluid); - - /** - * The settings of {@code type} that the dimension, the region or a biome declares for the block, as they are - * decoded for generation; empty when that level declares none. - */ - Optional settings(Class type, Level level, int x, int y, int z); - - /** The time and weather of the world, or empty when the world has no platform world yet. */ - Optional sky(); - - /** Whether the world is a studio world. */ - boolean studio(); - - /** The keys of the loot tables the platform has, such as {@code minecraft:chests/simple_dungeon}. They do not change while the world runs. */ - Set platformLootTables(); - - /** The floors of the caves marked in the chunk, none on a platform that cannot read them. */ - List caveFloors(int chunkX, int chunkZ); - - /** The loot the object placed at the block defines, or empty when no object placement covers the block. */ - Optional objectLoots(int x, int y, int z); - - /** The cooldowns of the world's spawners. */ - SpawnCooldowns spawnCooldowns(); - - /** Where the layout is asked: the dimension, the region of the column, or one of its biomes. */ - enum Level { - DIMENSION, - REGION, - /** The biome at the column's surface. */ - SURFACE_BIOME, - /** The biome at the block: a cave biome below the surface, the surface biome above. */ - BIOME, - /** The cave biome at the block, the surface biome when it has none. */ - CAVE_BIOME - } - - /** What a biome is for, which decides the spawners that fit it. */ - enum BiomeKind { - LAND, SEA, SHORE, CAVE - } - - /** The world's time of day in ticks, whether it is storming and whether it thunders. */ - record Sky(long time, boolean storming, boolean thundering) { - } - - /** - * The loot an object placement gives its containers. - * - * @param packTables tables of the pack - * @param platformTables tables of the platform - * @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes - */ - record ObjectLoots(List packTables, List platformTables, boolean overridesGlobalLoot) { - public ObjectLoots { - packTables = List.copyOf(packTables); - platformTables = List.copyOf(platformTables); - } - - /** Whether the placement names any table. */ - public boolean defined() { - return !packTables.isEmpty() || !platformTables.isEmpty(); - } - } -} diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java index 939981af3..82b806f69 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java @@ -27,17 +27,11 @@ import com.volmit.resource.ResourceId; import java.util.Optional; /** - * What {@code iris:floating} asks of Iris beyond the API: the biome of any column, a biome's own terrain height, the sky - * biome an island paints, and placing Iris objects against an island. Iris offers it as an extension of its worlds and - * of the settings of the pack it loads: {@code world.extension(FloatingHost.class)}. + * What {@code iris:floating} asks of Iris beyond the API: a biome's own terrain height, the sky biome an island paints, + * and placing Iris objects against an island. Iris offers it as an extension of its worlds: + * {@code world.extension(FloatingHost.class)}. */ public interface FloatingHost { - /** The biome of the column's surface, the biome an island grows from; any column, not only the chunk's. */ - ResourceId surfaceBiome(int worldX, int worldZ); - - /** The biome {@code key} names in the pack; empty when the pack has none. */ - Optional biome(String key); - /** The height the terrain generators of {@code biome} give the column, as Iris shapes the biome's terrain with {@code seed}. */ double biomeHeight(ResourceId biome, int worldX, int worldZ, long seed); diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java index 90d41ce2e..e8c09d44f 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java @@ -18,36 +18,30 @@ package art.arcane.iris.builtin.objects; +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; import art.arcane.volmlib.util.math.RNG; -import com.volmit.config.Level; import com.volmit.IrisFeature; -import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; import com.volmit.generation.InvocationContext; import com.volmit.resource.ResourceId; import java.util.List; import java.util.Optional; -import java.util.function.Function; /** - * What {@code iris:objects} asks of Iris: the objects of the pack, how Iris scales and places them, and the layout around - * a world position. Iris offers it as an extension of its worlds and of the settings of the pack it loads: - * {@code world.extension(ObjectHost.class)}, {@code settings.extension(ObjectHost.class)}. Nothing here hands out the - * engine. + * What {@code iris:objects} asks of Iris's object system: the pack's objects, how Iris scales, picks and places them, and + * the loot of what it placed. The layout, settings and seeds around an object are the API's. Iris offers it as an + * extension of its worlds and of the settings of the pack it loads: {@code world.extension(ObjectHost.class)}, + * {@code settings.extension(ObjectHost.class)}. + * + *

Objects are named by the keys placements hold ({@link ObjectPlacement#place()}). The randoms are VolmLib's + * {@link RNG}, since the streams Iris draws objects with decide where existing worlds have them. */ public interface ObjectHost { - /** Whether Iris's debug setting is on. */ + /** Whether Iris's debug setting is on, which makes object placing trace what it does. */ boolean debugging(); - /** The height, above the dimension's bottom, up to which caves are filled with lava. */ - int caveLavaHeight(); - - /** The height of the dimension's fluid. */ - int fluidHeight(); - - /** The settings that apply at a world column, for work outside a chunk's generation. */ - FeatureSettings columnSettings(); - /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ RNG chunkRandom(int chunkX, int chunkZ); @@ -69,42 +63,42 @@ public interface ObjectHost { /** Builds what placing the placement would build on first use, so the first chunk to place it does not wait. */ void warm(ObjectPlacement placement, RNG rng); - /** The procedural objects {@code settings} declare, made placeable by {@code resolve} once per world. */ - List procedural(ProceduralObjectSettings settings, - Function> resolve); - /** A builder for one bake of objects made block by block. */ ObjectBuilder builder(); - /** The object settings of the biome and the region of the dimension stacked above, at the column; none where nothing sits above. */ - Optional upperObjects(int worldX, int worldZ); - /** Places the object into {@code sink}, which is outside any chunk's generation, such as a growing sapling's tree. */ int placeInto(PlaceableObject object, int x, int y, int z, ObjectPlacement placement, ObjectSink sink, RNG rng); - /** The region at the column. */ - ResourceId regionAt(int worldX, int worldZ); + /** The loot of the object placed at the block; empty when no object placement covers the block. */ + Optional placedLoot(int x, int y, int z); - /** The surface biome at the column. */ - ResourceId surfaceBiomeAt(int worldX, int worldZ); - - /** The biome at the position, which is the cave biome underground. */ - ResourceId biomeAt(int worldX, int y, int worldZ); - - /** The settings the biome declares itself, whichever column it is found at; empty when it declares none. */ - Optional biomeDeclaration(ResourceId biome, Class type); - - /** The settings the region declares itself; empty when it declares none. */ - Optional regionDeclaration(ResourceId region, Class type); - - /** Every region and every reachable biome that declares the settings, by the key the pack knows it by, regions first. */ + /** + * Every region and every reachable biome that declares the settings, regions first. Unlike the sources of + * {@link com.volmit.config.PackSettings#declared}, which name the resource that declares them, each is named by the + * id a {@link com.volmit.world.BiomeSample} gives it. + */ List> declarations(Class type); - /** What the dimension stacked above declares to place at a column, where each is null when its level declares none. */ - record UpperObjects(ObjectSettings biome, ObjectSettings region, String biomeKey, String regionKey) { + /** One region's or biome's declaration of settings, by the id of the region or biome. */ + record Declaration(Level level, ResourceId id, F settings) { } - /** One region's or biome's declaration of settings. */ - record Declaration(Level level, String key, F settings) { + /** + * The loot an object placement gives its containers. + * + * @param packTables tables of the pack + * @param platformTables tables of the platform + * @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes + */ + record ObjectLoots(List packTables, List platformTables, boolean overridesGlobalLoot) { + public ObjectLoots { + packTables = List.copyOf(packTables); + platformTables = List.copyOf(platformTables); + } + + /** Whether the placement names any table. */ + public boolean defined() { + return !packTables.isEmpty() || !platformTables.isEmpty(); + } } } diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 08eb9cb3a..bd72b7c93 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -29,7 +29,8 @@ *

* Besides those, it holds what the compiled-in built-ins and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.IrisSeed}, {@link art.arcane.iris.builtin.LiveWorld}, {@link art.arcane.iris.builtin.objects.ObjectHost}), + * ({@link art.arcane.iris.builtin.spawn.SpawnCooldowns}, {@link art.arcane.iris.builtin.objects.ObjectHost}), the seed purposes Iris + * answers with its legacy seeds ({@link art.arcane.iris.builtin.IrisSeedPurposes}), * and per-world state several of them use ({@link art.arcane.iris.builtin.terrain.LayerBlocks}, * {@link art.arcane.iris.builtin.terrain.BiomeLayers}, {@link art.arcane.iris.builtin.terrain.TerrainPalettes}). Keep them few: each is * a promise. diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java index ca17005ee..8bfb4f624 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java @@ -22,8 +22,8 @@ import java.util.function.ToLongFunction; /** * When spawners last fired, which Iris keeps with the world's data so that a spawner's rates hold across restarts. Rates - * count per spawner, by the key the pack names it by, in the world and in each chunk. Reached through - * {@link art.arcane.iris.builtin.LiveWorld#spawnCooldowns()}. + * count per spawner, by the key the pack names it by, in the world and in each chunk. Iris offers it as an extension of + * its worlds: {@code world.extension(SpawnCooldowns.class)}. */ public interface SpawnCooldowns { /** Whether the spawner may fire in the world again, {@code intervalMilliseconds} after it last did. */ diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java index 6ba518f2d..837713836 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.builtin.terrain; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; @@ -63,7 +62,7 @@ public final class TerrainPalettes { TerrainPalettes(PackWorld world) { this.world = world; - this.complexSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPLEX); + this.complexSeed = world.seed(IrisSeedPurposes.COMPLEX); } /** The palettes of {@code world}. */ diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java index eb2c3866a..81069d8b5 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.terrain.OreSettings; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.FeatureSettings.Entry; @@ -50,7 +49,7 @@ final class OreWarmUp { OreWarmUp(PackWorld world, TerrainOres ores) { this.world = world; this.ores = ores; - this.root = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT) + ROOT_SEED_SALT); + this.root = new RNG(world.seed(IrisSeedPurposes.COMPONENT) + ROOT_SEED_SALT); } void warm() { diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java index 4691b0ad7..aee9ca754 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.terrain.OreSettings; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; @@ -37,7 +36,7 @@ final class TerrainOres { TerrainOres(PackWorld world) { this.resources = world.resources(); - this.terrainSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.TERRAIN); + this.terrainSeed = world.seed(IrisSeedPurposes.TERRAIN); } /** The ores of {@code world}. */ diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index ce7c6c545..c960aeab4 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.terrain.BedrockSettings; import art.arcane.iris.builtin.terrain.HideOresSettings; import art.arcane.iris.builtin.terrain.OreSettings; @@ -67,7 +66,7 @@ final class TerrainShaper { this.palettes = palettes; this.layers = layers; this.ores = ores; - this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.TERRAIN)); + this.rng = new RNG(world.seed(IrisSeedPurposes.TERRAIN)); this.levelsBelowTheDimensionDeclareOres = world.settings().declared(OreSettings.class).entries().stream() .anyMatch(entry -> entry.level() != Level.DIMENSION); } diff --git a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java index 6d55fd58e..67888f7ca 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java +++ b/src/main/java/art/arcane/iris/engine/decorator/BiomeDecorators.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.engine.decorator; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.decorant.Decorator; @@ -60,7 +59,7 @@ public final class BiomeDecorators { this.world = world; this.resources = world.resources(); this.log = world.log(); - this.decoratorSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.DECORATOR); + this.decoratorSeed = world.seed(IrisSeedPurposes.DECORATOR); } /** The world's decorators, kept in its state store. */ diff --git a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java index 8d7df896b..485f82150 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java +++ b/src/main/java/art/arcane/iris/engine/decorator/DecorationScene.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.engine.decorator; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; @@ -53,7 +52,7 @@ public final class DecorationScene { public static DecorationScene of(ChunkStageContext context) { Mantle mantle = context.mantle(); return new DecorationScene(context.blocks(),context.world().resources().blocks(), context.terrain(), - mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), context.world().extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT), + mantle == null ? null : mantle.blocks(), BiomeDecorators.of(context.world()), context.world().seed(IrisSeedPurposes.COMPONENT), context.log()); } diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java b/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java new file mode 100644 index 000000000..56b044289 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java @@ -0,0 +1,52 @@ +/* + * 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.loot; + +import com.volmit.IrisFeature; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; + +/** + * The biome of a block in a running world, as block drops and ambient effects read it: the cave biome where the block + * lies at least two blocks under the column's highest solid block, the surface biome everywhere else. + */ +public final class BlockBiomes { + private static final int CAVE_DEPTH_BELOW_HIGHEST_BLOCK = 2; + + private BlockBiomes() { + } + + public static ResourceId biomeAt(RunningWorld running, int x, int y, int z) { + TerrainSampler layout = running.layout(); + ResourceId surface = layout.surfaceBiome(x, z); + if (!layout.bounds().contains(x, y, z) || y > running.highestBlock(x, z, true) - CAVE_DEPTH_BELOW_HIGHEST_BLOCK) { + return surface; + } + return layout.caveBiome(x, y, z).orElse(surface); + } + + /** The settings the biome of the block declares; empty when it declares none. */ + public static Optional declaredAt(RunningWorld running, Class type, BlockPosition at) { + return running.settings().declaredBy(biomeAt(running, at.x(), at.y(), at.z()), type); + } +} diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index 25da5e360..def6c09d8 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -18,19 +18,21 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.LiveWorld; -import art.arcane.iris.builtin.LiveWorld.Level; import art.arcane.iris.builtin.loot.BlockDrop; import art.arcane.iris.builtin.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.item.ItemDrop; import com.volmit.service.BlockDrops; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -41,17 +43,15 @@ import java.util.concurrent.ConcurrentMap; public final class BlockDropping implements BlockDrops { @Override public Result drops(PackWorld world, Broken broken) { - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); - int x = broken.position().x(); - int y = broken.position().y(); - int z = broken.position().z(); + RunningWorld running = world.running().orElseThrow(); String brokenKey = world.resources().blocks().find(broken.block().key()).orElse(broken.block()).key(); ResolvedDrops resolved = world.state(ResolvedDrops.class, ignored -> new ResolvedDrops()); + SettingsStack column = running.settings().at(BlockDropSettings.class, broken.position().x(), broken.position().z()); - List providers = dropsFor(live, Level.BIOME, x, y, z, brokenKey, resolved, world); + List providers = dropsFor(BlockBiomes.declaredAt(running, BlockDropSettings.class, broken.position()), brokenKey, resolved, world); if (providers.stream().noneMatch(provider -> provider.drop().skipParents())) { - providers.addAll(dropsFor(live, Level.REGION, x, y, z, brokenKey, resolved, world)); - providers.addAll(dropsFor(live, Level.DIMENSION, x, y, z, brokenKey, resolved, world)); + providers.addAll(dropsFor(column.level(Level.REGION), brokenKey, resolved, world)); + providers.addAll(dropsFor(column.dimension(), brokenKey, resolved, world)); } LootItems items = new LootItems(world.resources().items(), false, world.log()); @@ -73,10 +73,10 @@ public final class BlockDropping implements BlockDrops { } } - private static List dropsFor(LiveWorld live, Level level, int x, int y, int z, String brokenKey, - ResolvedDrops resolved, PackWorld world) { + private static List dropsFor(Optional declared, String brokenKey, ResolvedDrops resolved, + PackWorld world) { List matching = new ArrayList<>(); - for (BlockDrop drop : live.settings(BlockDropSettings.class, level, x, y, z).map(BlockDropSettings::drops).orElse(List.of())) { + for (BlockDrop drop : declared.map(BlockDropSettings::drops).orElse(List.of())) { ResolvedBlockDrop candidate = resolved.of(drop, world); if (candidate.dropsFor(brokenKey)) { matching.add(candidate); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 46e314993..9d2c266a3 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -18,11 +18,10 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; -import art.arcane.iris.builtin.LiveWorld; -import art.arcane.iris.builtin.LiveWorld.ObjectLoots; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.loot.LootResolver; +import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.builtin.objects.ObjectHost.ObjectLoots; import art.arcane.iris.builtin.loot.LootTable; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; @@ -42,19 +41,19 @@ import java.util.Optional; public final class LootGiving implements Loot { @Override public List tables(PackWorld world, Site site) { - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); int x = site.position().x(); int z = site.position().z(); int relativeY = site.position().y(); - int worldY = relativeY + live.bottomY(); + int worldY = relativeY + world.minWorldY(); RNG rng = LootResolver.containerRng(lootSeed(world), x, worldY, z); List sources = new ArrayList<>(); boolean objectLootDefined = site.nativeLootDefined(); - Optional objectLoots = site.container().isEmpty() ? Optional.empty() : live.objectLoots(x, relativeY, z); + Optional objectLoots = site.container().isEmpty() ? Optional.empty() + : world.extension(ObjectHost.class).orElseThrow().placedLoot(x, relativeY, z); if (objectLoots.isPresent()) { objectLootDefined = objectLootDefined || objectLoots.get().defined(); - Source picked = placementLoot(world, live).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(), + Source picked = placementLoot(world).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(), site.container().get(), rng, x, worldY, z); if (picked != null) { sources.add(picked); @@ -75,16 +74,16 @@ public final class LootGiving implements Loot { if (table == null) { return List.of(); } - int worldY = site.position().y() + world.extension(LiveWorld.class).orElseThrow().bottomY(); + int worldY = site.position().y() + world.minWorldY(); return new LootItems(world.resources().items(), site.debug(), world.log()) .draw(tableId.path(), table, lootSeed(world), site.position().x(), worldY, site.position().z()); } - private static PlacementLoot placementLoot(PackWorld world, LiveWorld live) { - return new PlacementLoot(world.resources(), live::platformLootTables, lootSeed(world), world.log()); + private static PlacementLoot placementLoot(PackWorld world) { + return new PlacementLoot(world.resources(), () -> world.running().orElseThrow().platformLootTables(), lootSeed(world), world.log()); } private static long lootSeed(PackWorld world) { - return world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.LOOT); + return world.seed(IrisSeedPurposes.LOOT); } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootTables.java b/src/main/java/art/arcane/iris/engine/loot/LootTables.java index a85432ac1..b82a8a6b7 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootTables.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootTables.java @@ -18,16 +18,20 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.LiveWorld; -import art.arcane.iris.builtin.LiveWorld.Level; import art.arcane.iris.builtin.loot.LootMode; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSampler; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.function.Function; /** @@ -63,9 +67,18 @@ public final class LootTables { return LootResolver.spatialOneIn(lootSeed, identity, entryIndex, x, y, z, rarity); } - /** The loot settings the level declares at the block; the defaults, which add nothing, when it declares none. */ - private static LootSettings settingsAt(LiveWorld live, Level level, int x, int relativeY, int z) { - return live.settings(LootSettings.class, level, x, relativeY, z).orElseGet(LootSettings::new); + /** The declared loot settings; the defaults, which add nothing, when none are declared. */ + private static LootSettings orDefaults(Optional declared) { + return declared.orElseGet(LootSettings::new); + } + + /** The cave biome of a block under the terrain's surface, when it is not the column's surface biome. */ + private static Optional distinctCaveBiome(TerrainSampler layout, int x, int relativeY, int z) { + if (relativeY >= layout.surfaceY(x, z) || !layout.bounds().contains(x, relativeY, z)) { + return Optional.empty(); + } + ResourceId surface = layout.surfaceBiome(x, z); + return layout.caveBiome(x, relativeY, z).filter(cave -> !cave.equals(surface)); } /** @@ -83,15 +96,17 @@ public final class LootTables { boolean objectLootDefined, Function mapper ) { - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); - boolean belowSurface = relativeY < live.terrainHeight(x, z); - boolean distinctContextualBiome = belowSurface && !live.caveBiome(x, relativeY, z).equals(live.surfaceBiome(x, z)); + RunningWorld running = world.running().orElseThrow(); + Optional distinctCaveBiome = distinctCaveBiome(running.layout(), x, relativeY, z); + SettingsStack column = running.settings().at(LootSettings.class, x, z); - LootSettings dimensionLoot = settingsAt(live, Level.DIMENSION, x, relativeY, z); - LootSettings regionLoot = settingsAt(live, Level.REGION, x, relativeY, z); - LootSettings surfaceLoot = settingsAt(live, Level.SURFACE_BIOME, x, relativeY, z); + LootSettings dimensionLoot = orDefaults(column.dimension()); + LootSettings regionLoot = orDefaults(column.level(Level.REGION)); + LootSettings surfaceLoot = orDefaults(column.level(Level.BIOME)); double multiplier = dimensionLoot.multiplier() * regionLoot.multiplier() * surfaceLoot.multiplier(); - LootSettings contextualLoot = distinctContextualBiome ? settingsAt(live, Level.CAVE_BIOME, x, relativeY, z) : null; + LootSettings contextualLoot = distinctCaveBiome + .map(cave -> orDefaults(running.settings().declaredBy(cave, LootSettings.class))) + .orElse(null); if (contextualLoot != null) { multiplier *= contextualLoot.multiplier(); } diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java index 7f39aaa0b..4ddb14bea 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacementLoot.java @@ -45,12 +45,12 @@ final class PlacementLoot { private static final char PROPERTIES_START = '['; private final PackResources resources; - private final Supplier> platformTables; + private final Supplier> platformTables; private final long lootSeed; private final ModuleLog log; - /** @param platformTables the keys of the loot tables the platform has, asked for only when a placement names one */ - PlacementLoot(PackResources resources, Supplier> platformTables, long lootSeed, ModuleLog log) { + /** @param platformTables the ids of the loot tables the platform has, asked for only when a placement names one */ + PlacementLoot(PackResources resources, Supplier> platformTables, long lootSeed, ModuleLog log) { this.resources = resources; this.platformTables = platformTables; this.lootSeed = lootSeed; @@ -92,10 +92,20 @@ final class PlacementLoot { private Loot.Source platformSource(String name, int x, int worldY, int z) { String key = platformKey(name); - if (key == null || !platformTables.get().contains(key)) { + ResourceId table = key == null ? null : platformTableId(key); + if (table == null || !platformTables.get().contains(table)) { + return null; + } + return new Loot.PlatformTable(table, LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z)); + } + + /** The id of the platform table the key names, or null for a key that is no id, which names no table. */ + private static ResourceId platformTableId(String key) { + try { + return ResourceId.parse(key); + } catch (IllegalArgumentException notAnId) { return null; } - return new Loot.PlatformTable(ResourceId.parse(key), LootTables.seed(lootSeed, LootTables.platformIdentity(key), x, worldY, z)); } /** A placement's name for a platform table as the platform's key for it, or null for a name that cannot be one. */ diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 1c5001d9b..337d67dab 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -20,6 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.objects.CavePlacement; import art.arcane.iris.builtin.objects.ObjectChunk; @@ -40,6 +41,7 @@ import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisFeature; import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Level; import com.volmit.config.SettingsStack; import com.volmit.resource.ResourceId; @@ -99,7 +101,7 @@ final class ChunkObjectPlacing { this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && host.debugging(); this.golden = chunk.goldenDebug(chunkX, chunkZ); this.worldHeight = context.mantle().bounds().maxY(); - this.caveLavaHeight = host.caveLavaHeight(); + this.caveLavaHeight = Optional.ofNullable(dimensionLevel(CaveLavaHeightSettings.class)).orElseGet(CaveLavaHeightSettings::new).height(); this.effective = new EffectivePlacements(dimensionRequiresSurfaceSupport(), dimensionSurfaceSupportBuffer()); this.caves = new CaveSettings(dimensionLevel(CaveProfile.class)); } @@ -125,8 +127,8 @@ final class ChunkObjectPlacing { /** The region and biomes at the chunk's centre and what each declares. */ private Column readColumn() { - ResourceId region = host.regionAt(centerX, centerZ); - ResourceId surface = host.surfaceBiomeAt(centerX, centerZ); + ResourceId region = terrain.biome(centerX, terrain.bounds().minY(), centerZ).region(); + ResourceId surface = terrain.surfaceBiome(centerX, centerZ); int surfaceY = terrain.surfaceHeight(centerX, centerZ); ResourceId cave = resolveCaveObjectBiome(surfaceY, surface); return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), proceduralOf(cave, region, surface), @@ -141,7 +143,7 @@ final class ChunkObjectPlacing { if (sampled.isEmpty() || sampled.get().equals(surfaceBiome)) { continue; } - if (hasCarvingObjects(host.biomeDeclaration(sampled.get(), ObjectSettings.class))) { + if (hasCarvingObjects(context.settings().declaredBy(sampled.get(), ObjectSettings.class))) { ladderChoice = sampled.get(); } } @@ -178,7 +180,7 @@ final class ChunkObjectPlacing { if (cave.equals(surface)) { return levelValue(declared, Level.BIOME); } - return host.biomeDeclaration(cave, type).orElse(null); + return context.settings().declaredBy(cave, type).orElse(null); } private F dimensionLevel(Class type) { @@ -395,7 +397,7 @@ final class ChunkObjectPlacing { } private List proceduralPlacements(ProceduralObjectSettings settings) { - return settings == null ? List.of() : ResolvedProceduralObjects.of(host, settings); + return settings == null ? List.of() : ResolvedProceduralObjects.of(context.world(), settings); } private void placeProceduralFrom(List placements, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome) { @@ -491,17 +493,26 @@ final class ChunkObjectPlacing { } private void placeUpperObjects(Column column) { - Optional upper = host.upperObjects(centerX, centerZ); - if (upper.isEmpty() || (upper.get().biome() == null && upper.get().region() == null)) { + SettingsStack upper = terrain.upperDimension() + .map(dimension -> dimension.settings().at(ObjectSettings.class, centerX, centerZ)) + .orElse(SettingsStack.empty()); + Optional> biome = levelEntry(upper, Level.BIOME); + Optional> region = levelEntry(upper, Level.REGION); + if (biome.isEmpty() && region.isEmpty()) { return; } boolean forcePlace = upperObjectsForced(); - placeUpperScope(upper.get().biome(), upper.get().biomeKey(), "upper-biome-surface", "biome", forcePlace); - placeUpperScope(upper.get().region(), upper.get().regionKey(), "upper-region-surface", "region", forcePlace); + biome.ifPresent(declared -> placeUpperScope(declared, "upper-biome-surface", "biome", forcePlace)); + region.ifPresent(declared -> placeUpperScope(declared, "upper-region-surface", "region", forcePlace)); } - private void placeUpperScope(ObjectSettings settings, String ownerKey, String scope, String kind, boolean forcePlace) { - for (ObjectPlacement placement : surfaceObjects(settings)) { + private static Optional> levelEntry(SettingsStack declared, Level level) { + return declared.entries().stream().filter(entry -> entry.level() == level).findFirst(); + } + + private void placeUpperScope(Entry declared, String scope, String kind, boolean forcePlace) { + String ownerKey = declared.source().toString(); + for (ObjectPlacement placement : surfaceObjects(declared.value())) { if (!rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 91de7d6c2..279de0056 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -18,14 +18,14 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.builtin.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.builtin.floating.IslandFootprint; import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ObjectSize; import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; @@ -89,7 +89,7 @@ public final class FloatingObjectPlacing { public static FloatingObjectPlacing of(PackWorld world, ModuleLog log) { return world.state(FloatingObjectPlacing.class, generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), - generating.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.MANTLE), log)); + generating.seed(IrisSeedPurposes.MANTLE), log)); } /** Places what originates in the chunk of {@code context} into the mantle. */ @@ -100,7 +100,7 @@ public final class FloatingObjectPlacing { int worldHeight = bounds.maxY() - bounds.minY(); RNG chunkRng = new RNG(CacheKey.key(context.chunkX(), context.chunkZ()) + mantleSeed + CHUNK_RANDOM_SALT); FloatingIslandSampleResolver samples = new FloatingIslandSampleResolver(world, worldHeight, - new FloatingIslandBoundarySampler(host::surfaceBiome), log); + new FloatingIslandBoundarySampler(world::surfaceBiome), log); FloatingIslandSample.clearChunkMemo(); Chunk chunk = new Chunk(context, minX, minZ,worldHeight, chunkRng, samples, sampleColumns(samples, minX, minZ)); @@ -388,8 +388,7 @@ public final class FloatingObjectPlacing { /** How far, in blocks along X and Z, the floating objects of the pack {@code settings} describe may write beyond their chunk. */ public static int reach(PackSettings settings, ModuleLog log) { - Reach reach = new Reach(settings.extension(FloatingHost.class).orElseThrow(), - settings.extension(ObjectHost.class).orElseThrow(), log); + Reach reach = new Reach(settings.extension(ObjectHost.class).orElseThrow(), biomeObjectsOf(settings), log); int maxObjectExtent = MIN_REACH_BLOCKS; try { for (Entry declared : settings.declared(FloatingChildSettings.class)) { @@ -413,20 +412,42 @@ public final class FloatingObjectPlacing { return path.startsWith(BIOME_PATH_PREFIX) ? new ResourceId(source.namespace(), path.substring(BIOME_PATH_PREFIX.length())) : source; } + /** The object settings every biome of the pack declares, by the biome's id. */ + private static Map biomeObjectsOf(PackSettings settings) { + Map byBiome = new HashMap<>(); + for (Entry declared : settings.declared(ObjectSettings.class)) { + if (declared.level() == Level.BIOME) { + byBiome.putIfAbsent(biomeIdOf(declared.source()), declared.value()); + } + } + return byBiome; + } + /** The reach of floating children's objects, each object sized once. */ private static final class Reach { - private final FloatingHost host; private final ObjectHost objects; + private final Map biomeObjects; private final ModuleLog log; private final Map> sizes = new HashMap<>(); private final Set warnedLargeObjects = new HashSet<>(); - private Reach(FloatingHost host, ObjectHost objects, ModuleLog log) { - this.host = host; + private Reach(ObjectHost objects, Map biomeObjects, ModuleLog log) { this.objects = objects; + this.biomeObjects = biomeObjects; this.log = log; } + /** + * The surface objects a child inherits: those of the biome it names when that biome declares objects, else its + * parent's. A named biome the pack lacks inherits the parent's while placing; one that declares no objects + * inherits none, so counting the parent's for it only widens the reach. + */ + private List inheritedSurfaceObjects(FloatingChildBiome child, ResourceId parent) { + ResourceId named = child.biome().isBlank() ? parent : ResourceId.ofPackKey(parent.namespace(), child.biome()); + ObjectSettings declared = biomeObjects.getOrDefault(named, biomeObjects.get(parent)); + return FloatingWorld.surfaceObjects(Optional.ofNullable(declared)); + } + int of(FloatingChildBiome child, ResourceId parent) { int reach = 0; reach = Math.max(reach, placementRadius(child.floatingObjects())); @@ -434,8 +455,7 @@ public final class FloatingObjectPlacing { reach = Math.max(reach, placementRadius(child.topObjectOverrides())); reach = Math.max(reach, placementRadius(child.bottomObjectOverrides())); try { - ResourceId target = child.biome().isBlank() ? parent : host.biome(child.biome()).orElse(parent); - List surface = child.inheritObjects() ? FloatingWorld.surfaceObjects(objects, target) : List.of(); + List surface = child.inheritObjects() ? inheritedSurfaceObjects(child, parent) : List.of(); reach = Math.max(reach, placementRadius(ResolvedFloatingChild.topObjects(child, surface))); reach = Math.max(reach, placementRadius(ResolvedFloatingChild.bottomObjects(child))); } catch (Throwable e) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index adc6abf81..9f90c5180 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -54,7 +54,7 @@ public final class ObjectLocating implements ObjectsAt { if (!placesObject(declaration.settings().objects(), resources, object)) { continue; } - (declaration.level() == Level.BIOME ? biomes : regions).add(resources.idOf(declaration.key())); + (declaration.level() == Level.BIOME ? biomes : regions).add(declaration.id()); } return new PlacedBy(biomes, regions); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index e4152abe8..1246b00ed 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -46,17 +46,19 @@ public final class ObjectPlacing { /** A guess draws from the biome's objects before the region's, as placing does. */ private static final Level[] GUESSED_LEVELS = {Level.BIOME, Level.REGION}; + private final PackWorld world; private final ObjectHost host; private final ModuleLog log; - private ObjectPlacing(ObjectHost host, ModuleLog log) { - this.host = host; - this.log = log; + private ObjectPlacing(PackWorld world) { + this.world = world; + this.host = world.extension(ObjectHost.class).orElseThrow(); + this.log = world.log(); } /** The object placing of {@code world}. */ public static ObjectPlacing of(PackWorld world) { - return world.state(ObjectPlacing.class, generating -> new ObjectPlacing(generating.extension(ObjectHost.class).orElseThrow(), generating.log())); + return world.state(ObjectPlacing.class, ObjectPlacing::new); } /** Places what originates in the chunk {@code context} generates. */ @@ -69,7 +71,7 @@ public final class ObjectPlacing { RNG rng = host.chunkRandom(chunkX, chunkZ); int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; - SettingsStack declared = host.columnSettings().at(ObjectSettings.class, centerX, centerZ); + SettingsStack declared = world.running().orElseThrow().settings().at(ObjectSettings.class, centerX, centerZ); Set keys = new HashSet<>(); for (Level level : GUESSED_LEVELS) { declared.level(level).ifPresent(settings -> guessFrom(settings, rng, chunkX, chunkZ, keys)); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 529ff7dec..e2a4525d8 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -24,8 +24,7 @@ import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.ProceduralPlacement; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; @@ -44,13 +43,15 @@ final class ObjectWarmUp { private static final long ROOT_SEED_SALT = 7777L; private static final Level[] WARMED_LEVELS = {Level.BIOME, Level.REGION}; + private final PackWorld world; private final ObjectHost host; private final RNG root; private int warmed; ObjectWarmUp(PackWorld world) { + this.world = world; this.host = world.extension(ObjectHost.class).orElseThrow(); - this.root = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.COMPONENT) + ROOT_SEED_SALT); + this.root = new RNG(world.seed(IrisSeedPurposes.COMPONENT) + ROOT_SEED_SALT); } void warm() { @@ -71,7 +72,7 @@ final class ObjectWarmUp { } private static List> byKey(List> declarations) { - return declarations.stream().sorted(Comparator.comparing(Declaration::key)).toList(); + return declarations.stream().sorted(Comparator.comparing(Declaration::id)).toList(); } private void warmPlacements(List placements) { @@ -83,7 +84,7 @@ final class ObjectWarmUp { } private void warmProcedural(ProceduralObjectSettings settings) { - for (ProceduralPlacement placement : ResolvedProceduralObjects.of(host, settings)) { + for (ProceduralPlacement placement : ResolvedProceduralObjects.of(world, settings)) { placement.variant(root.nextParallelRNG(warmed++)); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java index 0c3b064b4..13554aa69 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -102,7 +102,7 @@ final class PlacementReach { private int ofProcedural(ProceduralObjectSettings settings) { int radius = 0; - for (ProceduralPlacement placement : ResolvedProceduralObjects.of(host, settings)) { + for (ProceduralPlacement placement : ResolvedProceduralObjects.resolve(settings, host)) { for (PlaceableObject variant : placement.variants()) { radius = Math.max(radius, of(new ObjectSize(variant.width(), variant.height(), variant.depth()), placement)); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index e4e1d5beb..0e6cc5776 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -28,13 +28,16 @@ import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.TreeMode; import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.engine.loot.BlockBiomes; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; +import com.volmit.config.Level; import com.volmit.placement.PlacedBlock; import com.volmit.resource.ResourceId; import com.volmit.service.SaplingGrowth; import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.ArrayList; import java.util.HashSet; @@ -55,12 +58,13 @@ public final class TreeGrowing implements SaplingGrowth { @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); + RunningWorld running = world.running().orElseThrow(); BlockPosition at = sapling.at(); - TreeGrowthSettings growth = treeGrowth(host, at); + TreeGrowthSettings growth = treeGrowth(running, at); if (!growth.enabled()) { return Optional.empty(); } - Optional placement = pickPlacement(host, growth, sapling); + Optional placement = pickPlacement(running, growth, sapling); if (placement.isEmpty()) { return Optional.empty(); } @@ -70,7 +74,7 @@ public final class TreeGrowing implements SaplingGrowth { return Optional.empty(); } PlaceableObject object = tree.get(); - GrowthSink sink = new GrowthSink(surroundings, host); + GrowthSink sink = new GrowthSink(surroundings, running.layout().fluidHeight()); BlockPosition center = sapling.center(); host.placeInto(object, center.x(), center.y() + object.height() / 2, center.z(), placement.get(), sink, RNG.r); return Optional.of(new Growth(world.resources().idOf(object.key()), sink.placed())); @@ -94,19 +98,18 @@ public final class TreeGrowing implements SaplingGrowth { return keys.stream().map(world.resources()::idOf).collect(Collectors.toSet()); } - private static TreeGrowthSettings treeGrowth(ObjectHost host, BlockPosition at) { - return host.columnSettings().at(TreeGrowthSettings.class, at.x(), at.z()).dimension().orElseGet(TreeGrowthSettings::new); + private static TreeGrowthSettings treeGrowth(RunningWorld running, BlockPosition at) { + return running.settings().at(TreeGrowthSettings.class, at.x(), at.z()).dimension().orElseGet(TreeGrowthSettings::new); } /** One placement, picked at random, of the tree placements that grow {@code sapling}'s species. */ - private static Optional pickPlacement(ObjectHost host, TreeGrowthSettings growth, Sapling sapling) { + private static Optional pickPlacement(RunningWorld running, TreeGrowthSettings growth, Sapling sapling) { List placements = new ArrayList<>(); BlockPosition at = sapling.at(); - ResourceId biome = host.biomeAt(at.x(), at.y(), at.z()); - host.biomeDeclaration(biome, ObjectSettings.class).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + BlockBiomes.declaredAt(running, ObjectSettings.class, at).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); if (growth.mode() == TreeMode.ALL || placements.isEmpty()) { - ResourceId region = host.regionAt(at.x(), at.z()); - host.regionDeclaration(region, ObjectSettings.class).ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); + running.settings().at(ObjectSettings.class, at.x(), at.z()).level(Level.REGION) + .ifPresent(settings -> placements.addAll(matching(settings, sapling.species()))); } if (placements.isEmpty()) { return Optional.empty(); @@ -153,12 +156,12 @@ public final class TreeGrowing implements SaplingGrowth { /** Places an object into a list of blocks, reading the world around the sapling through the host. */ private static final class GrowthSink implements ObjectSink { private final Surroundings surroundings; - private final ObjectHost host; + private final int fluidHeight; private final List placed = new ArrayList<>(); - private GrowthSink(Surroundings surroundings, ObjectHost host) { + private GrowthSink(Surroundings surroundings, int fluidHeight) { this.surroundings = surroundings; - this.host = host; + this.fluidHeight = fluidHeight; } private List placed() { @@ -182,7 +185,7 @@ public final class TreeGrowing implements SaplingGrowth { @Override public int fluidHeight() { - return host.fluidHeight(); + return fluidHeight; } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index da05ee80d..93c141c92 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CarvingBiomeSettings; @@ -115,7 +114,7 @@ public final class CarveModule implements IrisModule { /** What the carvers need of the world, from the dimension's settings and the first terrain they see (constant for the world). */ private static CarveWorld carveWorld(PackWorld world, TerrainSampler terrain) { int lavaHeight = dimensionSetting(world, CaveLavaHeightSettings.class, CaveLavaHeightSettings::height, CaveLavaHeightSettings.DEFAULT_HEIGHT); - return new CarveWorld(world.resources().noise(), world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE), + return new CarveWorld(world.resources().noise(), world.seed(IrisSeedPurposes.CARVE), terrain.bounds().maxY(), terrain.fluidHeight(), lavaHeight, world.minWorldY()); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 72422ba98..52aaf9598 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -17,8 +17,7 @@ */ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositHeightDistribution; import art.arcane.iris.builtin.deposit.DepositPlacementScope; @@ -77,7 +76,7 @@ final class DepositPlacer { private final Map> biomeIdentities = new ConcurrentHashMap<>(); DepositPlacer(PackWorld world) { - this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.DEPOSIT)); + this.rng = new RNG(world.seed(IrisSeedPurposes.DEPOSIT)); this.resources = world.resources(); this.registry = resources.blocks(); this.log = world.log(); diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index dd5d8e3ea..c3cb11365 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; @@ -82,7 +81,7 @@ final class FloatingIslands { FloatingIslands(PackWorld world, ModuleLog log) { this.world = FloatingWorld.of(world); - this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.TERRAIN) ^ ISLAND_RANDOM_SALT); + this.rng = new RNG(world.seed(IrisSeedPurposes.TERRAIN) ^ ISLAND_RANDOM_SALT); this.biomeLayers = BiomeLayers.of(world); this.log = log; } @@ -450,7 +449,7 @@ final class FloatingIslands { this.explosion = PaletteExplosion.of(settings, context.centreX(), context.centreZ()); TerrainSampler terrain = context.terrain(); this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); - this.boundarySampler = new FloatingIslandBoundarySampler(world.host()::surfaceBiome); + this.boundarySampler = new FloatingIslandBoundarySampler(world::surfaceBiome); } } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 011ed8a08..21d4508e2 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; import art.arcane.iris.builtin.post.PostProcessingWallsSettings; import art.arcane.iris.builtin.terrain.LayerBlocks; @@ -82,7 +81,7 @@ final class SurfaceSmoothing { this.terrain = context.terrain(); this.settings = context.settings(); this.layerBlocks = LayerBlocks.of(context.world()); - this.postRandom = new RNG(context.world().extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.POST)); + this.postRandom = new RNG(context.world().seed(IrisSeedPurposes.POST)); this.originX = context.originX(); this.originZ = context.originZ(); this.planeWidth = blocks.width() + 2; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java index da9098e24..eb247cca9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java @@ -29,8 +29,12 @@ import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; +import com.volmit.world.PackWorld; + import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; /** The procedural objects a region or biome declares, each made placeable once per world, in the order the settings list them. */ @@ -38,12 +42,15 @@ public final class ResolvedProceduralObjects { private ResolvedProceduralObjects() { } - /** The placements {@code settings} declare in the world of {@code host}, resolved the first time a world asks. */ - public static List of(ObjectHost host, ProceduralObjectSettings settings) { - return host.procedural(settings, declared -> resolve(declared, host)); + /** The placements {@code settings} declare in {@code world}, resolved the first time the world asks. */ + public static List of(PackWorld world, ProceduralObjectSettings settings) { + ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); + return world.state(ResolvedByDeclaration.class, ignored -> new ResolvedByDeclaration()).placements + .computeIfAbsent(settings, declared -> resolve(declared, host)); } - static List resolve(ProceduralObjectSettings settings, ObjectHost host) { + /** The placements {@code settings} declare, resolved anew, for work outside any world such as working out the pack's reach. */ + public static List resolve(ProceduralObjectSettings settings, ObjectHost host) { List all = new ArrayList<>(); for (Tree tree : settings.trees()) { all.add(new ResolvedTree(tree, host)); @@ -62,4 +69,9 @@ public final class ResolvedProceduralObjects { all.add(resolve.apply(entry, host)); } } + + /** A world's resolved placements, by the settings that declare them. */ + private static final class ResolvedByDeclaration { + private final Map> placements = new ConcurrentHashMap<>(); + } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index 7b2e26468..81cf757fb 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.object.terrain.carving; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import com.volmit.ModuleLog; @@ -60,7 +59,7 @@ public final class CarvingResolver { this.resources = world.resources(); this.log = world.log(); this.minHeight = world.minWorldY(); - this.childSeed = world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.CARVE) ^ CHILD_SEED_SALT; + this.childSeed = world.seed(IrisSeedPurposes.CARVE) ^ CHILD_SEED_SALT; this.entries = declared.stream().filter(Objects::nonNull).map(ResolvedCarvingEntry::new).toList(); this.index = indexById(entries); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 8c864d072..0a010c637 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -342,7 +342,7 @@ public final class FloatingIslandSample { } double altNoise = altitudeCng.sample(wx, wz); double altClamped = Math.max(0, Math.min(1, altNoise)); - int worldMin = world.minHeight(); + int worldMin = world.minWorldY(); int minAlt = Math.max(0, entry.settings().minHeightAboveSurface() - worldMin); int maxAlt = Math.max(minAlt, entry.settings().maxHeightAboveSurface() - worldMin); int baseY = minAlt + (int) Math.round(altClamped * (maxAlt - minAlt)); diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index 11ccf245c..00bf35ed2 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.object.terrain.floating; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.carve.CarvingEntry; import art.arcane.iris.builtin.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveProfile; @@ -31,8 +30,11 @@ import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import com.volmit.noise.NoiseFactory; +import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import com.volmit.world.PackBiome; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.List; import java.util.Map; @@ -40,29 +42,32 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** - * What the floating islands of one world are made from: the world's hosts, noise and seeds, the floating children each - * biome declares, and the {@link ResolvedFloatingChild} of every child met, one per decoded entry. One per world ({@link #of}). + * What the floating islands of one world are made from: the world's hosts, layout, noise and seeds, the floating children + * each biome declares, and the {@link ResolvedFloatingChild} of every child met, one per decoded entry. One per world + * ({@link #of}). */ public final class FloatingWorld { private static final long BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; private final FloatingHost host; private final ObjectHost objects; - private final NoiseFactory noise; + private final PackResources resources; + private final RunningWorld running; private final long baseSeed; private final long carveSeed; - private final int minHeight; + private final int minWorldY; private final List dimensionCarving; private final Map resolved = new ConcurrentHashMap<>(); - FloatingWorld(FloatingHost host, ObjectHost objects, NoiseFactory noise, long terrainSeed, long carveSeed, int minHeight, - List dimensionCarving) { + FloatingWorld(FloatingHost host, ObjectHost objects, PackResources resources, RunningWorld running, long terrainSeed, + long carveSeed, int minWorldY, List dimensionCarving) { this.host = host; this.objects = objects; - this.noise = noise; + this.resources = resources; + this.running = running; this.baseSeed = terrainSeed ^ BASE_SEED_SALT; this.carveSeed = carveSeed; - this.minHeight = minHeight; + this.minWorldY = minWorldY; this.dimensionCarving = List.copyOf(dimensionCarving); } @@ -72,10 +77,9 @@ public final class FloatingWorld { } private static FloatingWorld create(PackWorld world) { - IrisSeeds seeds = world.extension(IrisSeeds.class).orElseThrow(); return new FloatingWorld(world.extension(FloatingHost.class).orElseThrow(), world.extension(ObjectHost.class).orElseThrow(), - world.resources().noise(), seeds.seed(IrisSeed.TERRAIN), seeds.seed(IrisSeed.CARVE), world.minWorldY(), - dimensionCarvingOf(world)); + world.resources(), world.running().orElseThrow(), world.seed(IrisSeedPurposes.TERRAIN), world.seed(IrisSeedPurposes.CARVE), + world.minWorldY(), dimensionCarvingOf(world)); } private static List dimensionCarvingOf(PackWorld world) { @@ -93,7 +97,7 @@ public final class FloatingWorld { } public NoiseFactory noise() { - return noise; + return resources.noise(); } /** The seed every island's noise and column random derive from. */ @@ -105,19 +109,29 @@ public final class FloatingWorld { return carveSeed; } - /** The platform's Y of the dimension's bottom. */ - public int minHeight() { - return minHeight; + /** The Y in the world of the dimension's bottom block. */ + public int minWorldY() { + return minWorldY; + } + + /** The biome of the column's surface, the biome an island grows from; any column of the world. */ + public ResourceId surfaceBiome(int worldX, int worldZ) { + return running.layout().surfaceBiome(worldX, worldZ); + } + + /** The biome the pack names {@code key}; empty when the pack has none. */ + public Optional biome(String key) { + return resources.find(PackResources.BIOMES, resources.idOf(key)).map(PackBiome::id); } /** The floating children {@code biome} declares, in the order it lists them; none when it declares none. */ public List declaredBy(ResourceId biome) { - return objects.biomeDeclaration(biome, FloatingChildSettings.class).map(FloatingChildSettings::children).orElse(List.of()); + return running.settings().declaredBy(biome, FloatingChildSettings.class).map(FloatingChildSettings::children).orElse(List.of()); } /** Whether {@code biome} samples every floating child on its own and unions their islands instead of picking one per column. */ public boolean merges(ResourceId biome) { - return objects.biomeDeclaration(biome, MergeFloatingChildrenSettings.class).map(MergeFloatingChildrenSettings::merge).orElse(false); + return running.settings().declaredBy(biome, MergeFloatingChildrenSettings.class).map(MergeFloatingChildrenSettings::merge).orElse(false); } public ResolvedFloatingChild resolve(FloatingChildBiome settings) { @@ -129,8 +143,13 @@ public final class FloatingWorld { } /** The surface object placements {@code biome} declares. */ - public static List surfaceObjects(ObjectHost objects, ResourceId biome) { - return objects.biomeDeclaration(biome, ObjectSettings.class).map(ObjectSettings::objects).orElse(List.of()).stream() + public List surfaceObjects(ResourceId biome) { + return surfaceObjects(running.settings().declaredBy(biome, ObjectSettings.class)); + } + + /** The surface object placements of the declared object settings; none when nothing is declared. */ + public static List surfaceObjects(Optional declared) { + return declared.map(ObjectSettings::objects).orElse(List.of()).stream() .filter(placement -> placement.carvingSupport().supportsSurface()) .toList(); } @@ -148,6 +167,6 @@ public final class FloatingWorld { /** The cave profile {@code biome} declares; null when it declares none. */ CaveProfile caveProfile(ResourceId biome) { - return objects.biomeDeclaration(biome, CaveProfile.class).orElse(null); + return running.settings().declaredBy(biome, CaveProfile.class).orElse(null); } } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index 15dc2147e..f708edb51 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -141,14 +141,14 @@ public final class ResolvedFloatingChild { String carving = settings.carving(); Optional entry = world.dimensionCarving(carving); if (entry.isEmpty()) { - return world.host().biome(carving); + return world.biome(carving); } String biomeKey = entry.get().biome().trim(); - return biomeKey.isEmpty() ? Optional.empty() : world.host().biome(biomeKey); + return biomeKey.isEmpty() ? Optional.empty() : world.biome(biomeKey); } public KList resolveTopObjects(ResourceId target) { - List surface = settings.inheritObjects() && target != null ? FloatingWorld.surfaceObjects(world.objects(), target) : List.of(); + List surface = settings.inheritObjects() && target != null ? world.surfaceObjects(target) : List.of(); return topObjects(settings, surface); } @@ -193,6 +193,6 @@ public final class ResolvedFloatingChild { if (settings.biome().isBlank()) { return parent; } - return namedBiome.aquire(() -> world.host().biome(settings.biome())).orElse(parent); + return namedBiome.aquire(() -> world.biome(settings.biome())).orElse(parent); } } diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java index cb46dd0fc..1c35bd195 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -18,21 +18,22 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.LiveWorld; -import art.arcane.iris.builtin.LiveWorld.Level; -import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EffectCommands; import art.arcane.iris.builtin.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.SpawnCommand; +import art.arcane.iris.engine.loot.BlockBiomes; import art.arcane.iris.engine.loot.PlatformKeys; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; +import com.volmit.config.Level; import com.volmit.entity.EntitySpec; import com.volmit.resource.ResourceId; import com.volmit.service.AmbientEffects; import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.RunningWorld.Sky; import java.util.ArrayList; import java.util.List; @@ -45,18 +46,18 @@ import java.util.Optional; public final class AmbientEffecting implements AmbientEffects { @Override public List due(PackWorld world, BlockPosition at) { - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); + RunningWorld running = world.running().orElseThrow(); EffectTimers timers = world.state(EffectTimers.class, ignored -> new EffectTimers()); - Optional sky = live.sky(); + Optional sky = running.sky(); List due = new ArrayList<>(); - addDue(due, effectsOf(live, Level.REGION, at), timers, sky, world.log()); - addDue(due, effectsOf(live, Level.BIOME, at), timers, sky, world.log()); + addDue(due, effectsOf(running.settings().at(EffectSettings.class, at.x(), at.z()).level(Level.REGION)), timers, sky, world.log()); + addDue(due, effectsOf(BlockBiomes.declaredAt(running, EffectSettings.class, at)), timers, sky, world.log()); return due; } - private static List effectsOf(LiveWorld live, Level level, BlockPosition at) { - return live.settings(EffectSettings.class, level, at.x(), at.y(), at.z()).map(EffectSettings::effects).orElse(List.of()); + private static List effectsOf(Optional declared) { + return declared.map(EffectSettings::effects).orElse(List.of()); } private static void addDue(List due, List effects, EffectTimers timers, Optional sky, ModuleLog log) { diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index af6d5a3f7..04c77d077 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EntityDefinition; @@ -35,6 +34,7 @@ import com.volmit.item.ItemDrop; import com.volmit.resource.ContentKey; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import com.volmit.world.RunningWorld.Sky; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index c32f591c6..0d178d35a 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -18,13 +18,11 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.IrisSeed; -import art.arcane.iris.builtin.IrisSeeds; -import art.arcane.iris.builtin.LiveWorld; -import art.arcane.iris.builtin.LiveWorld.Level; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.EntitySpawn; +import art.arcane.iris.builtin.spawn.SpawnCooldowns; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.SpawnSurface; import art.arcane.iris.builtin.spawn.Spawner; @@ -35,13 +33,17 @@ import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.scheduling.ChronoLatch; +import com.volmit.config.Level; import com.volmit.config.Range; +import com.volmit.config.SettingsStack; import com.volmit.entity.EntitySpec; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.service.EntitySpawns; import com.volmit.geometry.BlockPosition; +import com.volmit.world.BiomeKind; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.ArrayList; import java.util.List; @@ -62,7 +64,6 @@ public final class EntitySpawning implements EntitySpawns { private static final String CAVE_CEILING_MARKER = "cave_ceiling"; private static final int AIR_ABOVE_MARKER = 1; private static final long COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS = 60_000L; - private static final int LAYOUT_QUESTION_HEIGHT = 0; @Override public Optional plan(PackWorld world, Site site) { @@ -81,7 +82,7 @@ public final class EntitySpawning implements EntitySpawns { String spawnerKey = plan.spawner().path(); Spawner spawner = SpawnResources.spawner(world.resources(), spawnerKey); if (spawner != null) { - SpawnerGate.spawned(spawnerKey, spawner, world.extension(LiveWorld.class).orElseThrow(), plan.chunkX(), plan.chunkZ()); + SpawnerGate.of(world).spawned(spawnerKey, spawner, plan.chunkX(), plan.chunkZ()); } } @@ -122,25 +123,27 @@ public final class EntitySpawning implements EntitySpawns { return; } PackResources resources = world.resources(); - world.extension(LiveWorld.class).orElseThrow().spawnCooldowns().forgetExpired(key -> { + world.extension(SpawnCooldowns.class).orElseThrow().forgetExpired(key -> { Spawner spawner = SpawnResources.spawner(resources, key); return spawner == null ? -1L : spawner.maximumRate().interval(); }); } private Optional planChunk(PackWorld world, Chunk chunk) { - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); - Predicate canSpawn = keyed -> SpawnerGate.canSpawn(keyed.key(), keyed.spawner(), live, chunk.chunkX(), chunk.chunkZ()); + RunningWorld running = world.running().orElseThrow(); + SpawnerGate gate = SpawnerGate.of(world); + Predicate canSpawn = keyed -> gate.canSpawn(keyed.key(), keyed.spawner(), chunk.chunkX(), chunk.chunkZ()); int blockX = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkX()); int blockZ = PowerOfTwoCoordinates.chunkToBlock(chunk.chunkZ()); - LiveWorld.BiomeKind centreKind = live.surfaceKind(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); + BiomeKind centreKind = running.layout().surfaceKind(blockX + BLOCKS_TO_CHUNK_CENTRE, blockZ + BLOCKS_TO_CHUNK_CENTRE); + SettingsStack column = running.settings().at(SpawnerSettings.class, blockX, blockZ); List candidates = Stream.concat( - shuffled(world, live, Level.DIMENSION, blockX, blockZ).stream() + shuffled(world, column.dimension()).stream() .filter(canSpawn).filter(keyed -> SpawnerGate.suits(keyed.spawner(), centreKind)), Stream.concat( - shuffled(world, live, Level.REGION, blockX, blockZ).stream().filter(canSpawn), - shuffled(world, live, Level.SURFACE_BIOME, blockX, blockZ).stream().filter(canSpawn))) + shuffled(world, column.level(Level.REGION)).stream().filter(canSpawn), + shuffled(world, column.level(Level.BIOME)).stream().filter(canSpawn))) .filter(keyed -> chunk.livingEntities() < keyed.spawner().maxEntitiesPerChunk()) .toList(); @@ -149,17 +152,17 @@ public final class EntitySpawning implements EntitySpawns { if (chosen == null) { return Optional.empty(); } - return planChunkSpawn(world, live, chunk, chosen); + return planChunkSpawn(world, running, chunk, chosen); } - private Optional planChunkSpawn(PackWorld world, LiveWorld live, Chunk chunk, Candidate chosen) { + private Optional planChunkSpawn(PackWorld world, RunningWorld running, Chunk chunk, Candidate chosen) { EntitySpawn spawn = chosen.spawn(); int count = LootResolver.inclusive(RNG.r, spawn.minSpawns(), spawn.maxSpawns()); List attempts = new ArrayList<>(); for (int i = 0; i < count; i++) { int x = (chunk.chunkX() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); int z = (chunk.chunkZ() * CHUNK_SIZE) + RNG.r.i(CHUNK_SIZE); - BlockPosition at = spawnPosition(live, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); + BlockPosition at = spawnPosition(running, chosen.spawner(), chunk.chunkX(), chunk.chunkZ(), x, z); if (at != null) { addAttempt(attempts, world, chosen, at, true); } @@ -168,18 +171,18 @@ public final class EntitySpawning implements EntitySpawns { } /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ - private static BlockPosition spawnPosition(LiveWorld live, Spawner spawner, int chunkX, int chunkZ, int x, int z) { - int height = live.highestBlock(x, z, true); - int heightWithFluid = live.highestBlock(x, z, false); + private static BlockPosition spawnPosition(RunningWorld running, Spawner spawner, int chunkX, int chunkZ, int x, int z) { + int height = running.highestBlock(x, z, true); + int heightWithFluid = running.highestBlock(x, z, false); return switch (spawner.group()) { case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); - case CAVE -> caveSpawnPosition(live, chunkX, chunkZ); + case CAVE -> caveSpawnPosition(running, chunkX, chunkZ); case UNDERWATER, BEACH -> new BlockPosition(x, RNG.r.i(height + 1, heightWithFluid), z); }; } - static BlockPosition caveSpawnPosition(LiveWorld live, int chunkX, int chunkZ) { - KList floors = new KList<>(live.caveFloors(chunkX, chunkZ)); + static BlockPosition caveSpawnPosition(RunningWorld running, int chunkX, int chunkZ) { + KList floors = new KList<>(running.caveFloors(chunkX, chunkZ)); BlockPosition floor = floors.getRandom(RNG.r); return floor == null ? null : new BlockPosition(floor.x(), floor.y() + AIR_ABOVE_MARKER, floor.z()); } @@ -201,8 +204,7 @@ public final class EntitySpawning implements EntitySpawns { BlockPosition position = marker.position(); int chunkX = PowerOfTwoCoordinates.blockToChunkFloor(position.x()); int chunkZ = PowerOfTwoCoordinates.blockToChunkFloor(position.z()); - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); - if (!SpawnerGate.canSpawn(spawnerKey, spawner, live, chunkX, chunkZ)) { + if (!SpawnerGate.of(world).canSpawn(spawnerKey, spawner, chunkX, chunkZ)) { return Optional.empty(); } @@ -236,9 +238,9 @@ public final class EntitySpawning implements EntitySpawns { } private static EntityResolution resolution(PackWorld world) { - LiveWorld live = world.extension(LiveWorld.class).orElseThrow(); - LootItems items = new LootItems(world.resources().items(), live.studio(), world.log()); - return new EntityResolution(world.resources(), items, live.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers()), + RunningWorld running = world.running().orElseThrow(); + LootItems items = new LootItems(world.resources().items(), running.debug(), world.log()); + return new EntityResolution(world.resources(), items, running.sky(), world.state(EffectTimers.class, ignored -> new EffectTimers()), world.log()); } @@ -251,9 +253,8 @@ public final class EntitySpawning implements EntitySpawns { } /** The spawners the dimension, region or surface biome at the column lists, in a random order. */ - private static List shuffled(PackWorld world, LiveWorld live, Level level, int x, int z) { - List keys = live.settings(SpawnerSettings.class, level, x, LAYOUT_QUESTION_HEIGHT, z) - .map(SpawnerSettings::spawners).orElse(List.of()); + private static List shuffled(PackWorld world, Optional declared) { + List keys = declared.map(SpawnerSettings::spawners).orElse(List.of()); return new KList<>(SpawnResources.spawners(world.resources(), keys)).shuffleCopy(RNG.r); } @@ -274,7 +275,7 @@ public final class EntitySpawning implements EntitySpawns { private final RNG rng; private EntityRandom(PackWorld world) { - this.rng = new RNG(world.extension(IrisSeeds.class).orElseThrow().seed(IrisSeed.ENTITY)); + this.rng = new RNG(world.seed(IrisSeedPurposes.ENTITY)); } private RNG rng() { diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java index a7c565c79..8688584d7 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnConditions.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.LiveWorld.Sky; import art.arcane.iris.builtin.spawn.SpawnTimeBlock; import art.arcane.iris.builtin.spawn.SpawnWeather; +import com.volmit.world.RunningWorld.Sky; /** The time of day and the weather a command or spawner of the pack asks for, checked against a world's sky. */ final class SpawnConditions { diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java index 1327251af..3cdfb770f 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java @@ -18,21 +18,26 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.LiveWorld; -import art.arcane.iris.builtin.LiveWorld.BiomeKind; -import art.arcane.iris.builtin.LiveWorld.Sky; -import art.arcane.iris.builtin.spawn.SpawnRate; import art.arcane.iris.builtin.spawn.SpawnCooldowns; +import art.arcane.iris.builtin.spawn.SpawnRate; import art.arcane.iris.builtin.spawn.Spawner; +import com.volmit.world.BiomeKind; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld.Sky; import java.util.Optional; /** * Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not * more often than its rates allow. The rates count in the world's data, by the key the pack names the spawner by. + * + * @param sky the world's time and weather when the gate was made; empty while the platform has not loaded the world + * @param cooldowns when the world's spawners last fired */ -final class SpawnerGate { - private SpawnerGate() { +record SpawnerGate(Optional sky, SpawnCooldowns cooldowns) { + /** The gate of the running world, with its time and weather now. */ + static SpawnerGate of(PackWorld world) { + return new SpawnerGate(world.running().orElseThrow().sky(), world.extension(SpawnCooldowns.class).orElseThrow()); } /** Whether a spawner of this group fires in a biome of {@code kind}. */ @@ -60,40 +65,39 @@ final class SpawnerGate { } /** Whether the spawner may fire in the chunk now. */ - static boolean canSpawn(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) { - if (!canSpawn(key, spawner, live)) { + boolean canSpawn(String key, Spawner spawner, int chunkX, int chunkZ) { + if (!canSpawn(key, spawner)) { return false; } SpawnRate rate = spawner.maximumRatePerChunk(); - return rate.isInfinite() || live.spawnCooldowns().canSpawnInChunk(chunkX, chunkZ, key, rate.interval()); + return rate.isInfinite() || cooldowns.canSpawnInChunk(chunkX, chunkZ, key, rate.interval()); } /** Counts a spawn of the spawner in the chunk against its rates. */ - static void spawned(String key, Spawner spawner, LiveWorld live, int chunkX, int chunkZ) { - spawned(key, spawner, live); + void spawned(String key, Spawner spawner, int chunkX, int chunkZ) { + spawned(key, spawner); if (spawner.maximumRatePerChunk().isInfinite()) { return; } - live.spawnCooldowns().spawnedInChunk(chunkX, chunkZ, key); + cooldowns.spawnedInChunk(chunkX, chunkZ, key); } - private static boolean canSpawn(String key, Spawner spawner, LiveWorld live) { - Optional sky = live.sky(); + private boolean canSpawn(String key, Spawner spawner) { if (sky.isEmpty() || !suits(spawner, sky.get())) { return false; } SpawnRate rate = spawner.maximumRate(); - return rate.isInfinite() || live.spawnCooldowns().canSpawn(key, rate.interval()); + return rate.isInfinite() || cooldowns.canSpawn(key, rate.interval()); } - private static void spawned(String key, Spawner spawner, LiveWorld live) { + private void spawned(String key, Spawner spawner) { if (spawner.maximumRate().isInfinite()) { return; } - live.spawnCooldowns().spawned(key); + cooldowns.spawned(key); } } From e4cb8146a15686e510615bd4c75fa47fd5fc4186 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 10:24:25 +0200 Subject: [PATCH 105/139] Batch 6 part 4b: placement facades in API vocabulary Finding 40. PlacementTerrain answers minWorldY() instead of minHeight() and the object at a block as Optional instead of a nullable key; ObjectShape names its object by Optional; PlacementSettings' collisions are sets of object ids. The vacuum reads its fill rock from the module's own TerrainPalettes and validate reads BedrockSettings from the world's dimension, so PlacementTerrain loses rockAt and hasBedrock and the host no longer reaches either type. --- .../iris/builtin/placement/ObjectShape.java | 6 +++-- .../builtin/placement/PlacementSettings.java | 8 ++++-- .../builtin/placement/PlacementTerrain.java | 18 +++++-------- .../engine/object/placement/VacuumModule.java | 7 +++-- .../object/placement/ValidateModule.java | 26 ++++++++++++------- 5 files changed, 39 insertions(+), 26 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java index 9cae1d581..74f0bdb59 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java +++ b/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java @@ -19,8 +19,10 @@ package art.arcane.iris.builtin.placement; import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.resource.ResourceId; import java.util.List; +import java.util.Optional; /** The object being placed: its declared size, the block its offsets count from, and where it must stand on solid ground. */ public interface ObjectShape { @@ -37,8 +39,8 @@ public interface ObjectShape { int centerZ(); - /** The pack's key of the object, or null for an object without one. */ - String key(); + /** The pack object this is; empty for an object the pack does not name, such as a procedural variant. */ + Optional id(); /** The columns of the object's lowest solid layer, as offsets from its anchor before any transform; empty for the origin only. */ List surfaceSupportOffsets(); diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java index a8907bd54..198135b47 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java +++ b/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java @@ -27,9 +27,11 @@ import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; +import com.volmit.resource.ResourceId; import java.util.List; import java.util.Optional; +import java.util.Set; /** The settings of one object placement, as the placement stages read them. */ public interface PlacementSettings { @@ -86,7 +88,9 @@ public interface PlacementSettings { /** The snow filter's depth, 0 for none. */ double snow(); - List allowedCollisions(); + /** The pack objects the placement may overlap even when {@link #forbiddenCollisions()} names them. */ + Set allowedCollisions(); - List forbiddenCollisions(); + /** The pack objects the placement may not overlap. */ + Set forbiddenCollisions(); } diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java index 5334cf82c..c766a7104 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java +++ b/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java @@ -18,7 +18,9 @@ package art.arcane.iris.builtin.placement; -import com.volmit.block.BlockState; +import com.volmit.resource.ResourceId; + +import java.util.Optional; /** * What a placement asks of the terrain and the world around it: heights, carving and water at a column, and the @@ -53,20 +55,14 @@ public interface PlacementTerrain { /** The terrain height at a position between columns, as the dimension's height field gives it. */ double heightAt(double x, double z); - /** Whether the dimension has a bedrock floor. */ - boolean hasBedrock(); - - /** The real Y of the dimension's bottom. */ - int minHeight(); + /** The platform's Y of the dimension's bottom block. */ + int minWorldY(); /** The dimension's height in blocks. */ int worldHeight(); - /** The rock the dimension has at the column; air when it has none to say. */ - BlockState rockAt(int x, int z); - StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ); - /** The pack's key of the object placed at the block, or null when none was. */ - String objectKeyAt(int x, int y, int z); + /** The pack object placed at the block; empty when none was. */ + Optional objectAt(int x, int y, int z); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 8b0006989..3969448f0 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -26,6 +26,7 @@ import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.PlaneNoise; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.builtin.terrain.TerrainPalettes; import art.arcane.iris.builtin.vacuum.VacuumSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -80,6 +81,7 @@ public final class VacuumModule implements IrisModule { private final PreparedPlacement prepared; private final PlacementTerrain terrain; private final PlacementWorld world; + private final PlacementStageContext context; private final int radius; private final int step; private final double falloff; @@ -96,6 +98,7 @@ public final class VacuumModule implements IrisModule { this.prepared = prepared; this.terrain = prepared.terrain(); this.world = new PlacementWorld(context.access(), prepared.traits()); + this.context = context; VacuumSettings settings = prepared.settings().vacuum().orElse(null); this.radius = IrisObjectVacuum.resolveRadius(vacuum, settings); this.step = vacuum.columnStepBlocks(); @@ -158,8 +161,8 @@ public final class VacuumModule implements IrisModule { } private void raise(int x, int z, int fromY, int toY) { - BlockState fill = terrain.rockAt(x, z); - if (world.has(fill, BlockTrait.AIR)) { + BlockState fill = TerrainPalettes.of(context.world()).rockAt(x, z); + if (fill == null || world.has(fill, BlockTrait.AIR)) { fill = STONE; } for (int y = fromY + 1; y <= toY; y++) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index a55407cea..a8e8d03cd 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -28,6 +28,7 @@ import art.arcane.iris.builtin.placement.PlacementSettings; import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.StructureVolumes; import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.terrain.BedrockSettings; import art.arcane.iris.builtin.validate.ObjectLimit; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -35,8 +36,10 @@ import com.volmit.ModuleLog; import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.object.ObjectBlock; +import com.volmit.resource.ResourceId; import com.volmit.stage.PlacementStageContext; import com.volmit.geometry.BlockPosition; +import com.volmit.world.PackWorld; import java.util.Optional; import java.util.Set; @@ -84,7 +87,7 @@ public final class ValidateModule implements IrisModule { } int y = context.output(IrisStages.Anchor.HEIGHT).y(); boolean sampled = placement.requestedY() < 0; - if (sampled && settings.carvingSupport().supportsSurface() && isOnBedrock(prepared, y)) { + if (sampled && settings.carvingSupport().supportsSurface() && isOnBedrock(context, prepared, y)) { warnImplausibleBedrockPlacement(placement, settings, y, context.log()); context.reject("bedrock-anchor"); return; @@ -97,9 +100,12 @@ public final class ValidateModule implements IrisModule { } } - private static boolean isOnBedrock(PreparedPlacement prepared, int y) { - PlacementTerrain terrain = prepared.terrain(); - return y <= BEDROCK_ROW && terrain.hasWorld() && terrain.hasBedrock(); + private static boolean isOnBedrock(PlacementStageContext context, PreparedPlacement prepared, int y) { + return y <= BEDROCK_ROW && prepared.terrain().hasWorld() && hasBedrock(context.world()); + } + + private static boolean hasBedrock(PackWorld world) { + return world.settings().declared(BedrockSettings.class).dimension().map(BedrockSettings::bedrock).orElse(true); } private static boolean lacksSurfaceSupport(ObjectPlacement placement, PreparedPlacement prepared) { @@ -158,7 +164,7 @@ public final class ValidateModule implements IrisModule { return false; } boolean painted = WorldVolume.isPainted(placement, prepared); - int worldY = y + terrain.minHeight(); + int worldY = y + terrain.minWorldY(); int envelopeMinY = painted ? Integer.MIN_VALUE : worldY - margin; int envelopeMaxY = painted ? Integer.MAX_VALUE : worldY + margin; if (!volumes.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { @@ -175,7 +181,7 @@ public final class ValidateModule implements IrisModule { ? offset.y() + Math.floorDiv(placement.object().height(), 2) + terrain.highest(blockX, blockZ, prepared.settings().underwater()) : y + offset.y(); - int worldBlockY = blockY + terrain.minHeight(); + int worldBlockY = blockY + terrain.minWorldY(); if (volumes.containsWithin(blockX, worldBlockY, blockZ, prepared.warpMargin())) { return true; } @@ -212,11 +218,13 @@ public final class ValidateModule implements IrisModule { } private static boolean collidesWithForbiddenObject(PlacementTerrain terrain, PlacementSettings settings, WorldVolume volume) { + Set forbidden = settings.forbiddenCollisions(); + Set allowed = settings.allowedCollisions(); for (int x = volume.minX(); x <= volume.maxX(); x++) { for (int y = volume.minY(); y <= volume.maxY(); y++) { for (int z = volume.minZ(); z <= volume.maxZ(); z++) { - String key = terrain.objectKeyAt(x, y, z); - if (key != null && settings.forbiddenCollisions().contains(key) && !settings.allowedCollisions().contains(key)) { + Optional placed = terrain.objectAt(x, y, z); + if (placed.isPresent() && forbidden.contains(placed.get()) && !allowed.contains(placed.get())) { return true; } } @@ -226,7 +234,7 @@ public final class ValidateModule implements IrisModule { } private static void warnImplausibleBedrockPlacement(ObjectPlacement placement, PlacementSettings settings, int y, ModuleLog log) { - String key = placement.object().key(); + String key = placement.object().id().map(ResourceId::toString).orElse(null); String fingerprint = (key == null ? "" : key) + "|" + settings.mode(); long now = System.currentTimeMillis(); Long last = IMPLAUSIBLE_BEDROCK_WARNS.get(fingerprint); From bf29f4b486573e516a3ed92eadb4508d2e43dce1 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 24 Oct 2026 10:48:33 +0200 Subject: [PATCH 106/139] Batch 6 part 4c: the jar's own types leave the exposed package 41 settings and helper types that only the built-ins jar reads move from art.arcane.iris.builtin to art.arcane.iris.modules, which Iris does not expose, and builtin-modules.txt packs them into the jar: the terrain layers and palettes (BiomeLayers, LayerBlocks, TerrainPalettes, ResolvedLayer and the terrain settings), the post, decorate, deposit, carve, floating, loot, spawn and vanilla-feature settings. The exposed package goes from 16,168 to 13,711 lines. Types packs write as snippets stay exposed, with what they reference: a snippet type the host does not share must live under its module's id, which would move existing packs' snippet folders. --- README.md | 27 ++++++++++--------- builtin-modules.txt | 3 +++ .../art/arcane/iris/builtin/package-info.java | 13 +++++---- .../iris/engine/actuator/DecorantModule.java | 2 +- .../iris/engine/actuator/OreWarmUp.java | 2 +- .../iris/engine/actuator/ResolvedOre.java | 2 +- .../iris/engine/actuator/ResolvedOres.java | 4 +-- .../iris/engine/actuator/TerrainModule.java | 26 +++++++++--------- .../iris/engine/actuator/TerrainOres.java | 2 +- .../iris/engine/actuator/TerrainShaper.java | 18 ++++++------- .../vanillafeatures/ImportedFeatures.java | 2 +- .../VanillaFeaturesModule.java | 2 +- .../iris/engine/loot/BlockDropping.java | 2 +- .../arcane/iris/engine/loot/LootModule.java | 2 +- .../components/FloatingObjectPlacing.java | 2 +- .../engine/modifier/BuiltInCaveDressing.java | 8 +++--- .../iris/engine/modifier/CarveModule.java | 12 ++++----- .../iris/engine/modifier/CaveBiomeBands.java | 2 +- .../iris/engine/modifier/DepositModule.java | 8 +++--- .../iris/engine/modifier/DepositPlacer.java | 6 ++--- .../iris/engine/modifier/FloatingIslands.java | 10 +++---- .../iris/engine/modifier/FloatingModule.java | 4 +-- .../engine/modifier/PerfectionModule.java | 2 +- .../iris/engine/modifier/PostModule.java | 6 ++--- .../engine/modifier/SurfaceSmoothing.java | 10 +++---- .../engine/object/placement/VacuumModule.java | 2 +- .../terrain/carving/CarvingResolver.java | 2 +- .../terrain/floating/FloatingWorld.java | 6 ++--- .../iris/engine/spawn/AmbientEffecting.java | 2 +- .../iris/engine/spawn/EntitySpawning.java | 2 +- .../arcane/iris/engine/spawn/SpawnModule.java | 4 +-- .../carve/CarvingBiomeSettings.java | 2 +- .../carve/CarvingEnabledSettings.java | 2 +- .../carve/CarvingSettings.java | 3 ++- .../carve/CaveDepthSettings.java | 2 +- .../carve/UpperDimensionCarvingSettings.java | 2 +- .../decorant/DecorateSettings.java | 2 +- .../deposit/DepositSettings.java | 3 ++- .../deposit/DepositVariantSettings.java | 3 ++- .../deposit/OreFrequencySettings.java | 2 +- .../deposit/OreSizeSettings.java | 2 +- .../floating/FloatingChildSettings.java | 5 ++-- .../MergeFloatingChildrenSettings.java | 2 +- .../loot/BlockDropSettings.java | 3 ++- .../post/PostProcessingSettings.java | 2 +- .../post/PostProcessingSlabsSettings.java | 2 +- .../post/PostProcessingWallsSettings.java | 2 +- .../spawn/EffectSettings.java | 3 ++- .../spawn/SpawnerSettings.java | 3 ++- .../terrain/BiomeLayers.java | 4 ++- .../terrain/CaveCeilingLayersSettings.java | 3 ++- .../terrain/ColumnSlope.java | 2 +- .../ExplodeBiomePaletteSizeSettings.java | 2 +- .../terrain/ExplodeBiomePalettesSettings.java | 2 +- .../terrain/FluidPaletteSettings.java | 2 +- .../terrain/HideOresSettings.java | 2 +- .../terrain/LayerBlocks.java | 3 ++- .../terrain/LayerNoise.java | 2 +- .../terrain/LayeredBiome.java | 4 ++- .../terrain/LockLayersMaxSettings.java | 2 +- .../terrain/LockLayersSettings.java | 2 +- .../terrain/OreGenerator.java | 2 +- .../terrain/OreSettings.java | 2 +- .../terrain/PaletteBlocks.java | 2 +- .../terrain/PaletteExplosion.java | 2 +- .../terrain/ResolvedLayer.java | 3 ++- .../terrain/RockPaletteSettings.java | 2 +- .../terrain/SeaLayersSettings.java | 3 ++- .../terrain/SlabSettings.java | 3 ++- .../terrain/TerrainPalettes.java | 2 +- .../terrain/WallSettings.java | 3 ++- .../ImportedFeaturesSettings.java | 2 +- 72 files changed, 159 insertions(+), 137 deletions(-) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/CarvingBiomeSettings.java (98%) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/CarvingEnabledSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/CarvingSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/CaveDepthSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/UpperDimensionCarvingSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/decorant/DecorateSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositSettings.java (94%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositVariantSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/OreFrequencySettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/OreSizeSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/FloatingChildSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/MergeFloatingChildrenSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/loot/BlockDropSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/post/PostProcessingSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/post/PostProcessingSlabsSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/post/PostProcessingWallsSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/spawn/EffectSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/spawn/SpawnerSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/BiomeLayers.java (98%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/CaveCeilingLayersSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/ColumnSlope.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/ExplodeBiomePaletteSizeSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/ExplodeBiomePalettesSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/FluidPaletteSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/HideOresSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/LayerBlocks.java (98%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/LayerNoise.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/LayeredBiome.java (93%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/LockLayersMaxSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/LockLayersSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/OreGenerator.java (98%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/OreSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/PaletteBlocks.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/PaletteExplosion.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/ResolvedLayer.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/RockPaletteSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/SeaLayersSettings.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/SlabSettings.java (94%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/TerrainPalettes.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/terrain/WallSettings.java (94%) rename src/main/java/art/arcane/iris/{builtin => modules}/vanillafeatures/ImportedFeaturesSettings.java (98%) diff --git a/README.md b/README.md index ae8a17454..d6adb7459 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,11 @@ planned caves), `iris:post`, `iris:floating` (solids), `iris:deposit`, `iris:mat `iris:floating` (decoration), `iris:perfection` and `iris:custom`. There are no world modes and no Iris mantle components outside the stage graph any more. Their stage constants, and the settings and output types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack -modules; their stage bodies live beside the features they replace. +modules; their stage bodies live beside the features they replace. Settings and helper types that only the jar's modules read, +which Iris itself never touches, live in `art.arcane.iris.modules` instead, which Iris does not expose: the jar loads its own copy. +A type a pack writes as a snippet stays in `art.arcane.iris.builtin` even when only the jar reads it, because the snippet folder of +a type the host does not share must start with its module's id (`snippet/iris/carve/...`), and packs keep theirs where they always +were (`snippet/cave-profile/...`). Two of those modules are not in this project: `iris:biome` (writes the layout's platform biomes into the chunk) and `iris:custom` (records the platform's custom blocks of content plugins) are Iris itself, so their classes live in Iris @@ -83,8 +87,8 @@ regions and biomes. The loot tables, spawners, entities and markers are plain mo the `IrisChunk` their invocation offers (`context.extension(IrisChunk.class)`, then `state(...)`) or `engine.getGeneration().state(...)`. Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types -only: `DepositSettings` holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in -`art.arcane.iris.builtin.deposit`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the +only: `DepositSettings` (`art.arcane.iris.modules.deposit`) holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in +`art.arcane.iris.builtin.deposit`, since packs write generators as `snippet/deposit/...`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. The deposits run one generator after the other, each with a random of its own; they used to spread over threads on a multicore pregen, which no module can do (stages run on the host's threads). @@ -110,14 +114,14 @@ objects the same way. `iris:terrain` and `iris:post` own the fields that shape a column's blocks. Per biome: `layers`, `seaLayers`, `caveCeilingLayers` (lists of `PaletteLayer`, the old biome palette layer, in `art.arcane.iris.builtin.terrain`), `slab` and `wall` (one `PaletteLayer` each), `lockLayers` (a -boolean) and `lockLayersMax` (a number). Per dimension: `rockPalette` and `fluidPalette` (a `PaletteSpec` each) in `art.arcane.iris.builtin.terrain`, and -`postProcessing`, `postProcessingSlabs`, `postProcessingWalls` (booleans) in `art.arcane.iris.builtin.post`; `bedrock`, `explodeBiomePalettes` and +boolean) and `lockLayersMax` (a number). Per dimension: `rockPalette` and `fluidPalette` (a `PaletteSpec` each) in `art.arcane.iris.modules.terrain`, and +`postProcessing`, `postProcessingSlabs`, `postProcessingWalls` (booleans) in `art.arcane.iris.modules.post`; `bedrock`, `explodeBiomePalettes` and `explodeBiomePaletteSize` are dimension keys of `iris:terrain` too. A key a pack leaves out has the default Iris always had (one grass layer, no slab or wall, stone and water, post processing on). `ResolvedLayer` resolves one layer's blocks and noise for a pack, `BiomeLayers`, the world's state, keeps them and stacks a biome's layers into the blocks of a column, and `TerrainPalettes` is the world's -rock and fluid as a block for every column; the terrain, cave, floating and post stages ask them. Both live in `art.arcane.iris.builtin.terrain`, which -Iris exposes, so the jar's terrain and the carving compiled into Iris share one copy of them: a biome's layer thickness noise is built once, from the random -of whoever asks first, as it always was. The slope limit of a layer, a decorator and an +rock and fluid as a block for every column; the terrain, cave, floating, post and vacuum stages ask them. All of them are the jar's own +(`art.arcane.iris.modules.terrain`), and every stage that asks is in the jar, so one copy serves them all: a biome's layer thickness noise is built once, +from the random of whoever asks first, as it always was. The slope limit of a layer, a decorator and an object placement is the one `SlopeClip`. Caves, floating islands and ores are settings of their modules too, written under the keys they always had. `iris:carve` owns @@ -199,8 +203,7 @@ through the thread or a cast: a module asks `world.extension(X.class)` for what in a placement stage, `MatterMantle` in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), which Iris answers with the seeds its worlds always -had, so existing worlds generate the same; `terrain.LayerBlocks` (the world's picks from the biomes' palette layers: terrain, caves and post pick from the same -layers, and a layer's noise is built once per world by whichever asks first), `spawn.SpawnCooldowns` (the spawner cooldowns +had, so existing worlds generate the same; `spawn.SpawnCooldowns` (the spawner cooldowns Iris saves with the world's data, so they survive a restart), `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`, which the modules @@ -217,8 +220,8 @@ placement's own states). Its types answer with IrisApi, VolmLib and built-in val applies, which the platform and the rest of Iris read as slices, not as module layers). A mantle stage gets the whole mantle; a chunk stage gets its own chunk and the neighbors the world already holds in memory, which is all the cave apply stage ever read, so it writes nothing outside its chunk. What a -cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`terrain.BiomeLayers`, -`terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. +cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`modules.terrain.BiomeLayers`, +`modules.terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its absolute world Y bands convert with `PackWorld.minWorldY()`, and its noise reads `NoiseSampler.signed(...)` (Iris's memoised signed read) and `scaled(...)`. `caveLavaHeight` and `upperDimensionCarving` are its dimension settings. diff --git a/builtin-modules.txt b/builtin-modules.txt index 344628e87..6e22b08b6 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -14,6 +14,9 @@ # # Moving a module here means removing it from IrisModuleHost.generationModules() in Iris. +# The settings and helper types only the jar's modules use, which Iris does not expose. +include art/arcane/iris/modules/** + module art.arcane.iris.engine.modifier.PostModule include art/arcane/iris/engine/modifier/SurfaceSmoothing*.class module art.arcane.iris.engine.modifier.PerfectionModule diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index bd72b7c93..ca33b5443 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -24,15 +24,14 @@ *

* Keep implementation out of it: stage bodies and anything that uses Iris internals live in the * built-in module classes outside this package, which packs cannot see. Settings and output types go in one - * subpackage per built-in module, named after the module path, such as {@code art.arcane.iris.builtin.deposit} - * for {@code iris:deposit}. + * subpackage per built-in module, named after the module path, such as {@code art.arcane.iris.builtin.spawn} + * for {@code iris:spawn}. A type only the built-ins jar uses, which Iris itself never reads, lives in + * {@code art.arcane.iris.modules} instead, which Iris does not expose. *

- * Besides those, it holds what the compiled-in built-ins and the built-ins jar must share, since each sees its own copy + * Besides those, it holds what Iris and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.spawn.SpawnCooldowns}, {@link art.arcane.iris.builtin.objects.ObjectHost}), the seed purposes Iris - * answers with its legacy seeds ({@link art.arcane.iris.builtin.IrisSeedPurposes}), - * and per-world state several of them use ({@link art.arcane.iris.builtin.terrain.LayerBlocks}, - * {@link art.arcane.iris.builtin.terrain.BiomeLayers}, {@link art.arcane.iris.builtin.terrain.TerrainPalettes}). Keep them few: each is + * ({@link art.arcane.iris.builtin.spawn.SpawnCooldowns}, {@link art.arcane.iris.builtin.objects.ObjectHost}), and the seed purposes Iris + * answers with its legacy seeds ({@link art.arcane.iris.builtin.IrisSeedPurposes}). Keep them few: each is * a promise. *

* The placement stages ({@code iris:prepare} to {@code iris:snow}) reach the object being placed through diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 2837c98ca..73bc33b72 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.decorant.DecorantSettings; -import art.arcane.iris.builtin.decorant.DecorateSettings; +import art.arcane.iris.modules.decorant.DecorateSettings; import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.decorator.DecoratedBiome; import art.arcane.iris.engine.decorator.DecorationScene; diff --git a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java index 81069d8b5..8c54bb907 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/actuator/OreWarmUp.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.modules.terrain.OreSettings; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Level; diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java index 9593b00cb..dfd2a243a 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOre.java @@ -17,7 +17,7 @@ */ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.terrain.OreGenerator; +import art.arcane.iris.modules.terrain.OreGenerator; import art.arcane.volmlib.util.cache.AtomicCache; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; diff --git a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java index ed313ea66..002113c92 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/ResolvedOres.java @@ -17,8 +17,8 @@ */ package art.arcane.iris.engine.actuator; -import art.arcane.iris.builtin.terrain.OreGenerator; -import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.modules.terrain.OreGenerator; +import art.arcane.iris.modules.terrain.OreSettings; import com.volmit.block.BlockState; import com.volmit.resource.PackResources; diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index f11596586..8302ca016 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -19,19 +19,19 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.terrain.BedrockSettings; -import art.arcane.iris.builtin.terrain.CaveCeilingLayersSettings; -import art.arcane.iris.builtin.terrain.ExplodeBiomePaletteSizeSettings; -import art.arcane.iris.builtin.terrain.ExplodeBiomePalettesSettings; -import art.arcane.iris.builtin.terrain.FluidPaletteSettings; -import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.modules.terrain.CaveCeilingLayersSettings; +import art.arcane.iris.modules.terrain.ExplodeBiomePaletteSizeSettings; +import art.arcane.iris.modules.terrain.ExplodeBiomePalettesSettings; +import art.arcane.iris.modules.terrain.FluidPaletteSettings; +import art.arcane.iris.modules.terrain.HideOresSettings; import art.arcane.iris.builtin.terrain.LayersSettings; -import art.arcane.iris.builtin.terrain.LockLayersMaxSettings; -import art.arcane.iris.builtin.terrain.LockLayersSettings; -import art.arcane.iris.builtin.terrain.OreSettings; -import art.arcane.iris.builtin.terrain.RockPaletteSettings; -import art.arcane.iris.builtin.terrain.SeaLayersSettings; -import art.arcane.iris.builtin.terrain.SlabSettings; -import art.arcane.iris.builtin.terrain.WallSettings; +import art.arcane.iris.modules.terrain.LockLayersMaxSettings; +import art.arcane.iris.modules.terrain.LockLayersSettings; +import art.arcane.iris.modules.terrain.OreSettings; +import art.arcane.iris.modules.terrain.RockPaletteSettings; +import art.arcane.iris.modules.terrain.SeaLayersSettings; +import art.arcane.iris.modules.terrain.SlabSettings; +import art.arcane.iris.modules.terrain.WallSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; @@ -39,7 +39,7 @@ import com.volmit.ModuleSetup; import com.volmit.stage.ChunkStageContext; import com.volmit.world.PackWorld; -import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.iris.modules.terrain.TerrainPalettes; /** * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java index aee9ca754..49967a2b8 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainOres.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.modules.terrain.OreSettings; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java index c960aeab4..3c897c989 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainShaper.java @@ -19,14 +19,14 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.terrain.BedrockSettings; -import art.arcane.iris.builtin.terrain.HideOresSettings; -import art.arcane.iris.builtin.terrain.OreSettings; +import art.arcane.iris.modules.terrain.HideOresSettings; +import art.arcane.iris.modules.terrain.OreSettings; import art.arcane.iris.engine.actuator.ResolvedOres.YBand; -import art.arcane.iris.builtin.terrain.BiomeLayers; -import art.arcane.iris.builtin.terrain.ColumnSlope; -import art.arcane.iris.builtin.terrain.LayeredBiome; -import art.arcane.iris.builtin.terrain.PaletteExplosion; -import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.iris.modules.terrain.BiomeLayers; +import art.arcane.iris.modules.terrain.ColumnSlope; +import art.arcane.iris.modules.terrain.LayeredBiome; +import art.arcane.iris.modules.terrain.PaletteExplosion; +import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisFeature; @@ -230,8 +230,8 @@ final class TerrainShaper { /** What the biome of the upper dimension at the column declares about its layers. */ private LayeredBiome upperBiome(FeatureSettings upperSettings, int worldX, int worldZ) { return new LayeredBiome(biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LayersSettings.class, worldX, worldZ), null, null, - biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LockLayersSettings.class, worldX, worldZ), - biomeLevel(upperSettings, art.arcane.iris.builtin.terrain.LockLayersMaxSettings.class, worldX, worldZ), null); + biomeLevel(upperSettings, art.arcane.iris.modules.terrain.LockLayersSettings.class, worldX, worldZ), + biomeLevel(upperSettings, art.arcane.iris.modules.terrain.LockLayersMaxSettings.class, worldX, worldZ), null); } private static S biomeLevel(FeatureSettings settings, Class type, int worldX, int worldZ) { diff --git a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java index 15f5367d5..b97e597ed 100644 --- a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java +++ b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/ImportedFeatures.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.framework.vanillafeatures; import art.arcane.iris.builtin.RegistryKeyFamily; -import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings; +import art.arcane.iris.modules.vanillafeatures.ImportedFeaturesSettings; import com.volmit.resource.ResourceId; import com.volmit.service.VanillaFeatures; import com.volmit.vanilla.DecorationStep; diff --git a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java index 3e14713d5..74fe3ea30 100644 --- a/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java +++ b/src/main/java/art/arcane/iris/engine/framework/vanillafeatures/VanillaFeaturesModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.framework.vanillafeatures; -import art.arcane.iris.builtin.vanillafeatures.ImportedFeaturesSettings; +import art.arcane.iris.modules.vanillafeatures.ImportedFeaturesSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index def6c09d8..b34e0641e 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.loot.BlockDrop; -import art.arcane.iris.builtin.loot.BlockDropSettings; +import art.arcane.iris.modules.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index d29cd6677..3da073e4d 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.loot.BlockDropSettings; +import art.arcane.iris.modules.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootSettings; import art.arcane.iris.builtin.loot.ObjectLoot; import art.arcane.iris.builtin.loot.ObjectVanillaLoot; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 279de0056..3ed1d5baa 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.modules.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.builtin.floating.IslandFootprint; import art.arcane.iris.builtin.objects.ObjectHost; diff --git a/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java b/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java index c54076c93..705ef99df 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/BuiltInCaveDressing.java @@ -19,10 +19,10 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.builtin.terrain.BiomeLayers; -import art.arcane.iris.builtin.terrain.ColumnSlope; -import art.arcane.iris.builtin.terrain.PaletteExplosion; -import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.iris.modules.terrain.BiomeLayers; +import art.arcane.iris.modules.terrain.ColumnSlope; +import art.arcane.iris.modules.terrain.PaletteExplosion; +import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.decorator.DecoratedBiome; import art.arcane.iris.engine.decorator.DecorationScene; diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 93c141c92..12e70ddf9 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -21,14 +21,14 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.MatterMantle; -import art.arcane.iris.builtin.carve.CarvingBiomeSettings; -import art.arcane.iris.builtin.carve.CarvingEnabledSettings; -import art.arcane.iris.builtin.carve.CarvingSettings; -import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.modules.carve.CarvingBiomeSettings; +import art.arcane.iris.modules.carve.CarvingEnabledSettings; +import art.arcane.iris.modules.carve.CarvingSettings; +import art.arcane.iris.modules.carve.CaveDepthSettings; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.carve.UpperDimensionCarvingSettings; -import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings; +import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.iris.engine.mantle.components.CaveCarving; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java index 587b9bdd0..49ede6917 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveBiomeBands.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.carve.CaveDepthSettings; +import art.arcane.iris.modules.carve.CaveDepthSettings; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.DeclaredByLevel; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index fbdb502e7..aa349a945 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -20,10 +20,10 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.deposit.DepositGenerator; -import art.arcane.iris.builtin.deposit.DepositSettings; -import art.arcane.iris.builtin.deposit.DepositVariantSettings; -import art.arcane.iris.builtin.deposit.OreFrequencySettings; -import art.arcane.iris.builtin.deposit.OreSizeSettings; +import art.arcane.iris.modules.deposit.DepositSettings; +import art.arcane.iris.modules.deposit.DepositVariantSettings; +import art.arcane.iris.modules.deposit.OreFrequencySettings; +import art.arcane.iris.modules.deposit.OreSizeSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 52aaf9598..5772d7452 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -22,9 +22,9 @@ import art.arcane.iris.builtin.deposit.DepositGenerator; import art.arcane.iris.builtin.deposit.DepositHeightDistribution; import art.arcane.iris.builtin.deposit.DepositPlacementScope; import art.arcane.iris.builtin.deposit.DepositVariant; -import art.arcane.iris.builtin.deposit.DepositVariantSettings; -import art.arcane.iris.builtin.deposit.OreFrequencySettings; -import art.arcane.iris.builtin.deposit.OreSizeSettings; +import art.arcane.iris.modules.deposit.DepositVariantSettings; +import art.arcane.iris.modules.deposit.OreFrequencySettings; +import art.arcane.iris.modules.deposit.OreSizeSettings; import art.arcane.iris.engine.modifier.ResolvedDeposit.BiomeIdentity; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index c3cb11365..0285e5b90 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -23,12 +23,12 @@ import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; import art.arcane.iris.builtin.prepare.SlopeClip; -import art.arcane.iris.builtin.terrain.BiomeLayers; -import art.arcane.iris.builtin.terrain.ColumnSlope; -import art.arcane.iris.builtin.terrain.LayerNoise; -import art.arcane.iris.builtin.terrain.PaletteExplosion; +import art.arcane.iris.modules.terrain.BiomeLayers; +import art.arcane.iris.modules.terrain.ColumnSlope; +import art.arcane.iris.modules.terrain.LayerNoise; +import art.arcane.iris.modules.terrain.PaletteExplosion; import art.arcane.iris.builtin.terrain.PaletteLayer; -import art.arcane.iris.builtin.terrain.ResolvedLayer; +import art.arcane.iris.modules.terrain.ResolvedLayer; import art.arcane.iris.engine.decorator.BiomeDecorators; import art.arcane.iris.engine.decorator.DecoratedBiome; import art.arcane.iris.engine.decorator.DecorationScene; diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 1b84810cc..8e3ef5fa9 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -19,8 +19,8 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.floating.FloatingChildSettings; -import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; +import art.arcane.iris.modules.floating.FloatingChildSettings; +import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; import art.arcane.iris.engine.mantle.components.FloatingObjectPlacing; import com.volmit.IrisModule; import com.volmit.ModuleInfo; diff --git a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java index 057669ff0..0c57ee111 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PerfectionModule.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.terrain.HideOresSettings; +import art.arcane.iris.modules.terrain.HideOresSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index a28fe3c3b..936b968f6 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -19,9 +19,9 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.post.PostProcessingSettings; -import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; -import art.arcane.iris.builtin.post.PostProcessingWallsSettings; +import art.arcane.iris.modules.post.PostProcessingSettings; +import art.arcane.iris.modules.post.PostProcessingSlabsSettings; +import art.arcane.iris.modules.post.PostProcessingWallsSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; diff --git a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java index 21d4508e2..667f4be76 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java +++ b/src/main/java/art/arcane/iris/engine/modifier/SurfaceSmoothing.java @@ -19,12 +19,12 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.post.PostProcessingSlabsSettings; -import art.arcane.iris.builtin.post.PostProcessingWallsSettings; -import art.arcane.iris.builtin.terrain.LayerBlocks; +import art.arcane.iris.modules.post.PostProcessingSlabsSettings; +import art.arcane.iris.modules.post.PostProcessingWallsSettings; +import art.arcane.iris.modules.terrain.LayerBlocks; import art.arcane.iris.builtin.terrain.PaletteLayer; -import art.arcane.iris.builtin.terrain.SlabSettings; -import art.arcane.iris.builtin.terrain.WallSettings; +import art.arcane.iris.modules.terrain.SlabSettings; +import art.arcane.iris.modules.terrain.WallSettings; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisFeature; import com.volmit.block.BlockRegistry; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 3969448f0..9627612ba 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -26,7 +26,7 @@ import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.PlaneNoise; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; -import art.arcane.iris.builtin.terrain.TerrainPalettes; +import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.builtin.vacuum.VacuumSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index 81cf757fb..8611e7f36 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.modules.carve.CarvingSettings; import com.volmit.ModuleLog; import com.volmit.config.Range; import com.volmit.noise.NoiseSampler; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index 00bf35ed2..e78e4d125 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -20,12 +20,12 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.modules.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; -import art.arcane.iris.builtin.floating.FloatingChildSettings; +import art.arcane.iris.modules.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.FloatingHost; -import art.arcane.iris.builtin.floating.MergeFloatingChildrenSettings; +import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; diff --git a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java index 1c35bd195..ecdaba34b 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java +++ b/src/main/java/art/arcane/iris/engine/spawn/AmbientEffecting.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EffectCommands; -import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.modules.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.engine.loot.BlockBiomes; import art.arcane.iris.engine.loot.PlatformKeys; diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 0d178d35a..e9efe4bb0 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -26,7 +26,7 @@ import art.arcane.iris.builtin.spawn.SpawnCooldowns; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.SpawnSurface; import art.arcane.iris.builtin.spawn.Spawner; -import art.arcane.iris.builtin.spawn.SpawnerSettings; +import art.arcane.iris.modules.spawn.SpawnerSettings; import art.arcane.iris.engine.loot.LootItems; import art.arcane.iris.engine.spawn.SpawnResources.KeyedSpawner; import art.arcane.volmlib.util.collection.KList; diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index d964b4a0d..78f805d35 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.spawn.EffectSettings; +import art.arcane.iris.modules.spawn.EffectSettings; import art.arcane.iris.builtin.spawn.PlacementMarker; -import art.arcane.iris.builtin.spawn.SpawnerSettings; +import art.arcane.iris.modules.spawn.SpawnerSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java rename to src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java index 3e4398221..964676cd3 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingBiomeSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java b/src/main/java/art/arcane/iris/modules/carve/CarvingEnabledSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java rename to src/main/java/art/arcane/iris/modules/carve/CarvingEnabledSettings.java index 21f6c1385..eb5339324 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingEnabledSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingEnabledSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java rename to src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java index 16bc33f71..36941b629 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; +import art.arcane.iris.builtin.carve.CarvingEntry; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java b/src/main/java/art/arcane/iris/modules/carve/CaveDepthSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java rename to src/main/java/art/arcane/iris/modules/carve/CaveDepthSettings.java index 4c09160f5..10393858b 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CaveDepthSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CaveDepthSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java b/src/main/java/art/arcane/iris/modules/carve/UpperDimensionCarvingSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java rename to src/main/java/art/arcane/iris/modules/carve/UpperDimensionCarvingSettings.java index 2d6d05e2c..a9a18fd8a 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/UpperDimensionCarvingSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/UpperDimensionCarvingSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java b/src/main/java/art/arcane/iris/modules/decorant/DecorateSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java rename to src/main/java/art/arcane/iris/modules/decorant/DecorateSettings.java index c9d7cc943..7d68745e5 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecorateSettings.java +++ b/src/main/java/art/arcane/iris/modules/decorant/DecorateSettings.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.decorant; +package art.arcane.iris.modules.decorant; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java similarity index 94% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java index 208f6fb52..e080867dc 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositSettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; +import art.arcane.iris.builtin.deposit.DepositGenerator; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java b/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java index 5578aa9f3..7ba4980d9 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariantSettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; +import art.arcane.iris.builtin.deposit.DepositVariant; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java b/src/main/java/art/arcane/iris/modules/deposit/OreFrequencySettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java rename to src/main/java/art/arcane/iris/modules/deposit/OreFrequencySettings.java index 2d8f61ccb..8576e8f86 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/OreFrequencySettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/OreFrequencySettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java b/src/main/java/art/arcane/iris/modules/deposit/OreSizeSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java rename to src/main/java/art/arcane/iris/modules/deposit/OreSizeSettings.java index 9c3dd9d2b..31052380c 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/OreSizeSettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/OreSizeSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java rename to src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java index 072629fdb..8e6a97863 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildSettings.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java @@ -16,9 +16,10 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; -import art.arcane.iris.builtin.carve.CarvingSettings; +import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.modules.carve.CarvingSettings; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java b/src/main/java/art/arcane/iris/modules/floating/MergeFloatingChildrenSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java rename to src/main/java/art/arcane/iris/modules/floating/MergeFloatingChildrenSettings.java index 2fad82f8b..3a6e030c8 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/MergeFloatingChildrenSettings.java +++ b/src/main/java/art/arcane/iris/modules/floating/MergeFloatingChildrenSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java b/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java rename to src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java index 948c3b5c9..659a257d6 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/BlockDropSettings.java +++ b/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.loot; +package art.arcane.iris.modules.loot; +import art.arcane.iris.builtin.loot.BlockDrop; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java b/src/main/java/art/arcane/iris/modules/post/PostProcessingSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java rename to src/main/java/art/arcane/iris/modules/post/PostProcessingSettings.java index c434601f7..17d0cbaaf 100644 --- a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSettings.java +++ b/src/main/java/art/arcane/iris/modules/post/PostProcessingSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.post; +package art.arcane.iris.modules.post; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java b/src/main/java/art/arcane/iris/modules/post/PostProcessingSlabsSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java rename to src/main/java/art/arcane/iris/modules/post/PostProcessingSlabsSettings.java index 36c5b9885..636b77953 100644 --- a/src/main/java/art/arcane/iris/builtin/post/PostProcessingSlabsSettings.java +++ b/src/main/java/art/arcane/iris/modules/post/PostProcessingSlabsSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.post; +package art.arcane.iris.modules.post; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java b/src/main/java/art/arcane/iris/modules/post/PostProcessingWallsSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java rename to src/main/java/art/arcane/iris/modules/post/PostProcessingWallsSettings.java index 658f97e0c..d475ff1e7 100644 --- a/src/main/java/art/arcane/iris/builtin/post/PostProcessingWallsSettings.java +++ b/src/main/java/art/arcane/iris/modules/post/PostProcessingWallsSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.post; +package art.arcane.iris.modules.post; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java b/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java rename to src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java index 99a51be5f..71ba8ca72 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EffectSettings.java +++ b/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.spawn; +package art.arcane.iris.modules.spawn; +import art.arcane.iris.builtin.spawn.AmbientEffect; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java b/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java rename to src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java index e2a2725cb..7162227e2 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnerSettings.java +++ b/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.spawn; +package art.arcane.iris.modules.spawn; +import art.arcane.iris.builtin.spawn.Spawner; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/terrain/BiomeLayers.java rename to src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java index ed0105594..71906e315 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/BiomeLayers.java +++ b/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java @@ -15,9 +15,11 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.LayersSettings; +import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java b/src/main/java/art/arcane/iris/modules/terrain/CaveCeilingLayersSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/CaveCeilingLayersSettings.java index e2a8c9c12..e4d7f490b 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/CaveCeilingLayersSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/CaveCeilingLayersSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; +import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java b/src/main/java/art/arcane/iris/modules/terrain/ColumnSlope.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java rename to src/main/java/art/arcane/iris/modules/terrain/ColumnSlope.java index 9a0da0a4b..c09d1dc84 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/ColumnSlope.java +++ b/src/main/java/art/arcane/iris/modules/terrain/ColumnSlope.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; /** The slope of the terrain at a column, asked only when a layer limits where it shows by slope. */ @FunctionalInterface diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java b/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePaletteSizeSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePaletteSizeSettings.java index bc1d156ba..ebf9b7267 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePaletteSizeSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePaletteSizeSettings.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java b/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePalettesSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePalettesSettings.java index a47485ed6..a1bfea78e 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/ExplodeBiomePalettesSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/ExplodeBiomePalettesSettings.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java b/src/main/java/art/arcane/iris/modules/terrain/FluidPaletteSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/FluidPaletteSettings.java index b0a336996..75c725ae3 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/FluidPaletteSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/FluidPaletteSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java b/src/main/java/art/arcane/iris/modules/terrain/HideOresSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/HideOresSettings.java index 84cfb13b8..432d533eb 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/HideOresSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/HideOresSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayerBlocks.java b/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/terrain/LayerBlocks.java rename to src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java index 6ae0f400b..0887c3ac3 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LayerBlocks.java +++ b/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; +import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java b/src/main/java/art/arcane/iris/modules/terrain/LayerNoise.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java rename to src/main/java/art/arcane/iris/modules/terrain/LayerNoise.java index c99dad96d..daf2180c1 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LayerNoise.java +++ b/src/main/java/art/arcane/iris/modules/terrain/LayerNoise.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.noise.NoiseSampler; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java b/src/main/java/art/arcane/iris/modules/terrain/LayeredBiome.java similarity index 93% rename from src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java rename to src/main/java/art/arcane/iris/modules/terrain/LayeredBiome.java index 4cde1683d..ab5185d14 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LayeredBiome.java +++ b/src/main/java/art/arcane/iris/modules/terrain/LayeredBiome.java @@ -15,7 +15,9 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; + +import art.arcane.iris.builtin.terrain.LayersSettings; /** diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java b/src/main/java/art/arcane/iris/modules/terrain/LockLayersMaxSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/LockLayersMaxSettings.java index 4746b6ab6..68d543355 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersMaxSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/LockLayersMaxSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java b/src/main/java/art/arcane/iris/modules/terrain/LockLayersSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/LockLayersSettings.java index 7204003c4..0d0fa56e1 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/LockLayersSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/LockLayersSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java b/src/main/java/art/arcane/iris/modules/terrain/OreGenerator.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java rename to src/main/java/art/arcane/iris/modules/terrain/OreGenerator.java index 1f9cb8f47..7893b323a 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/OreGenerator.java +++ b/src/main/java/art/arcane/iris/modules/terrain/OreGenerator.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.block.PaletteSpec; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java b/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/OreSettings.java index 4f82565aa..256c9cae4 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/OreSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/PaletteBlocks.java b/src/main/java/art/arcane/iris/modules/terrain/PaletteBlocks.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/PaletteBlocks.java rename to src/main/java/art/arcane/iris/modules/terrain/PaletteBlocks.java index cf69aef45..0264da295 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/PaletteBlocks.java +++ b/src/main/java/art/arcane/iris/modules/terrain/PaletteBlocks.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java b/src/main/java/art/arcane/iris/modules/terrain/PaletteExplosion.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java rename to src/main/java/art/arcane/iris/modules/terrain/PaletteExplosion.java index b88d7a2f7..08ca17cc8 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/PaletteExplosion.java +++ b/src/main/java/art/arcane/iris/modules/terrain/PaletteExplosion.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.FeatureSettings; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/ResolvedLayer.java b/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/ResolvedLayer.java rename to src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java index 413669206..f484309c4 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/ResolvedLayer.java +++ b/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java @@ -15,9 +15,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.terrain.PaletteLayer; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java b/src/main/java/art/arcane/iris/modules/terrain/RockPaletteSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/RockPaletteSettings.java index 66dd5fd4a..21cc14f94 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/RockPaletteSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/RockPaletteSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java b/src/main/java/art/arcane/iris/modules/terrain/SeaLayersSettings.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/SeaLayersSettings.java index e81e00b2a..9354ca99f 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/SeaLayersSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/SeaLayersSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; +import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java b/src/main/java/art/arcane/iris/modules/terrain/SlabSettings.java similarity index 94% rename from src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/SlabSettings.java index 46adeef22..f5adfc3c0 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/SlabSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/SlabSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; +import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java b/src/main/java/art/arcane/iris/modules/terrain/TerrainPalettes.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java rename to src/main/java/art/arcane/iris/modules/terrain/TerrainPalettes.java index 837713836..5f56d978d 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/TerrainPalettes.java +++ b/src/main/java/art/arcane/iris/modules/terrain/TerrainPalettes.java @@ -15,7 +15,7 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.volmlib.util.cache.AtomicCache; diff --git a/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java b/src/main/java/art/arcane/iris/modules/terrain/WallSettings.java similarity index 94% rename from src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java rename to src/main/java/art/arcane/iris/modules/terrain/WallSettings.java index 3ef3e8d8a..06d5fa6a5 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/WallSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/WallSettings.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.terrain; +package art.arcane.iris.modules.terrain; +import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java b/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java rename to src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java index 543309866..69ee50b1c 100644 --- a/src/main/java/art/arcane/iris/builtin/vanillafeatures/ImportedFeaturesSettings.java +++ b/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.vanillafeatures; +package art.arcane.iris.modules.vanillafeatures; import com.volmit.config.Level; import com.volmit.IrisFeature; From 749b187dc4a1c4de0aeec1265f030116e59d65c1 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 27 Oct 2026 00:59:47 +0100 Subject: [PATCH 107/139] Batch 7 stage 1: jigsaw definitions become iris:structure resource kinds IrisStructure, IrisJigsawPiece, IrisJigsawPieceEntry, IrisJigsawPool, IrisJigsawConnector, IrisJigsawWorkcell, IrisJigsawWorkcellArchetype and StructureResources move here from Iris core, with IrisDirection (without its Bukkit helpers, which nothing used) and a KeyedResource base for the key Iris sets when it reads a resource file. The kinds are iris:structure/structure, /pool and /piece, registered by StructureModule. StructureModule leaves the built-ins jar: Iris registers it with its own modules, because Iris's jigsaw studio, importers and exporters read the resources it registers as the same classes, which a jar's own copy of a class is not. --- README.md | 24 +-- builtin-modules.txt | 3 +- .../structure/StructureResources.java | 92 ++++++++++++ .../mantle/components/StructureModule.java | 13 +- .../iris/engine/object/KeyedResource.java | 41 ++++++ .../object/structure/IrisStructure.java | 139 ++++++++++++++++++ .../structure/jigsaw/IrisJigsawConnector.java | 96 ++++++++++++ .../structure/jigsaw/IrisJigsawPiece.java | 94 ++++++++++++ .../jigsaw/IrisJigsawPieceEntry.java | 66 +++++++++ .../structure/jigsaw/IrisJigsawPool.java | 63 ++++++++ .../structure/jigsaw/IrisJigsawWorkcell.java | 40 +++++ .../jigsaw/IrisJigsawWorkcellArchetype.java | 88 +++++++++++ .../engine/object/value/IrisDirection.java | 87 +++++++++++ 13 files changed, 831 insertions(+), 15 deletions(-) create mode 100644 src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java create mode 100644 src/main/java/art/arcane/iris/engine/object/KeyedResource.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java create mode 100644 src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java create mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java diff --git a/README.md b/README.md index d6adb7459..8f1513f25 100644 --- a/README.md +++ b/README.md @@ -30,14 +30,16 @@ service or hook, `setup.log()` during setup), which labels each line with the mo use `IrisLogging`. Classes of the host's object model (the host-classes list) and code that only has an engine or pack data still log as Iris itself. -Modules also own pack resources and checks of their own. Iris's own module `iris:structure-model` (core -`StructureModelModule`) reads structures, jigsaw pools and jigsaw pieces as resource kinds (`StructureResources`, -`iris:structure-model/structure`, `/pool`, `/piece`), from the folders and files packs have always used, and checks -them with its validator (`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris -validates a pack. The structure model, assembler, locator, fitting and placing are host: the jigsaw studio, the -structure importers and exporters read them too. `iris:structure` in the built-ins jar declares the structure -placement settings and the mantle stage, and places through the `StructureHost` facade -(`art.arcane.iris.builtin.structure`). +Modules also own pack resources and checks of their own. `iris:structure` (`StructureModule`) reads structures, jigsaw +pools and jigsaw pieces as resource kinds (`StructureResources`, `iris:structure/structure`, `/pool`, `/piece`), from the +folders and files packs have always used, and declares the structure placement settings and the mantle stage. Its +definitions (`IrisStructure`, `IrisJigsawPiece`, `IrisJigsawPool` and their parts in `engine/object/structure`) live +here and build against the API. It is not in the built-ins jar: Iris registers it with its own modules, because Iris's +jigsaw studio, importers and exporters read the structures it registers as the same classes, which a jar's own copy of +a class is not. Iris's own module `iris:structure-model` (core `StructureModelModule`) checks them with its validator +(`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris validates a pack. The +assembler, locator, fitting and placing are still Iris's, and `iris:structure` places through the `StructureHost` +facade (`art.arcane.iris.builtin.structure`). Built-in modules answer Iris through IrisApi services instead of Iris reading their features: `iris:objects` provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure-model` @@ -163,8 +165,10 @@ compiled these sources itself. 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`. +styles, expressions, images), the pack's objects and blocks, the structure assembler, locator, fitting and placer +(behind `StructureHost`), and the object placers behind `ObjectHost` and `FloatingHost`. A module this build holds +but the jar does not, such as `iris:structure`, is one Iris registers with its own modules (`IrisModuleHost`): its +classes are then the ones Iris's own code sees. `./gradlew check` compiles every source and builds the built-ins jar below, which runs the pack class checks. diff --git a/builtin-modules.txt b/builtin-modules.txt index 6e22b08b6..76a7b50f2 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -94,4 +94,5 @@ include art/arcane/iris/engine/mantle/components/FloatingObjectPlacing*.class include art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver*.class include art/arcane/iris/engine/mantle/components/IslandFace*.class include art/arcane/iris/engine/mantle/components/UndersideTurn*.class -module art.arcane.iris.engine.mantle.components.StructureModule +# iris:structure (art.arcane.iris.engine.mantle.components.StructureModule) is not here: Iris registers it with its own +# modules, because its jigsaw studio reads the structure resources the module registers. 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 new file mode 100644 index 000000000..219c84836 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -0,0 +1,92 @@ +/* + * 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.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 {@code iris:structure}, which keep the folders and files Iris packs have always used, and + * lookups by pack key for code that names structures, pools and pieces by key. Every lookup goes through the pack's + * {@link PackResources}, so it sees the pack's current snapshot: a hotload, or a tool that rewrote the files and asked + * for a new snapshot, reads them again. + *

+ * Lookups answer null 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/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/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/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(PackResources pack, String key) { + return find(pack, STRUCTURES, key); + } + + public static IrisJigsawPool pool(PackResources pack, String key) { + return find(pack, POOLS, key); + } + + public static IrisJigsawPiece piece(PackResources pack, String key) { + return find(pack, PIECES, key); + } + + /** The key of every structure of the pack snapshot {@code pack}, in key order. */ + public static List structureKeys(PackResources pack) { + return keys(pack, STRUCTURES); + } + + /** The key of every jigsaw piece of the pack snapshot {@code pack}, in key order. */ + public static List pieceKeys(PackResources pack) { + return keys(pack, PIECES); + } + + private static T find(PackResources pack, ResourceKind kind, String key) { + if (key == null || key.isBlank()) { + return null; + } + try { + return pack.find(kind, pack.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(PackResources pack, ResourceKind kind) { + return pack.ids(kind).stream().map(ResourceId::path).toList(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index ce5958210..55c1fcc37 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -22,6 +22,7 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.structure.StructureHost; import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureSettings; +import art.arcane.iris.engine.framework.structure.StructureResources; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; @@ -29,10 +30,13 @@ import com.volmit.config.PackSettings; import com.volmit.stage.MantleStageContext; /** - * Module {@code iris:structure}: the structure placements a pack declares, and the mantle stage that places the jigsaw - * structures starting in each chunk. Iris builds and places the structures ({@link StructureHost}); the structure - * resources, their validation, the locator and the platform structure answers are Iris's own module - * {@code iris:structure-model}. + * Module {@code iris:structure}: the jigsaw structures, pools and pieces of a pack (its resource kinds), the structure + * placements a pack declares, and the mantle stage that places the structures starting in each chunk. Iris builds and + * places the structures ({@link StructureHost}); their validation, the locator and the platform structure answers are + * Iris's own module {@code iris:structure-model}. + *

+ * It is not in the built-ins jar: Iris registers it with its own modules, because Iris's jigsaw studio, importers and + * exporters read the resources it registers as the same classes. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; @@ -47,6 +51,7 @@ public final class StructureModule implements IrisModule { setup.stages().define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE, IrisStages.Floating.OBJECTS) .reach(StructureModule::reach).run(StructureModule::place); var registry = setup.registry(); + StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerSettings(StructureSettings.class, StructurePlacementSettings.class); } diff --git a/src/main/java/art/arcane/iris/engine/object/KeyedResource.java b/src/main/java/art/arcane/iris/engine/object/KeyedResource.java new file mode 100644 index 000000000..b42699e90 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/KeyedResource.java @@ -0,0 +1,41 @@ +/* + * 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.object; + +/** + * A resource of Iris's pack object model read from one file of a pack. Iris sets its key, the file's path below the + * folder without {@code .json}, when it reads the file; the folder and type name are what studio and load reports show. + */ +public abstract class KeyedResource { + private transient String loadKey; + + public String getLoadKey() { + return loadKey; + } + + public void setLoadKey(String loadKey) { + this.loadKey = loadKey; + } + + /** The folder below the pack root that holds resources of this type. */ + public abstract String getFolderName(); + + /** The name studio and load reports give a resource of this type, such as {@code Structure}. */ + public abstract String getTypeName(); +} 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 new file mode 100644 index 000000000..a1e726548 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -0,0 +1,139 @@ +/* + * 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.engine.object.KeyedResource; +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.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 KeyedResource { + @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; + } + + @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 new file mode 100644 index 000000000..dc99b49cc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java @@ -0,0 +1,96 @@ +/* + * 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 new file mode 100644 index 000000000..b123f3a0f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java @@ -0,0 +1,94 @@ +/* + * 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.KeyedResource; +import com.volmit.object.GeneratedObject; +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 KeyedResource { + @Desc("Optional author-facing name shown by Jigsaw Studio. The resource key is shown when this is blank.") + private String displayName = ""; + + @Required + @RegistryListResource(GeneratedObject.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 new file mode 100644 index 000000000..c022d4de8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java @@ -0,0 +1,66 @@ +/* + * 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 new file mode 100644 index 000000000..bc66b71b2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java @@ -0,0 +1,63 @@ +/* + * 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.KeyedResource; +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 KeyedResource { + @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 new file mode 100644 index 000000000..e998e142e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java @@ -0,0 +1,40 @@ +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 new file mode 100644 index 000000000..4275be726 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java @@ -0,0 +1,88 @@ +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/value/IrisDirection.java b/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java new file mode 100644 index 000000000..07cd1b927 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/object/value/IrisDirection.java @@ -0,0 +1,87 @@ +/* + * 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; + +/** One of the six axis directions, named by its axis and sign as packs write it. */ +@Desc("A direction object") +public enum IrisDirection { + @Desc("0, 1, 0") + UP_POSITIVE_Y(0, 1, 0), + @Desc("0, -1, 0") + DOWN_NEGATIVE_Y(0, -1, 0), + @Desc("0, 0, -1") + NORTH_NEGATIVE_Z(0, 0, -1), + @Desc("0, 0, 1") + SOUTH_POSITIVE_Z(0, 0, 1), + @Desc("1, 0, 0") + EAST_POSITIVE_X(1, 0, 0), + @Desc("-1, 0, 0") + WEST_NEGATIVE_X(-1, 0, 0); + + private final int x; + private final int y; + private final int z; + + IrisDirection(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + @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 this == DOWN_NEGATIVE_Y || this == UP_POSITIVE_Y; + } + + public IrisDirection reverse() { + return switch (this) { + case DOWN_NEGATIVE_Y -> UP_POSITIVE_Y; + case EAST_POSITIVE_X -> WEST_NEGATIVE_X; + case NORTH_NEGATIVE_Z -> SOUTH_POSITIVE_Z; + case SOUTH_POSITIVE_Z -> NORTH_NEGATIVE_Z; + case UP_POSITIVE_Y -> DOWN_NEGATIVE_Y; + case WEST_NEGATIVE_X -> EAST_POSITIVE_X; + }; + } + + public int x() { + return x; + } + + public int y() { + return y; + } + + public int z() { + return z; + } +} From 1582a2126f4388c6749e52af66fd15b9399bd6e6 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 27 Oct 2026 01:43:53 +0100 Subject: [PATCH 108/139] Make object placements plain iris:objects settings ObjectPlacement is the one placement type: accessors for every option, a builder for placements made in code (build() copies, so later builder changes never reach a built placement) and toBuilder() copies that keep the source JSON and Iris's cached form. ObjectRotation carries the full rotation logic, ScaleInterpolation replaces Iris's scale interpolator, and the modules no longer register held types. --- README.md | 24 +- .../iris/builtin/objects/ObjectPlacement.java | 453 ++++++++++++++++-- .../iris/builtin/prepare/ObjectRotation.java | 189 +++++++- .../arcane/iris/engine/loot/LootModule.java | 4 - .../engine/object/placement/BlocksModule.java | 2 - .../object/placement/PrepareModule.java | 4 - .../engine/object/placement/StiltModule.java | 1 - .../engine/object/placement/VacuumModule.java | 1 - .../object/placement/ValidateModule.java | 2 - .../IrisObjectPlacementScaleInterpolator.java | 33 -- .../arcane/iris/engine/spawn/SpawnModule.java | 2 - 11 files changed, 614 insertions(+), 101 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java diff --git a/README.md b/README.md index 8f1513f25..1404c8a15 100644 --- a/README.md +++ b/README.md @@ -62,9 +62,8 @@ stilt, `VacuumProfile`, `PlaceTrait`s) that the placement stages ask; the pack J objects are trees) and says which biomes and regions place an object (`ObjectLocating`, for the object search). `iris:objects` ships in the built-ins jar. It declares the settings `objects` (region, biome: the list of `ObjectPlacement`s), `proceduralObjects` (region, biome), `treeSettings` (dimension), `requireObjectSurfaceSupport`, `objectSurfaceSupportBuffer`, -`upperDimensionObjects` and `upperObjectsForcePlace` (dimension), all written as they always were. `ObjectPlacement` describes -the same JSON as Iris's `IrisObjectPlacement` and keeps the JSON it was read from, because Iris's placement stages still read -a placement as their own class (`ObjectPlacements.host`). What a jar cannot do, Iris does through the facades `ObjectHost` and +`upperDimensionObjects` and `upperObjectsForcePlace` (dimension), all written as they always were. `ObjectPlacement` is the +placement itself, read by the module decoder like any settings class, and the one type Iris places with. What a jar cannot do, Iris does through the facades `ObjectHost` and `ObjectChunk` in `art.arcane.iris.builtin.objects`: loading and scaling the pack's objects, placing one with the placement stages into the chunk's mantle (on the surface, in a cave inside the cave's bounds, or hung from the terrain above), reading the carved space the cave carver planned, and the loot an object placed at a block defines; the layout, the settings of a column and @@ -94,13 +93,13 @@ only: `DepositSettings` (`art.arcane.iris.modules.deposit`) holds `DepositGenera palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. The deposits run one generator after the other, each with a random of its own; they used to spread over threads on a multicore pregen, which no module can do (stages run on the host's threads). -Settings that live inside a class of Iris's own, such as an object placement's clamp, stilt, vacuum and edit settings, its slope condition -or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, -`.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`). A module registers each with -`registry.registerHeldType(...)` so studio describes it from the module's own annotations. A module in the built-ins jar may -too, because the classes are in the exposed package: the placement stages register what Iris's `IrisObjectPlacement` holds -(`iris:prepare` its slope clip and rotation clamp, `iris:validate` its limit, `iris:stilt`, `iris:vacuum`, `iris:blocks` its -replace). Packs write the same JSON as before. Behaviour +An object placement is `iris:objects` settings (`objects.ObjectPlacement`, under a biome's or region's `objects`), and the +settings inside it, such as its clamp, stilt, vacuum and edit settings, its slope condition or a procedural coral, are +module-owned classes too (`art.arcane.iris.builtin.validate`, `.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, +`.floating`, `.objects.*`), so studio describes them from the module's own annotations. Iris reads a placement's module +settings (the keys pack modules add at `Level.PLACEMENT`) from the JSON the placement was written as (`json()`), and keeps +what it makes of the placement in `hostForm()`; a placement made in code uses `ObjectPlacement.builder()` or +`toBuilder()`. Packs write the same JSON as before. Behaviour that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`). @@ -210,11 +209,10 @@ IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), had, so existing worlds generate the same; `spawn.SpawnCooldowns` (the spawner cooldowns Iris saves with the world's data, so they survive a restart), `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and -marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`, which the modules -register as held types, because Iris's `IrisObjectPlacement` holds them). The placement stages need more of the object being +marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`). The placement stages need more of the object being placed than IrisApi describes, so `placement.ObjectPlacement` is the facade Iris implements for each placement and offers with its invocation (`context.extension(ObjectPlacement.class)`): the object's size (`ObjectShape`), the placement's settings (`PlacementSettings`, read from -Iris's `IrisObjectPlacement`), the terrain questions of its placer and the world around it (`PlacementTerrain`), the surface warp, +the `objects.ObjectPlacement` being placed), the terrain questions of its placer and the world around it (`PlacementTerrain`), the surface warp, and the block operations only the platform can do (turning a state with the object, merging two states, matching, traits of the placement's own states). Its types answer with IrisApi, VolmLib and built-in values only. `prepare.PreparedPlacement`, the output of `iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index faf5429a6..f012c04ad 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -185,9 +185,93 @@ public final class ObjectPlacement implements PlacementSource { public ObjectPlacement() { } + private ObjectPlacement(ObjectPlacement source) { + place = source.place; + rotation = source.rotation; + clamp = source.clamp; + snow = source.snow; + isDolphinTarget = source.isDolphinTarget; + slopeCondition = source.slopeCondition; + rotateTowardsSlope = source.rotateTowardsSlope; + chance = source.chance; + density = source.density; + densityStyle = source.densityStyle; + stiltSettings = source.stiltSettings; + vacuumSettings = source.vacuumSettings; + boreExtendMaxY = source.boreExtendMaxY; + markers = source.markers; + boreExtendMinY = source.boreExtendMinY; + underwater = source.underwater; + carvingSupport = source.carvingSupport; + surfaceSupportBuffer = source.surfaceSupportBuffer; + surfaceSupportDepth = source.surfaceSupportDepth; + requireSurfaceSupport = source.requireSurfaceSupport; + caveAnchorMode = source.caveAnchorMode; + heightmap = source.heightmap; + smartBore = source.smartBore; + waterloggable = source.waterloggable; + onwater = source.onwater; + meld = source.meld; + fromBottom = source.fromBottom; + bottom = source.bottom; + bore = source.bore; + warp = source.warp; + mode = source.mode; + edit = source.edit; + translate = source.translate; + scale = source.scale; + loot = source.loot; + vanillaLoot = source.vanillaLoot; + overrideGlobalLoot = source.overrideGlobalLoot; + trees = source.trees; + allowedCollisions = source.allowedCollisions; + forbiddenCollisions = source.forbiddenCollisions; + forcePlace = source.forcePlace; + json = source.json; + hostForm = source.hostForm; + } + + /** A builder of a placement made in code, starting from the defaults a pack's placement starts from. */ + public static Builder builder() { + return new Builder(new ObjectPlacement()); + } + + /** + * A builder of a copy of this placement with some options changed. The copy keeps the JSON this placement was + * read from, so the module settings it declares, and what Iris made of it, unless a noise option changes. + */ + public Builder toBuilder() { + return new Builder(new ObjectPlacement(this)); + } + /** The objects to pick from, by the keys of the pack's objects. */ public List place() { - return place == null ? List.of() : Collections.unmodifiableList(place); + return listOf(place); + } + + public ObjectRotation rotation() { + return rotation; + } + + public ObjectLimit clamp() { + return clamp; + } + + public double snow() { + return snow; + } + + @Override + public boolean isDolphinTarget() { + return isDolphinTarget; + } + + public SlopeClip slopeCondition() { + return slopeCondition; + } + + public boolean rotateTowardsSlope() { + return rotateTowardsSlope; } @Override @@ -212,16 +296,86 @@ public final class ObjectPlacement implements PlacementSource { return (int) ((densityStyle.max() + densityStyle.min()) / 2); } - public ObjectRotation rotation() { - return rotation; + public Optional stiltSettings() { + return Optional.ofNullable(stiltSettings); } - public ObjectTranslate translate() { - return translate; + public Optional vacuumSettings() { + return Optional.ofNullable(vacuumSettings); } - public ObjectScale scale() { - return scale; + public int boreExtendMaxY() { + return boreExtendMaxY; + } + + public List markers() { + return listOf(markers); + } + + public int boreExtendMinY() { + return boreExtendMinY; + } + + @Override + public boolean underwater() { + return underwater; + } + + @Override + public CarvingMode carvingSupport() { + return carvingSupport; + } + + @Override + public int surfaceSupportBuffer() { + return surfaceSupportBuffer; + } + + public int surfaceSupportDepth() { + return surfaceSupportDepth; + } + + @Override + public boolean requireSurfaceSupport() { + return requireSurfaceSupport; + } + + @Override + public CaveAnchorMode caveAnchorMode() { + return caveAnchorMode; + } + + /** The virtual heightmap the objects place on instead of the terrain, if one is set. */ + public Optional heightmap() { + return Optional.ofNullable(heightmap); + } + + public boolean smartBore() { + return smartBore; + } + + public boolean waterloggable() { + return waterloggable; + } + + public boolean onwater() { + return onwater; + } + + public boolean meld() { + return meld; + } + + public boolean fromBottom() { + return fromBottom; + } + + public boolean bottom() { + return bottom; + } + + public boolean bore() { + return bore; } public NoiseStyle warp() { @@ -233,55 +387,58 @@ public final class ObjectPlacement implements PlacementSource { return mode; } - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); + public List edit() { + return listOf(edit); } - @Override - public CarvingMode carvingSupport() { - return carvingSupport; + public ObjectTranslate translate() { + return translate; } - @Override - public CaveAnchorMode caveAnchorMode() { - return caveAnchorMode; + public ObjectScale scale() { + return scale; } - @Override - public boolean underwater() { - return underwater; + public List loot() { + return listOf(loot); } - @Override - public boolean isDolphinTarget() { - return isDolphinTarget; + public List vanillaLoot() { + return listOf(vanillaLoot); + } + + public boolean overrideGlobalLoot() { + return overrideGlobalLoot; + } + + public List trees() { + return listOf(trees); + } + + /** Whether one of the trees this placement overrides is the species {@code species} grown on a sapling area of {@code width} by {@code depth}. */ + public boolean overridesTree(int width, int depth, String species) { + return trees().stream().anyMatch(tree -> tree.matches(width, depth, species)); + } + + public List allowedCollisions() { + return listOf(allowedCollisions); + } + + public List forbiddenCollisions() { + return listOf(forbiddenCollisions); } public boolean forcePlace() { return forcePlace; } - @Override - public boolean requireSurfaceSupport() { - return requireSurfaceSupport; - } - - @Override - public int surfaceSupportBuffer() { - return surfaceSupportBuffer; - } - - public List trees() { - return trees == null ? List.of() : Collections.unmodifiableList(trees); - } - - /** The JSON this placement was read from, which Iris reads again as its own placement; null for one made in code. */ + /** The JSON this placement was read from, which declares its module settings; null for one made in code. */ public String json() { return json; } /** - * What Iris made of {@link #json()} the last time it asked, kept here so it asks once. Only Iris sets or reads it, + * What Iris made of this placement the last time it asked, kept here so it asks once. Only Iris sets or reads it, * and it is its own type. */ public Object hostForm() { @@ -292,6 +449,228 @@ public final class ObjectPlacement implements PlacementSource { this.hostForm = form; } + private static List listOf(List values) { + return values == null ? List.of() : Collections.unmodifiableList(values); + } + + /** Sets the options of a placement made in code; each setter returns the builder. */ + public static final class Builder { + private final ObjectPlacement placement; + + private Builder(ObjectPlacement placement) { + this.placement = placement; + } + + public Builder place(List keys) { + placement.place = List.copyOf(keys); + return this; + } + + public Builder rotation(ObjectRotation rotation) { + placement.rotation = rotation; + return this; + } + + public Builder clamp(ObjectLimit clamp) { + placement.clamp = clamp; + return this; + } + + public Builder snow(double snow) { + placement.snow = snow; + return this; + } + + public Builder slopeCondition(SlopeClip slopeCondition) { + placement.slopeCondition = slopeCondition; + return this; + } + + public Builder rotateTowardsSlope(boolean rotateTowardsSlope) { + placement.rotateTowardsSlope = rotateTowardsSlope; + return this; + } + + public Builder chance(double chance) { + placement.chance = chance; + return this; + } + + public Builder density(int density) { + placement.density = density; + return this; + } + + public Builder densityStyle(StyledRange densityStyle) { + placement.densityStyle = densityStyle; + placement.hostForm = null; + return this; + } + + public Builder stiltSettings(StiltSettings stiltSettings) { + placement.stiltSettings = stiltSettings; + return this; + } + + public Builder vacuumSettings(VacuumSettings vacuumSettings) { + placement.vacuumSettings = vacuumSettings; + return this; + } + + public Builder boreExtendMaxY(int blocks) { + placement.boreExtendMaxY = blocks; + return this; + } + + public Builder markers(List markers) { + placement.markers = List.copyOf(markers); + return this; + } + + public Builder boreExtendMinY(int blocks) { + placement.boreExtendMinY = blocks; + return this; + } + + public Builder underwater(boolean underwater) { + placement.underwater = underwater; + return this; + } + + public Builder carvingSupport(CarvingMode carvingSupport) { + placement.carvingSupport = carvingSupport; + return this; + } + + public Builder surfaceSupportBuffer(int blocks) { + placement.surfaceSupportBuffer = blocks; + return this; + } + + public Builder surfaceSupportDepth(int blocks) { + placement.surfaceSupportDepth = blocks; + return this; + } + + public Builder requireSurfaceSupport(boolean require) { + placement.requireSurfaceSupport = require; + return this; + } + + public Builder caveAnchorMode(CaveAnchorMode caveAnchorMode) { + placement.caveAnchorMode = caveAnchorMode; + return this; + } + + public Builder heightmap(HeightmapNoise heightmap) { + placement.heightmap = heightmap; + placement.hostForm = null; + return this; + } + + public Builder smartBore(boolean smartBore) { + placement.smartBore = smartBore; + return this; + } + + public Builder waterloggable(boolean waterloggable) { + placement.waterloggable = waterloggable; + return this; + } + + public Builder onwater(boolean onwater) { + placement.onwater = onwater; + return this; + } + + public Builder meld(boolean meld) { + placement.meld = meld; + return this; + } + + public Builder fromBottom(boolean fromBottom) { + placement.fromBottom = fromBottom; + return this; + } + + public Builder bottom(boolean bottom) { + placement.bottom = bottom; + return this; + } + + public Builder bore(boolean bore) { + placement.bore = bore; + return this; + } + + public Builder warp(NoiseStyle warp) { + placement.warp = warp; + placement.hostForm = null; + return this; + } + + public Builder mode(ObjectPlaceMode mode) { + placement.mode = mode; + return this; + } + + public Builder edit(List edit) { + placement.edit = List.copyOf(edit); + return this; + } + + public Builder translate(ObjectTranslate translate) { + placement.translate = translate; + return this; + } + + public Builder scale(ObjectScale scale) { + placement.scale = scale; + return this; + } + + public Builder loot(List loot) { + placement.loot = List.copyOf(loot); + return this; + } + + public Builder vanillaLoot(List vanillaLoot) { + placement.vanillaLoot = List.copyOf(vanillaLoot); + return this; + } + + public Builder overrideGlobalLoot(boolean override) { + placement.overrideGlobalLoot = override; + return this; + } + + public Builder trees(List trees) { + placement.trees = List.copyOf(trees); + return this; + } + + public Builder allowedCollisions(List keys) { + placement.allowedCollisions = List.copyOf(keys); + return this; + } + + public Builder forbiddenCollisions(List keys) { + placement.forbiddenCollisions = List.copyOf(keys); + return this; + } + + public Builder forcePlace(boolean forcePlace) { + placement.forcePlace = forcePlace; + return this; + } + + /** The placement; the builder must not be used after. */ + /** The placement as set so far; later changes to the builder do not reach it. */ + public ObjectPlacement build() { + return new ObjectPlacement(placement); + } + } + /** Reads a placement like any settings and keeps the JSON it was read from. */ public static final class KeepingItsJson implements TypeAdapterFactory { @Override diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java index 8cde2c559..9e3c51289 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java @@ -18,14 +18,25 @@ package art.arcane.iris.builtin.prepare; +import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.volmlib.util.math.IrisBlockVector; import com.volmit.config.Desc; import com.volmit.config.Snippet; -/** How an object is turned around each axis, written as a placement's {@code rotation}. */ +import java.util.Objects; + +/** + * How an object is turned around each axis, written as a placement's {@code rotation}. Positions turn around X, then Z, + * then Y; an axis locked to a multiple of a quarter turn swaps coordinates exactly instead of turning by an angle. + */ @Snippet("object-rotator") @Desc("Configures rotation for iris") public final class ObjectRotation { private static final double QUARTER_TURN_DEGREES = 90; + private static final double HALF_TURN_DEGREES = 180; + private static final double THREE_QUARTER_TURN_DEGREES = 270; + private static final double FULL_TURN_DEGREES = 360; @Desc("If this rotator is enabled or not") private boolean enabled = true; @@ -42,7 +53,7 @@ public final class ObjectRotation { public ObjectRotation() { } - /** A rotation with the given axes, as Iris's own rotation model hands them to the placement stages. */ + /** A rotation with the given axes. */ public static ObjectRotation of(boolean enabled, AxisRotationClamp xAxis, AxisRotationClamp yAxis, AxisRotationClamp zAxis) { ObjectRotation rotation = new ObjectRotation(); rotation.enabled = enabled; @@ -52,6 +63,34 @@ public final class ObjectRotation { return rotation; } + /** A rotation locked to the given angles, in degrees; enabled only when one of them is not 0. */ + public static ObjectRotation of(double x, double y, double z) { + return of(x != 0 || y != 0 || z != 0, + AxisRotationClamp.locked(x != 0, x, QUARTER_TURN_DEGREES), + AxisRotationClamp.locked(y != 0, y, QUARTER_TURN_DEGREES), + AxisRotationClamp.locked(z != 0, z, QUARTER_TURN_DEGREES)); + } + + /** Upside down: half a turn around X and no turn around Y or Z. */ + public static ObjectRotation xFlip180() { + return of(true, AxisRotationClamp.locked(true, HALF_TURN_DEGREES, 0), new AxisRotationClamp(), new AxisRotationClamp()); + } + + /** Upside down, then a random quarter turn around Y. */ + public static ObjectRotation xFlip180RandomY() { + return xFlip180().withYAxis(AxisRotationClamp.of(true, false, 0, 0, QUARTER_TURN_DEGREES)); + } + + /** Upside down, then {@code y} degrees around Y. */ + public static ObjectRotation xFlip180WithY(double y) { + return xFlip180().withYAxis(AxisRotationClamp.locked(true, y, QUARTER_TURN_DEGREES)); + } + + /** This rotation with {@code axis} around Y. */ + public ObjectRotation withYAxis(AxisRotationClamp axis) { + return of(enabled, xAxis, axis, zAxis); + } + public boolean enabled() { return enabled; } @@ -91,4 +130,150 @@ public final class ObjectRotation { } return axis.getRadians(spin); } + + public double xRadians(int spin) { + return radians(xAxis, spin); + } + + public double yRadians(int spin) { + return radians(yAxis, spin); + } + + public double zRadians(int spin) { + return radians(zAxis, spin); + } + + public IrisBlockVector rotate(IrisBlockVector position) { + return rotate(position, 0, 0, 0); + } + + public IrisPosition rotate(IrisPosition position) { + return rotate(position, 0, 0, 0); + } + + public IrisPosition rotate(IrisPosition position, int spinX, int spinY, int spinZ) { + IrisBlockVector turned = rotate(new IrisBlockVector(position.getX(), position.getY(), position.getZ()), spinX, spinY, spinZ); + return new IrisPosition(turned.getBlockX(), turned.getBlockY(), turned.getBlockZ()); + } + + /** The direction closest to {@code direction} turned by this rotation. */ + public IrisDirection rotate(IrisDirection direction) { + IrisBlockVector turned = rotate(new IrisBlockVector(direction.x(), direction.y(), direction.z())); + double closestDistance = Double.MAX_VALUE; + IrisDirection closest = null; + for (IrisDirection candidate : IrisDirection.values()) { + double distance = new IrisBlockVector(candidate.x(), candidate.y(), candidate.z()).distance(turned); + if (distance < closestDistance) { + closestDistance = distance; + closest = candidate; + } + } + return closest; + } + + /** {@code position} turned around X, then Z, then Y, each by the angle {@code spin} picks for it; a copy unless nothing turns. */ + public IrisBlockVector rotate(IrisBlockVector position, int spinX, int spinY, int spinZ) { + if (!canRotate()) { + return position; + } + IrisBlockVector turned = position.clone(); + if (canRotateX()) { + turnAroundX(turned, spinX); + } + if (canRotateZ()) { + turnAroundZ(turned, spinZ); + } + if (canRotateY()) { + turnAroundY(turned, spinY); + } + return turned; + } + + private void turnAroundX(IrisBlockVector v, int spin) { + if (!xAxis.isLocked()) { + v.rotateAroundX(xRadians(spin)); + return; + } + double angle = xAxis.max(); + if (Math.abs(angle) % FULL_TURN_DEGREES == HALF_TURN_DEGREES) { + v.setZ(-v.getZ()); + v.setY(-v.getY()); + } else if (isQuarterTurn(angle)) { + double z = v.getZ(); + v.setZ(v.getY()); + v.setY(-z); + } else if (isThreeQuarterTurn(angle)) { + double z = v.getZ(); + v.setZ(-v.getY()); + v.setY(z); + } else { + v.rotateAroundX(xRadians(spin)); + } + } + + private void turnAroundZ(IrisBlockVector v, int spin) { + if (!zAxis.isLocked()) { + v.rotateAroundZ(zRadians(spin)); + return; + } + double angle = zAxis.max(); + if (Math.abs(angle) % FULL_TURN_DEGREES == HALF_TURN_DEGREES) { + v.setY(-v.getY()); + v.setX(-v.getX()); + } else if (isQuarterTurn(angle)) { + double y = v.getY(); + v.setY(v.getX()); + v.setX(-y); + } else if (isThreeQuarterTurn(angle)) { + double y = v.getY(); + v.setY(-v.getX()); + v.setX(y); + } else { + v.rotateAroundZ(zRadians(spin)); + } + } + + private void turnAroundY(IrisBlockVector v, int spin) { + if (!yAxis.isLocked()) { + v.rotateAroundY(yRadians(spin)); + return; + } + double angle = yAxis.max(); + if (Math.abs(angle) % FULL_TURN_DEGREES == HALF_TURN_DEGREES) { + v.setX(-v.getX()); + v.setZ(-v.getZ()); + } else if (isQuarterTurn(angle)) { + double x = v.getX(); + v.setX(v.getZ()); + v.setZ(-x); + } else if (isThreeQuarterTurn(angle)) { + double x = v.getX(); + v.setX(-v.getZ()); + v.setZ(x); + } else { + v.rotateAroundY(yRadians(spin)); + } + } + + private static boolean isQuarterTurn(double angle) { + return angle % FULL_TURN_DEGREES == QUARTER_TURN_DEGREES || angle % FULL_TURN_DEGREES == -THREE_QUARTER_TURN_DEGREES; + } + + private static boolean isThreeQuarterTurn(double angle) { + return angle == -QUARTER_TURN_DEGREES || angle % FULL_TURN_DEGREES == THREE_QUARTER_TURN_DEGREES; + } + + @Override + public boolean equals(Object other) { + return other instanceof ObjectRotation rotation + && enabled == rotation.enabled + && Objects.equals(xAxis, rotation.xAxis) + && Objects.equals(yAxis, rotation.yAxis) + && Objects.equals(zAxis, rotation.zAxis); + } + + @Override + public int hashCode() { + return Objects.hash(enabled, xAxis, yAxis, zAxis); + } } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index 3da073e4d..4e4b10285 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -20,8 +20,6 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.modules.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootSettings; -import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.builtin.loot.ObjectVanillaLoot; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; @@ -46,8 +44,6 @@ public final class LootModule implements IrisModule { public void setup(ModuleSetup setup) { var registry = setup.registry(); registry.registerSettings(LootSettings.class, BlockDropSettings.class); - registry.registerHeldType(ObjectLoot.class); - registry.registerHeldType(ObjectVanillaLoot.class); LootResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new LootValidator()); registry.registerService(Loot.class, new LootGiving()); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index efc33ebaa..29eb88f06 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.blocks.ObjectMarkers; -import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.placement.MarkerRule; @@ -87,7 +86,6 @@ public final class BlocksModule implements IrisModule { .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.MARKERS) .run(context -> { }); - setup.registry().registerHeldType(ObjectReplace.class); } private static void write(BlockStageContext context, WrittenBlocks written) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index 3479bfc8a..d5df41e61 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -31,7 +31,6 @@ import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectSpinKernel; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.prepare.PreparedPlacement; -import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; @@ -66,9 +65,6 @@ public final class PrepareModule implements IrisModule { graph.define(IrisStages.Prepare.TRANSFORMS) .requires(IrisStages.Prepare.SLOPE) .produce(PrepareModule::transforms); - var registry = setup.registry(); - registry.registerHeldType(SlopeClip.class); - registry.registerHeldType(AxisRotationClamp.class); } private static ObjectRotation slope(PlacementStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index a1ee111bd..5ef55b48c 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -79,7 +79,6 @@ public final class StiltModule implements IrisModule { graph.define(IrisStages.Stilt.FILL) .requires(IrisStages.Stilt.LAYERS, IrisStages.Anchor.FINAL, IrisStages.Blocks.COMPLETE) .run(StiltModule::fill); - setup.registry().registerHeldType(StiltSettings.class); } private static void collectLayer(BlockStageContext context, StiltLayers layers) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index 9627612ba..f263a2ae9 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -61,7 +61,6 @@ public final class VacuumModule implements IrisModule { .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) .reach(IrisObjectVacuum.MAX_RADIUS_BLOCKS) .run(VacuumModule::bendTerrain); - setup.registry().registerHeldType(VacuumSettings.class); } private static void bendTerrain(PlacementStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index a8e8d03cd..487e21d8f 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -29,7 +29,6 @@ import art.arcane.iris.builtin.placement.PlacementTerrain; import art.arcane.iris.builtin.placement.StructureVolumes; import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.terrain.BedrockSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; @@ -75,7 +74,6 @@ public final class ValidateModule implements IrisModule { graph.define(IrisStages.Validate.COLLISIONS) .requires(IrisStages.Validate.STRUCTURES, IrisStages.Anchor.HEIGHT) .run(ValidateModule::checkCollisions); - setup.registry().registerHeldType(ObjectLimit.class); } private static void checkSurface(PlacementStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java b/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java deleted file mode 100644 index 4df6edd8a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/prefab/IrisObjectPlacementScaleInterpolator.java +++ /dev/null @@ -1,33 +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; - -@Desc("Use 3D Interpolation on scaled objects if they are larger than the origin.") -public enum IrisObjectPlacementScaleInterpolator { - @Desc("Don't interpolate, big cubes") - NONE, - @Desc("Uses linear interpolation in 3 dimensions, generally pretty good, but slow") - TRILINEAR, - @Desc("Uses cubic spline interpolation in 3 dimensions, even better, but extreme slowdowns") - TRICUBIC, - @Desc("Uses hermite spline interpolation in 3 dimensions, even better, but extreme slowdowns") - TRIHERMITE -} diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index 78f805d35..791a3ae65 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.modules.spawn.EffectSettings; -import art.arcane.iris.builtin.spawn.PlacementMarker; import art.arcane.iris.modules.spawn.SpawnerSettings; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -46,7 +45,6 @@ public final class SpawnModule implements IrisModule { public void setup(ModuleSetup setup) { var registry = setup.registry(); registry.registerSettings(SpawnerSettings.class, EffectSettings.class); - registry.registerHeldType(PlacementMarker.class); SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); registry.registerService(AmbientEffects.class, new AmbientEffecting()); From a13593f16e0867593533501334bd941b1b9ee2ec Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 01:25:45 +0100 Subject: [PATCH 109/139] Batch 7 stage 3: object placing runs on the api The object, floating and tree placers place through PackWorld.placements() with their own ObjectRun input instead of ObjectHost. ObjectHost, ObjectChunk, ObjectSink, the builtin PlaceableObject and the ObjectPlacement facade are gone; objects come from PackResources.objects(), and Iris's chunk random, density and heightmap noise from the LegacyStreams extension. Placement stage constants move to modules.placement.PlacementStages, and smart bore debugging is the dimension setting iris:blocks/debug-smart-bore. EdgeSimplex is a copy of Iris's 2D simplex, pinned against it in Iris. Structure loot reads the structure's tables through StructureHost until stage 4 moves the structures. --- builtin-modules.txt | 3 + .../arcane/iris/builtin/IrisSeedPurposes.java | 2 + .../art/arcane/iris/builtin/IrisStages.java | 98 +------ .../arcane/iris/builtin/LegacyStreams.java | 38 +++ .../iris/builtin/blocks/ObjectMarkers.java | 15 +- .../iris/builtin/floating/FloatingHost.java | 34 +-- .../iris/builtin/objects/CarvedSpace.java | 33 --- .../iris/builtin/objects/ObjectChunk.java | 56 ---- .../iris/builtin/objects/ObjectHost.java | 104 -------- .../iris/builtin/objects/ObjectRun.java | 218 ++++++++++++++++ .../iris/builtin/objects/ObjectSink.java | 34 --- .../iris/builtin/objects/PlaceableObject.java | 34 --- .../art/arcane/iris/builtin/package-info.java | 9 +- .../iris/builtin/placement/CaveSpace.java | 23 -- .../builtin/placement/ObjectPlacement.java | 94 ------- .../iris/builtin/placement/ObjectShape.java | 47 ---- .../builtin/placement/PlacementSettings.java | 96 ------- .../builtin/placement/PlacementTerrain.java | 68 ----- .../iris/builtin/placement/PlaneNoise.java | 24 -- .../iris/builtin/structure/StructureHost.java | 6 + .../arcane/iris/engine/loot/LootGiving.java | 5 +- .../iris/engine/loot/PlacedObjectLoot.java | 106 ++++++++ .../engine/mantle/components/CaveAnchors.java | 4 +- .../engine/mantle/components/CaveRejects.java | 9 +- .../mantle/components/ChunkObjectPlacing.java | 87 +++---- .../components/EffectivePlacements.java | 8 +- .../components/FloatingObjectPlacing.java | 46 ++-- .../mantle/components/FloatingPlacer.java | 243 ++++++++++++++++++ .../mantle/components/GoldenDebugTerrain.java | 99 +++++++ .../engine/mantle/components/IslandFace.java | 2 +- .../engine/mantle/components/ObjectChunk.java | 171 ++++++++++++ .../mantle/components/ObjectLocating.java | 5 +- .../mantle/components/ObjectModule.java | 3 +- .../mantle/components/ObjectPlacing.java | 29 +-- .../mantle/components/ObjectWarmUp.java | 23 +- .../mantle/components/PlacementReach.java | 28 +- .../engine/mantle/components/TreeGrowing.java | 103 ++++++-- .../engine/object/placement/AnchorModule.java | 42 +-- .../engine/object/placement/BlocksModule.java | 48 ++-- .../engine/object/placement/BoreModule.java | 18 +- .../object/placement/IrisSurfaceSupport.java | 8 +- .../engine/object/placement/ObjectEdits.java | 8 +- .../object/placement/PlacementWorld.java | 2 +- .../object/placement/PrepareModule.java | 36 +-- .../engine/object/placement/SnowModule.java | 14 +- .../engine/object/placement/StiltModule.java | 30 +-- .../engine/object/placement/VacuumModule.java | 28 +- .../object/placement/ValidateModule.java | 76 +++--- .../engine/object/placement/WorldVolume.java | 8 +- .../procedural/IrisProceduralBlocks.java | 2 +- .../procedural/ResolvedProceduralObjects.java | 29 +-- .../ResolvedProceduralPlacement.java | 18 +- .../procedural/coral/CoralGenerator.java | 2 +- .../procedural/coral/ResolvedCoral.java | 8 +- .../procedural/crystal/CrystalGenerator.java | 2 +- .../procedural/crystal/ResolvedCrystal.java | 8 +- .../formation/FormationBlockResolver.java | 2 +- .../formation/FormationGenerator.java | 2 +- .../formation/ResolvedFormation.java | 8 +- .../procedural/fungi/FungusGenerator.java | 2 +- .../procedural/fungi/ResolvedFungus.java | 10 +- .../object/procedural/ruin/ResolvedRuin.java | 8 +- .../procedural/ruin/RuinDecoratorApplier.java | 2 +- .../object/procedural/ruin/RuinGenerator.java | 2 +- .../tree/ProceduralTreeGenerator.java | 2 +- .../object/procedural/tree/ResolvedTree.java | 10 +- .../procedural/tree/TreeBlockResolver.java | 2 +- .../procedural/tree/TreePlausibility.java | 2 +- .../terrain/floating/FloatingWorld.java | 12 +- .../blocks/SmartBoreDebugSettings.java} | 25 +- .../floating/IslandAnchor.java | 2 +- .../floating/IslandFootprint.java | 2 +- .../iris/modules/objects/CarvedSpace.java | 114 ++++++++ .../objects/CavePlacement.java | 18 +- .../iris/modules/objects/CaveTransaction.java | 86 +++++++ .../{builtin => modules}/objects/Cavern.java | 2 +- .../iris/modules/objects/Declaration.java | 53 ++++ .../modules/objects/EffectiveSettings.java | 101 ++++++++ .../modules/objects/ForwardingTerrain.java | 106 ++++++++ .../objects/ObjectBuilder.java | 38 ++- .../iris/modules/objects/ObjectPool.java | 136 ++++++++++ .../objects/ObjectSize.java | 2 +- .../objects/PlacementChanges.java | 2 +- .../objects/PlacementTags.java | 2 +- .../objects/ProceduralPlacement.java | 4 +- .../modules/objects/TerrainTransaction.java | 161 ++++++++++++ .../placement/BlockTraits.java | 17 +- .../iris/modules/placement/EdgeSimplex.java | 86 +++++++ .../placement/MarkerRule.java | 26 +- .../iris/modules/placement/ObjectShape.java | 73 ++++++ .../modules/placement/PlacementSettings.java | 169 ++++++++++++ .../modules/placement/PlacementStages.java | 121 +++++++++ .../placement}/PreparedPlacement.java | 31 ++- .../modules/placement/RunningPlacement.java | 185 +++++++++++++ .../iris/modules/placement/StageTerrain.java | 132 ++++++++++ .../placement/SurfaceSupportOffsets.java | 113 ++++++++ .../placement/SurfaceWarp.java | 17 +- 97 files changed, 3087 insertions(+), 1195 deletions(-) create mode 100644 src/main/java/art/arcane/iris/builtin/LegacyStreams.java delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java create mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java delete mode 100644 src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java delete mode 100644 src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java delete mode 100644 src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java delete mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java delete mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java delete mode 100644 src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java create mode 100644 src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java rename src/main/java/art/arcane/iris/{builtin/placement/StructureVolumes.java => modules/blocks/SmartBoreDebugSettings.java} (53%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/IslandAnchor.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/IslandFootprint.java (97%) create mode 100644 src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java rename src/main/java/art/arcane/iris/{builtin => modules}/objects/CavePlacement.java (66%) create mode 100644 src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java rename src/main/java/art/arcane/iris/{builtin => modules}/objects/Cavern.java (96%) create mode 100644 src/main/java/art/arcane/iris/modules/objects/Declaration.java create mode 100644 src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java create mode 100644 src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ObjectBuilder.java (51%) create mode 100644 src/main/java/art/arcane/iris/modules/objects/ObjectPool.java rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ObjectSize.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/PlacementChanges.java (98%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/PlacementTags.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ProceduralPlacement.java (95%) create mode 100644 src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java rename src/main/java/art/arcane/iris/{builtin => modules}/placement/BlockTraits.java (80%) create mode 100644 src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java rename src/main/java/art/arcane/iris/{builtin => modules}/placement/MarkerRule.java (60%) create mode 100644 src/main/java/art/arcane/iris/modules/placement/ObjectShape.java create mode 100644 src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java create mode 100644 src/main/java/art/arcane/iris/modules/placement/PlacementStages.java rename src/main/java/art/arcane/iris/{builtin/prepare => modules/placement}/PreparedPlacement.java (84%) create mode 100644 src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java create mode 100644 src/main/java/art/arcane/iris/modules/placement/StageTerrain.java create mode 100644 src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java rename src/main/java/art/arcane/iris/{builtin => modules}/placement/SurfaceWarp.java (64%) diff --git a/builtin-modules.txt b/builtin-modules.txt index 76a7b50f2..9d5af6cac 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -86,11 +86,14 @@ include art/arcane/iris/engine/mantle/components/PlacementReach*.class include art/arcane/iris/engine/mantle/components/ObjectWarmUp*.class include art/arcane/iris/engine/mantle/components/ObjectLocating*.class include art/arcane/iris/engine/mantle/components/TreeGrowing*.class +include art/arcane/iris/engine/mantle/components/ObjectChunk*.class +include art/arcane/iris/engine/mantle/components/GoldenDebugTerrain*.class include art/arcane/iris/engine/object/procedural/** module art.arcane.iris.engine.modifier.FloatingModule include art/arcane/iris/engine/modifier/FloatingIslands*.class include art/arcane/iris/engine/object/terrain/floating/** include art/arcane/iris/engine/mantle/components/FloatingObjectPlacing*.class +include art/arcane/iris/engine/mantle/components/FloatingPlacer*.class include art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver*.class include art/arcane/iris/engine/mantle/components/IslandFace*.class include art/arcane/iris/engine/mantle/components/UndersideTurn*.class diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java index eb048f802..c292be806 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java @@ -36,6 +36,8 @@ public final class IrisSeedPurposes { public static final ResourceId ENTITY = purpose("entity"); public static final ResourceId LOOT = purpose("loot"); public static final ResourceId MANTLE = purpose("mantle"); + /** The noise that warps the columns of object placements with a surface warp. */ + public static final ResourceId OBJECT_WARP = purpose("object-warp"); public static final ResourceId POST = purpose("post"); public static final ResourceId TERRAIN = purpose("terrain"); diff --git a/src/main/java/art/arcane/iris/builtin/IrisStages.java b/src/main/java/art/arcane/iris/builtin/IrisStages.java index 16810ab3f..725fbb028 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisStages.java +++ b/src/main/java/art/arcane/iris/builtin/IrisStages.java @@ -18,111 +18,19 @@ package art.arcane.iris.builtin; -import art.arcane.iris.builtin.anchor.AnchorHeight; -import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.PreparedPlacement; -import art.arcane.iris.builtin.stilt.StiltLayers; -import com.volmit.stage.BlockStage; import com.volmit.stage.ChunkStage; import com.volmit.stage.MantleStage; -import com.volmit.stage.PlacementStage; import com.volmit.stage.Stage; /** - * Every stage of Iris's built-in modules, one nested class per module. Modules are listed in the order their - * pipelines run them: placement, then mantle, then chunk; a module with stages in several pipelines is listed - * where its first stage runs. The stage graph decides the actual order. + * The mantle and chunk stages of Iris's built-in modules, one nested class per module, in the order their pipelines + * run them: mantle, then chunk. The stage graph decides the actual order. The object placement stages are the + * placement modules' own. */ public final class IrisStages { private IrisStages() { } - /** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ - public static final class Prepare { - /** The rotation the placement uses: the requested one, turned downhill when the settings ask to face the slope. Rejects {@code slope}. */ - public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", ObjectRotation.class); - /** The random rotation, translation and height offset, chosen once per placement. */ - public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); - - private Prepare() { - } - } - - /** Module {@code iris:anchor}: the height an object is placed at. */ - public static final class Anchor { - /** The requested or sampled height the checks judge. Rejects {@code carving-anchor}. */ - public static final PlacementStage HEIGHT = Stage.placement("iris:anchor/height", AnchorHeight.class); - /** The height the object's blocks are written at: the checked height plus the random offset. */ - public static final PlacementStage FINAL = Stage.placement("iris:anchor/final", AnchorHeight.class); - - private Anchor() { - } - } - - /** Module {@code iris:validate}: the checks that reject a placement before anything is written, in this order. */ - public static final class Validate { - /** Rejects {@code bedrock-anchor} and {@code surface-support}. */ - public static final PlacementStage SURFACE = Stage.placement("iris:validate/surface"); - /** Rejects {@code underwater-anchor}, {@code cave-clearance}, {@code fluid-height} and {@code height-clamp}. */ - public static final PlacementStage LIMITS = Stage.placement("iris:validate/limits"); - /** Rejects {@code native-structure}, even for placements that force their way past the other checks. */ - public static final PlacementStage STRUCTURES = Stage.placement("iris:validate/structures"); - /** Rejects {@code object-collision}. */ - public static final PlacementStage COLLISIONS = Stage.placement("iris:validate/collisions"); - - private Validate() { - } - } - - /** Module {@code iris:bore}: clearing the object's volume before its blocks are written. */ - public static final class Bore { - public static final PlacementStage CLEAR = Stage.placement("iris:bore/clear"); - - private Bore() { - } - } - - /** Module {@code iris:blocks}: writing the object's blocks. */ - public static final class Blocks { - /** Writes each object block where the placement puts it. */ - public static final BlockStage WRITE = Stage.placementBlock("iris:blocks/write", WrittenBlocks.class); - /** Marks some written blocks with the placement's markers. */ - public static final PlacementStage MARKERS = Stage.placement("iris:blocks/markers"); - /** Milestone: stages requiring it run after the object and its markers are written. */ - public static final PlacementStage COMPLETE = Stage.placement("iris:blocks/complete"); - - private Blocks() { - } - } - - /** Module {@code iris:stilt}: the stilts of the stilt and ceiling placement modes. */ - public static final class Stilt { - /** Finds the layers to repeat. */ - public static final BlockStage LAYERS = Stage.placementBlock("iris:stilt/layers", StiltLayers.class); - /** Grows the stilt once the object is written. */ - public static final PlacementStage FILL = Stage.placement("iris:stilt/fill"); - - private Stilt() { - } - } - - /** Module {@code iris:vacuum}: bending the terrain to meet objects of the vacuum placement modes. */ - public static final class Vacuum { - public static final PlacementStage TERRAIN = Stage.placement("iris:vacuum/terrain"); - - private Vacuum() { - } - } - - /** Module {@code iris:snow}: snow on the object, after its stilt or terrain bend. */ - public static final class Snow { - public static final PlacementStage COVER = Stage.placement("iris:snow/cover"); - - private Snow() { - } - } - /** Module {@code iris:carve}: caves, planned in the mantle and cut into each chunk's terrain. */ public static final class Carve { /** Plans the caves of the dimension's cave profiles into the mantle, one block into each neighbor. */ diff --git a/src/main/java/art/arcane/iris/builtin/LegacyStreams.java b/src/main/java/art/arcane/iris/builtin/LegacyStreams.java new file mode 100644 index 000000000..e00716157 --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/LegacyStreams.java @@ -0,0 +1,38 @@ +/* + * 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.builtin; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.volmlib.util.math.RNG; + +/** + * The random streams and noise of Iris's own generators that decide where existing worlds have their objects, which no + * API noise reproduces: Iris's chunk random, and the noise of a placement's density style and virtual heightmap. Iris + * offers it as an extension of its worlds: {@code world.extension(LegacyStreams.class)}. + */ +public interface LegacyStreams { + /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ + RNG objectChunkRandom(int chunkX, int chunkZ); + + /** How many objects the placement places at the column: its fixed density, or what its density style gives there for {@code rng}. */ + int density(ObjectPlacement placement, RNG rng, double x, double z); + + /** The height the placement's virtual heightmap gives the column, its noise seeded with {@code seed}; for a placement with a heightmap. */ + int heightmapSurface(ObjectPlacement placement, long seed, int x, int z); +} diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java index 447f40726..7abc74a7a 100644 --- a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java +++ b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java @@ -25,16 +25,27 @@ import com.volmit.geometry.BlockPosition; import java.util.Map; /** - * Iris markers as IrisApi placement markers: type {@code iris:marker}, naming the pack's marker under the - * {@code marker} attribute. Iris stores markers of this type only. + * The placement markers Iris keeps: a pack marker, type {@code iris:marker}, naming the pack's marker under the + * {@code marker} attribute; a placed object's block that is a tree's ({@code iris:tree_material}), which Iris keeps + * as the block's tree material for felling and growth; and a buried treasure chest ({@code iris:buried_treasure}). */ public final class ObjectMarkers { public static final ResourceId TYPE = ResourceId.parse("iris:marker"); + public static final ResourceId TREE_MATERIAL = ResourceId.parse("iris:tree_material"); + public static final ResourceId BURIED_TREASURE = ResourceId.parse("iris:buried_treasure"); public static final String MARKER_ATTRIBUTE = "marker"; private ObjectMarkers() { } + public static PlacedMarker treeMaterial(BlockPosition position) { + return new PlacedMarker(position, TREE_MATERIAL, Map.of()); + } + + public static PlacedMarker buriedTreasure(BlockPosition position) { + return new PlacedMarker(position, BURIED_TREASURE, Map.of()); + } + /** {@code markerKey} is the pack's marker, such as {@code spawn/zombie}. */ public static PlacedMarker of(BlockPosition position, String markerKey) { return new PlacedMarker(position, TYPE, Map.of(MARKER_ATTRIBUTE, markerKey)); diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java index 82b806f69..314079b65 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java +++ b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java @@ -18,18 +18,12 @@ package art.arcane.iris.builtin.floating; -import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.volmlib.util.math.RNG; -import com.volmit.generation.InvocationContext; import com.volmit.resource.ResourceId; -import java.util.Optional; - /** - * What {@code iris:floating} asks of Iris beyond the API: a biome's own terrain height, the sky biome an island paints, - * and placing Iris objects against an island. Iris offers it as an extension of its worlds: - * {@code world.extension(FloatingHost.class)}. + * What {@code iris:floating} asks of Iris beyond the API: a biome's own terrain height and the sky biome an island + * paints. Iris offers it as an extension of its worlds: {@code world.extension(FloatingHost.class)}. */ public interface FloatingHost { /** The height the terrain generators of {@code biome} give the column, as Iris shapes the biome's terrain with {@code seed}. */ @@ -40,28 +34,4 @@ public interface FloatingHost { * pass finds it. {@code random} seeds the biome's generator the first time the biome is asked. */ void paintSkyBiome(ResourceId biome, int worldX, int worldZ, int[] ys, RNG random); - - /** Where {@code object} stands: its solid columns, its tallest column and that column's lowest solid block. */ - IslandFootprint footprint(PlaceableObject object); - - /** {@code object} shrunk by {@code factor} (below 1), the variant picked with {@code random}. */ - Optional shrink(PlaceableObject object, double factor, RNG random); - - /** Places {@code object} floating free at the column, into the chunk the mantle invocation {@code context} generates. */ - void placeFloating(InvocationContext context, PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, - RNG random); - - /** - * Places {@code object} on an island's top, its lowest block at {@code y}, into the chunk the mantle invocation - * {@code context} generates; nothing is written unless every block it writes is one {@code anchor} lets it write. - */ - void placeOnTop(InvocationContext context, PlaceableObject object, int worldX, int y, int worldZ, - ObjectPlacement placement, IslandAnchor anchor, RNG random); - - /** - * Places {@code object} upside down under an island, turned {@code yRotation} degrees about Y, as {@link #placeOnTop} does - * on top. - */ - void placeUnder(InvocationContext context, PlaceableObject object, int worldX, int y, int worldZ, int yRotation, - ObjectPlacement placement, IslandAnchor anchor, RNG random); } diff --git a/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java b/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java deleted file mode 100644 index 6ee201b23..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/CarvedSpace.java +++ /dev/null @@ -1,33 +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.builtin.objects; - -import java.util.Optional; - -/** The voids the cave carver planned in the mantle around the chunk being placed, which cave objects anchor in. */ -public interface CarvedSpace { - /** Whether the position is carved. */ - boolean isCarved(int x, int y, int z); - - /** Whether each height from 0 up to {@code height} is carved at the column, 1 for carved and 0 for not. */ - byte[] column(int x, int z, int height); - - /** The void at the position; empty where nothing was carved. */ - Optional cavernAt(int x, int y, int z); -} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java deleted file mode 100644 index 822163a0f..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectChunk.java +++ /dev/null @@ -1,56 +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.builtin.objects; - -import art.arcane.volmlib.util.math.RNG; - -/** - * The chunk whose mantle {@code iris:objects} is placing into: the one place objects are written. Every placement here - * runs Iris's placement stages, so it is what a pack's {@code objects} get when they are placed anywhere. Reached through - * {@link ObjectHost#chunk()} from a mantle stage. - */ -public interface ObjectChunk { - /** The voids the cave carver planned around the chunk. */ - CarvedSpace carved(); - - /** Whether the golden-debug switch is on for the chunk, which logs every decision of its placements. */ - boolean goldenDebug(int chunkX, int chunkZ); - - /** - * Places an object on the terrain, where it sits at the height its place mode finds. - * - * @param goldenTag logs the placer's questions under this tag, or null to leave them - * @return the height the object was placed at, negative when the placement rejected it - */ - int placeOnSurface(PlaceableObject object, int x, int z, PlacementSource placement, PlacementChanges changes, - PlacementTags tags, RNG rng, String goldenTag); - - /** - * Places an object in a cave, anchored at {@code anchorY}, and writes it only when all of it lies inside the cave and - * no deeper than {@code minDepthBelowSurface} under the surface. - * - * @param goldenTag logs the placer's questions under this tag, or null to leave them - */ - CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, PlacementSource placement, PlacementChanges changes, - int minDepthBelowSurface, PlacementTags tags, RNG rng, String goldenTag); - - /** Places an object at a given height, which the terrain stacked above uses for the objects hung from it. */ - int placeUpper(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, - PlacementTags tags, RNG rng); -} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.java deleted file mode 100644 index e8c09d44f..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectHost.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.builtin.objects; - -import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.builtin.loot.ObjectVanillaLoot; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.IrisFeature; -import com.volmit.config.Level; -import com.volmit.generation.InvocationContext; -import com.volmit.resource.ResourceId; - -import java.util.List; -import java.util.Optional; - -/** - * What {@code iris:objects} asks of Iris's object system: the pack's objects, how Iris scales, picks and places them, and - * the loot of what it placed. The layout, settings and seeds around an object are the API's. Iris offers it as an - * extension of its worlds and of the settings of the pack it loads: {@code world.extension(ObjectHost.class)}, - * {@code settings.extension(ObjectHost.class)}. - * - *

Objects are named by the keys placements hold ({@link ObjectPlacement#place()}). The randoms are VolmLib's - * {@link RNG}, since the streams Iris draws objects with decide where existing worlds have them. - */ -public interface ObjectHost { - /** Whether Iris's debug setting is on, which makes object placing trace what it does. */ - boolean debugging(); - - /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ - RNG chunkRandom(int chunkX, int chunkZ); - - /** The chunk whose objects the mantle invocation {@code context} places. */ - ObjectChunk chunk(InvocationContext context); - - /** The object of the pack that {@code key} names. */ - Optional object(String key); - - /** An object of the placement, picked with {@code rng} and scaled the way the placement scales it; empty when it has none. */ - Optional pickScaled(ObjectPlacement placement, RNG rng); - - /** How many objects the placement places at the column, when its chance check passes. */ - int density(ObjectPlacement placement, RNG rng, double x, double z); - - /** The size of the pack's object, read without loading its blocks; empty when the pack has no such object. */ - Optional sizeOf(String objectKey); - - /** Builds what placing the placement would build on first use, so the first chunk to place it does not wait. */ - void warm(ObjectPlacement placement, RNG rng); - - /** A builder for one bake of objects made block by block. */ - ObjectBuilder builder(); - - /** Places the object into {@code sink}, which is outside any chunk's generation, such as a growing sapling's tree. */ - int placeInto(PlaceableObject object, int x, int y, int z, ObjectPlacement placement, ObjectSink sink, RNG rng); - - /** The loot of the object placed at the block; empty when no object placement covers the block. */ - Optional placedLoot(int x, int y, int z); - - /** - * Every region and every reachable biome that declares the settings, regions first. Unlike the sources of - * {@link com.volmit.config.PackSettings#declared}, which name the resource that declares them, each is named by the - * id a {@link com.volmit.world.BiomeSample} gives it. - */ - List> declarations(Class type); - - /** One region's or biome's declaration of settings, by the id of the region or biome. */ - record Declaration(Level level, ResourceId id, F settings) { - } - - /** - * The loot an object placement gives its containers. - * - * @param packTables tables of the pack - * @param platformTables tables of the platform - * @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes - */ - record ObjectLoots(List packTables, List platformTables, boolean overridesGlobalLoot) { - public ObjectLoots { - packTables = List.copyOf(packTables); - platformTables = List.copyOf(platformTables); - } - - /** Whether the placement names any table. */ - public boolean defined() { - return !packTables.isEmpty() || !platformTables.isEmpty(); - } - } -} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java new file mode 100644 index 000000000..1ee0350bd --- /dev/null +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java @@ -0,0 +1,218 @@ +/* + * 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.builtin.objects; + +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.noise.NoiseStyle; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacementOutcome; +import com.volmit.placement.PlacementRequest; +import com.volmit.placement.PlacementRun; +import com.volmit.placement.PlacementTerrain; +import com.volmit.world.PackWorld; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalInt; + +/** + * One object placed through the pack's placement stages with an object placement's settings: the input Iris's built-in + * placement stages read ({@link PlacementRun#input}), and what they report back, the height the object was anchored at + * and which of the written blocks are the object's own. Made for one placement; not thread-safe. + */ +public final class ObjectRun { + private static final int NOT_ANCHORED = Integer.MIN_VALUE; + private static final int NEIGHBOR_READ_BLOCKS = 1; + private static final long X_MULTIPLIER = 0x9E3779B97F4A7C15L; + private static final long Z_MULTIPLIER = 0xC2B2AE3D27D4EB4FL; + private static final long Y_MULTIPLIER = 0x165667B19E3779F9L; + private static final long FNV_OFFSET_BASIS = 0xCBF29CE484222325L; + private static final long FNV_PRIME = 0x100000001B3L; + + private PlaceableObject object; + private final ObjectPlacement settings; + private final int x; + private final int requestedY; + private final int z; + private final Cave cave; + private final List objectBlocks = new ArrayList<>(); + private int anchorY = NOT_ANCHORED; + + private ObjectRun(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z, Cave cave) { + this.object = Objects.requireNonNull(object, "object"); + this.settings = Objects.requireNonNull(settings, "settings"); + this.x = x; + this.requestedY = requestedY; + this.z = z; + this.cave = cave; + } + + /** @param requestedY the height to place at, or a negative value for the stages to sample it */ + public static ObjectRun of(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z) { + return new ObjectRun(object, settings, x, requestedY, z, null); + } + + /** A placement inside {@code cave}, which the stages anchor in and keep the object's height within. */ + public static ObjectRun inCave(PlaceableObject object, ObjectPlacement settings, int x, int requestedY, int z, Cave cave) { + return new ObjectRun(object, settings, x, requestedY, z, Objects.requireNonNull(cave, "cave")); + } + + /** + * The cave an object is placed in. + * + * @param surface the height of its floor + * @param height how many blocks high it is + */ + public record Cave(int surface, int height) { + } + + /** Places the object into {@code terrain} through the pack's placement stages of {@code world} ({@link #toRun}). */ + public PlacementOutcome placeIn(PackWorld world, PlacementTerrain terrain) { + return world.placements().place(toRun(terrain, world)); + } + + /** + * The run of this placement in {@code terrain}. Its seed comes from the world's seed and the placement's identity, the + * object's name and requested position, so the same placement draws the same in every run. Its area is every column + * the object reaches in any rotation around its anchor, moved by its translation and surface warp, and one block more + * for neighbor reads. A placement that smart bores bores its object first, so the stages see the bored air. + */ + public PlacementRun toRun(PlacementTerrain terrain, PackWorld world) { + return toRun(terrain, world.seed(), world.resources().objects()); + } + + /** As {@link #toRun(PlacementTerrain, PackWorld)}, for a world of seed {@code worldSeed} whose pack's objects are {@code objects}. */ + public PlacementRun toRun(PlacementTerrain terrain, long worldSeed, PackObjects objects) { + if (settings.smartBore()) { + object = objects.smartBored(object); + } + PlacementRequest request = new PlacementRequest(object.geometry(), new BlockPosition(x, requestedY, z)); + return new PlacementRun(request, area(), terrain, this, placementSeed(worldSeed)); + } + + public PlaceableObject object() { + return object; + } + + /** The settings as the caller passed them; the stages derive what they change, such as the rotation, themselves. */ + public ObjectPlacement settings() { + return settings; + } + + public int x() { + return x; + } + + /** The height the caller asked for, negative when the stages sample it. */ + public int requestedY() { + return requestedY; + } + + public int z() { + return z; + } + + /** The cave the object is placed in; empty outside caves. */ + public Optional cave() { + return Optional.ofNullable(cave); + } + + /** Reports the height the object was anchored at. */ + public void anchoredAt(int y) { + anchorY = y; + } + + /** The height the object was anchored at; empty until a stage anchors it. */ + public OptionalInt anchorY() { + return anchorY == NOT_ANCHORED ? OptionalInt.empty() : OptionalInt.of(anchorY); + } + + /** Reports a written block as one of the object's own, as opposed to boring, stilts, snow or a terrain bend. */ + public void objectBlockWritten(BlockPosition position) { + objectBlocks.add(position); + } + + /** The object's own blocks the stages wrote, in the order they wrote them; they reach the world only if it is placed. */ + public List objectBlocks() { + return Collections.unmodifiableList(objectBlocks); + } + + private BlockBox area() { + int objectRadius = Math.max(rotationRadius(object.geometry().bounds()), rotationRadius(declaredBox())); + int reach = objectRadius + translationLength(settings.translate()) + warpMargin(settings.warp()) + NEIGHBOR_READ_BLOCKS; + return new BlockBox(x - reach, Integer.MIN_VALUE, z - reach, x + reach + 1, Integer.MAX_VALUE, z + reach + 1); + } + + /** The object's declared size around its center, which its block offsets count from. */ + private BlockBox declaredBox() { + BlockPosition center = object.center(); + return new BlockBox(-center.x(), -center.y(), -center.z(), Math.max(1, object.width()) - center.x(), + Math.max(1, object.height()) - center.y(), Math.max(1, object.depth()) - center.z()); + } + + /** The farthest any block of {@code bounds} lies from the origin, which rotations turn around. */ + private static int rotationRadius(BlockBox bounds) { + long farthestX = farthest(bounds.minX(), bounds.maxX()); + long farthestY = farthest(bounds.minY(), bounds.maxY()); + long farthestZ = farthest(bounds.minZ(), bounds.maxZ()); + return (int) Math.ceil(Math.sqrt(farthestX * farthestX + farthestY * farthestY + farthestZ * farthestZ)); + } + + private static long farthest(int min, int maxExclusive) { + return Math.max(Math.abs((long) min), Math.abs((long) maxExclusive - 1)); + } + + private static int translationLength(ObjectTranslate translate) { + long translateX = translate.x(); + long translateY = translate.y(); + long translateZ = translate.z(); + return (int) Math.ceil(Math.sqrt(translateX * translateX + translateY * translateY + translateZ * translateZ)); + } + + private static int warpMargin(NoiseStyle warp) { + return warps(warp) ? (int) Math.ceil(Math.abs(warp.multiplier()) / 2D) : 0; + } + + /** + * Whether {@code warp} moves the placement's columns: any base style but {@link NoiseStyle#FLAT}. Unlike + * {@link NoiseStyle#isFlat()}, a flat style with an expression still does not warp, as Iris always read it. + */ + public static boolean warps(NoiseStyle warp) { + return !NoiseStyle.FLAT.equals(warp.style()); + } + + private long placementSeed(long worldSeed) { + return worldSeed ^ fnv1a(object.name()) ^ (x * X_MULTIPLIER) ^ (requestedY * Y_MULTIPLIER) ^ (z * Z_MULTIPLIER); + } + + private static long fnv1a(String text) { + long hash = FNV_OFFSET_BASIS; + for (byte value : text.getBytes(StandardCharsets.UTF_8)) { + hash = (hash ^ (value & 0xFF)) * FNV_PRIME; + } + return hash; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java deleted file mode 100644 index 777ef63e4..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectSink.java +++ /dev/null @@ -1,34 +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.builtin.objects; - -import com.volmit.block.BlockState; - -/** Where an object placed through {@link ObjectHost#placeInto} reads the world around it and writes its blocks. */ -public interface ObjectSink { - /** The height of the highest block at the column; {@code ignoreFluid} leaves out the fluid above the ground. */ - int highest(int x, int z, boolean ignoreFluid); - - BlockState get(int x, int y, int z); - - void set(int x, int y, int z, BlockState state); - - /** The height of the dimension's fluid. */ - int fluidHeight(); -} diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java b/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java deleted file mode 100644 index 8aafb4eab..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/PlaceableObject.java +++ /dev/null @@ -1,34 +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.builtin.objects; - -/** An object of the pack, or one made for a placement, that {@link ObjectHost} can place; Iris's own object class is one. */ -public interface PlaceableObject { - /** The key the pack loads the object by, or the key a procedural object is given; null for an object made in code. */ - String key(); - - /** How wide the object is, in blocks. */ - int width(); - - /** How tall the object is, in blocks. */ - int height(); - - /** How deep the object is, in blocks. */ - int depth(); -} diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index ca33b5443..5a6a97740 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -30,13 +30,12 @@ *

* Besides those, it holds what Iris and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.spawn.SpawnCooldowns}, {@link art.arcane.iris.builtin.objects.ObjectHost}), and the seed purposes Iris + * ({@link art.arcane.iris.builtin.spawn.SpawnCooldowns}, {@link art.arcane.iris.builtin.LegacyStreams}), and the seed purposes Iris * answers with its legacy seeds ({@link art.arcane.iris.builtin.IrisSeedPurposes}). Keep them few: each is * a promise. *

- * The placement stages ({@code iris:prepare} to {@code iris:snow}) reach the object being placed through - * {@link art.arcane.iris.builtin.placement.ObjectPlacement}, a facade Iris implements for each placement. Its types - * answer with IrisApi, VolmLib and built-in values only, and the stages' outputs ({@link art.arcane.iris.builtin.prepare.PreparedPlacement}) - * are built-in types too, so a pack module can require a placement stage and read what it chose. + * The placement stages ({@code iris:prepare} to {@code iris:snow}) run in the pack's placement graph, which + * {@code PackWorld.placements()} runs. They read the object and its settings from the run's input, + * {@link art.arcane.iris.builtin.objects.ObjectRun}, which Iris also builds when it places an object itself. */ package art.arcane.iris.builtin; diff --git a/src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java b/src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java deleted file mode 100644 index c03884dfa..000000000 --- a/src/main/java/art/arcane/iris/builtin/placement/CaveSpace.java +++ /dev/null @@ -1,23 +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.builtin.placement; - -/** The cave an object is placed in: the height of its floor and how many blocks it is high. */ -public record CaveSpace(int surface, int height) { -} diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java deleted file mode 100644 index 950ad0013..000000000 --- a/src/main/java/art/arcane/iris/builtin/placement/ObjectPlacement.java +++ /dev/null @@ -1,94 +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.builtin.placement; - -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.block.BlockState; -import com.volmit.block.BlockTrait; -import com.volmit.resource.PackResources; -import com.volmit.geometry.BlockPosition; - -import java.util.Optional; - -/** - * The object placement being run, as Iris's built-in placement stages see it: what is placed and with which settings, the - * terrain it is placed on, and the few block operations that only the platform can do. Iris implements it for each - * placement and offers it as an extension of the placement invocation: {@code context.extension(ObjectPlacement.class)}. - * Heights are in the coordinates of the placement stages: above the dimension's bottom. - *

- * It never hands out an engine, pack data or a platform type; everything it answers is an IrisApi, VolmLib or - * {@code art.arcane.iris.builtin} value. - */ -public interface ObjectPlacement { - ObjectShape object(); - - /** The settings as the caller passed them; the stages derive what they change (the rotation) themselves. */ - PlacementSettings settings(); - - int x(); - - /** The height the caller asked for, negative when the placement samples it. */ - int requestedY(); - - int z(); - - /** The cave the object is placed in; empty outside caves. */ - Optional cave(); - - /** Answers the questions of the terrain the placement was asked to place on. */ - PlacementTerrain terrain(); - - /** - * The terrain the placement anchors against: {@link #terrain()}, or, when the settings place on a heightmap, the same - * terrain with its heights from the heightmap's noise, seeded from {@code rng}. - */ - PlacementTerrain terrainFor(RNG rng); - - /** The noise that warps the placement's columns; empty when the settings do not warp. */ - Optional surfaceWarp(RNG rng); - - /** Iris's simplex noise of {@code seed}, whose signed reads fill -1 to 1. */ - PlaneNoise simplex(long seed); - - /** {@code state} turned with the object by {@code rotation}, as the platform turns stairs, logs and other facing blocks. */ - BlockState rotate(BlockState state, ObjectRotation rotation, int spinX, int spinY, int spinZ); - - /** {@code update} laid over {@code base}: the platform's merge of two states of one block, else {@code update}. */ - BlockState merge(BlockState base, BlockState update); - - /** Whether {@code state}, as the platform's own state, matches {@code other}: {@code state.matches(other)} of the platform. */ - boolean matches(BlockState state, BlockState other); - - /** - * Whether {@code state} has {@code trait}, as the platform's own state answers it. Unlike the block registry it keeps - * the identity of the states this placement handed out, so a content plugin's block, which shares its key with the - * block it is drawn as, answers as itself ({@link BlockTrait#CUSTOM}). - */ - boolean hasTrait(BlockState state, BlockTrait trait); - - /** The resources of the object's pack, where the placement's markers are found. */ - PackResources resources(); - - /** Reports a buffered write as one of the object's own blocks, which Iris's placement listener hears after the commit. */ - void objectBlockWritten(BlockPosition position); - - /** Reports the height the object was anchored at, which the placement returns to its caller. */ - void anchoredAt(int y); -} diff --git a/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java b/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java deleted file mode 100644 index 74f0bdb59..000000000 --- a/src/main/java/art/arcane/iris/builtin/placement/ObjectShape.java +++ /dev/null @@ -1,47 +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.builtin.placement; - -import art.arcane.volmlib.util.math.IrisBlockVector; -import com.volmit.resource.ResourceId; - -import java.util.List; -import java.util.Optional; - -/** The object being placed: its declared size, the block its offsets count from, and where it must stand on solid ground. */ -public interface ObjectShape { - int width(); - - int height(); - - int depth(); - - /** The block the object's offsets count from, relative to its corner. */ - int centerX(); - - int centerY(); - - int centerZ(); - - /** The pack object this is; empty for an object the pack does not name, such as a procedural variant. */ - Optional id(); - - /** The columns of the object's lowest solid layer, as offsets from its anchor before any transform; empty for the origin only. */ - List surfaceSupportOffsets(); -} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java deleted file mode 100644 index 198135b47..000000000 --- a/src/main/java/art/arcane/iris/builtin/placement/PlacementSettings.java +++ /dev/null @@ -1,96 +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.builtin.placement; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.prepare.SlopeClip; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.resource.ResourceId; - -import java.util.List; -import java.util.Optional; -import java.util.Set; - -/** The settings of one object placement, as the placement stages read them. */ -public interface PlacementSettings { - boolean forcePlace(); - - SlopeClip slopeCondition(); - - boolean rotateTowardsSlope(); - - ObjectRotation rotation(); - - ObjectTranslate translate(); - - ObjectPlaceMode mode(); - - boolean fromBottom(); - - /** Whether the object places from the ground up instead of by height checks. */ - boolean bottom(); - - CarvingMode carvingSupport(); - - boolean underwater(); - - boolean onwater(); - - boolean requireSurfaceSupport(); - - int surfaceSupportBuffer(); - - int surfaceSupportDepth(); - - ObjectLimit clamp(); - - /** Whether air is placed before the object. */ - boolean bore(); - - int boreExtendMinY(); - - int boreExtendMaxY(); - - List edit(); - - boolean waterloggable(); - - boolean meld(); - - List markers(); - - Optional stilt(); - - Optional vacuum(); - - /** The snow filter's depth, 0 for none. */ - double snow(); - - /** The pack objects the placement may overlap even when {@link #forbiddenCollisions()} names them. */ - Set allowedCollisions(); - - /** The pack objects the placement may not overlap. */ - Set forbiddenCollisions(); -} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java b/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java deleted file mode 100644 index c766a7104..000000000 --- a/src/main/java/art/arcane/iris/builtin/placement/PlacementTerrain.java +++ /dev/null @@ -1,68 +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.builtin.placement; - -import com.volmit.resource.ResourceId; - -import java.util.Optional; - -/** - * What a placement asks of the terrain and the world around it: heights, carving and water at a column, and the - * world's own facts. A placement made without a world ({@link #hasWorld()} is false) answers its terrain questions from - * the placer alone and the world's facts with nothing. - */ -public interface PlacementTerrain { - /** The surface height of the column, counting fluid unless {@code ignoreFluid}. */ - int highest(int x, int z, boolean ignoreFluid); - - boolean isCarved(int x, int y, int z); - - /** Whether the block is real, solid ground; the height field alone cannot say at mantle time. */ - boolean isSurfaceSolid(int x, int y, int z); - - boolean isUnderwater(int x, int z); - - /** The height up to which the dimension is filled with fluid. */ - int fluidHeight(); - - /** Whether leaves the placement writes never decay. */ - boolean preventsDecay(); - - /** Whether bored air is written as a visible block, to see where smart boring bored. */ - boolean debugsSmartBore(); - - boolean hasWorld(); - - /** The terrain's slope at the column, as the dimension's slope field gives it. */ - double slopeAt(int x, int z); - - /** The terrain height at a position between columns, as the dimension's height field gives it. */ - double heightAt(double x, double z); - - /** The platform's Y of the dimension's bottom block. */ - int minWorldY(); - - /** The dimension's height in blocks. */ - int worldHeight(); - - StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ); - - /** The pack object placed at the block; empty when none was. */ - Optional objectAt(int x, int y, int z); -} diff --git a/src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java b/src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java deleted file mode 100644 index b5b20a0c7..000000000 --- a/src/main/java/art/arcane/iris/builtin/placement/PlaneNoise.java +++ /dev/null @@ -1,24 +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.builtin.placement; - -/** Noise over a plane that swings between -1 and 1, such as the rolling wave of a terrain bend. */ -public interface PlaneNoise { - double signed(double x, double z); -} diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java index b2bd0d8fe..14dabfe37 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java @@ -19,6 +19,9 @@ package art.arcane.iris.builtin.structure; import com.volmit.generation.InvocationContext; +import java.util.List; +import java.util.Optional; + /** * What {@code iris:structure} asks of Iris: Iris places its jigsaw structures itself. The structure model (structures, * pools, pieces), the assembler that builds a structure from them and the locator that spreads them over the world are @@ -31,4 +34,7 @@ public interface StructureHost { /** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */ int reach(); + + /** The loot tables the structure gives its pieces' containers; empty when the pack has no such structure. */ + Optional> lootTables(String structureKey); } diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 9d2c266a3..e33a47d74 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -20,9 +20,8 @@ package art.arcane.iris.engine.loot; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.loot.LootResolver; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.ObjectHost.ObjectLoots; import art.arcane.iris.builtin.loot.LootTable; +import art.arcane.iris.engine.loot.PlacedObjectLoot.ObjectLoots; import art.arcane.volmlib.util.math.RNG; import com.volmit.item.ItemDrop; import com.volmit.resource.ResourceId; @@ -50,7 +49,7 @@ public final class LootGiving implements Loot { List sources = new ArrayList<>(); boolean objectLootDefined = site.nativeLootDefined(); Optional objectLoots = site.container().isEmpty() ? Optional.empty() - : world.extension(ObjectHost.class).orElseThrow().placedLoot(x, relativeY, z); + : PlacedObjectLoot.at(world, x, relativeY, z); if (objectLoots.isPresent()) { objectLootDefined = objectLootDefined || objectLoots.get().defined(); Source picked = placementLoot(world).pick(objectLoots.get().platformTables(), objectLoots.get().packTables(), diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java new file mode 100644 index 000000000..f73dadc74 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java @@ -0,0 +1,106 @@ +/* + * 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.loot; + +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.loot.ObjectVanillaLoot; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.builtin.structure.StructureHost; +import art.arcane.iris.builtin.structure.StructurePlacementMarker; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The loot of the object placed at a block, found from the placement the world recorded there: a structure piece gives + * its structure's tables; any other object the tables of the first placement of the column's region, then of its + * surface biome, that places it. Procedural objects give none. + */ +final class PlacedObjectLoot { + private static final String PROCEDURAL_PREFIX = "procedural/"; + private static final int STRUCTURE_TABLE_WEIGHT = 1; + + private PlacedObjectLoot() { + } + + /** + * The loot an object placement gives its containers. + * + * @param packTables tables of the pack + * @param platformTables tables of the platform + * @param overridesGlobalLoot whether the placement's tables replace those of the dimension, region and biomes + */ + record ObjectLoots(List packTables, List platformTables, boolean overridesGlobalLoot) { + ObjectLoots { + packTables = List.copyOf(packTables); + platformTables = List.copyOf(platformTables); + } + + /** Whether the placement names any table. */ + boolean defined() { + return !packTables.isEmpty() || !platformTables.isEmpty(); + } + } + + /** The loot of the object placed at the block; empty when no object placement covers the block. Y is above the dimension's bottom. */ + static Optional at(PackWorld world, int x, int y, int z) { + RunningWorld running = world.running().orElseThrow(); + Optional marker = running.placementAt(x, y, z).map(StructurePlacementMarker::decode); + if (marker.isEmpty() || marker.get().objectKey().startsWith(PROCEDURAL_PREFIX)) { + return Optional.empty(); + } + String objectKey = marker.get().objectKey(); + Optional placement = marker.get().structureAware() + ? structurePlacement(world, marker.get().structureKey(), objectKey) + : columnPlacement(running.settings().at(ObjectSettings.class, x, z), objectKey); + return placement.map(found -> new ObjectLoots(found.loot(), found.vanillaLoot(), found.overrideGlobalLoot())); + } + + /** A structure piece's object gives every table its structure names, each once. */ + private static Optional structurePlacement(PackWorld world, String structureKey, String objectKey) { + Optional> tables = world.extension(StructureHost.class).orElseThrow().lootTables(structureKey); + PackResources resources = world.resources(); + if (tables.isEmpty() || resources.objects().object(resources.idOf(objectKey)).isEmpty()) { + return Optional.empty(); + } + List loot = new ArrayList<>(); + for (String table : tables.get()) { + loot.add(new ObjectLoot(table, STRUCTURE_TABLE_WEIGHT)); + } + return Optional.of(ObjectPlacement.builder().place(List.of(objectKey)).loot(loot).build()); + } + + private static Optional columnPlacement(SettingsStack declared, String objectKey) { + Optional fromRegion = declared.level(Level.REGION).flatMap(settings -> placing(settings, objectKey)); + return fromRegion.isPresent() ? fromRegion : declared.level(Level.BIOME).flatMap(settings -> placing(settings, objectKey)); + } + + private static Optional placing(ObjectSettings settings, String objectKey) { + return settings.objects().stream() + .filter(placement -> placement.place().contains(objectKey)) + .findFirst(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java index e7444ceb9..6c78f1538 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java @@ -19,8 +19,8 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.objects.CarvedSpace; -import art.arcane.iris.builtin.objects.Cavern; +import art.arcane.iris.modules.objects.CarvedSpace; +import art.arcane.iris.modules.objects.Cavern; import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.math.RNG; import com.volmit.resource.ResourceId; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java index 0dd2f8ff6..cdfcc382b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveRejects.java @@ -18,9 +18,8 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.objects.PlaceableObject; +import com.volmit.object.PlaceableObject; import com.volmit.ModuleLog; import java.util.Map; @@ -36,13 +35,13 @@ final class CaveRejects { private CaveRejects() { } - static void log(ObjectHost host, ModuleLog log, String scope, String reason, int chunkX, int chunkZ, ObjectPlacement placement, + static void log(ModuleLog log, String scope, String reason, int chunkX, int chunkZ, ObjectPlacement placement, PlaceableObject object, int densityIndex, int density, CaveAnchors.Search search, Integer anchorY, Throwable error) { - if (!host.debugging()) { + if (!log.debugging()) { return; } String placementKeys = placement == null ? "none" : String.join(",", placement.place()); - String objectKey = object == null ? "null" : object.key(); + String objectKey = object == null ? "null" : object.name(); String throttleKey = scope + "|" + reason + "|" + placementKeys + "|" + objectKey; State state = STATES.computeIfAbsent(throttleKey, key -> new State()); long now = System.currentTimeMillis(); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 337d67dab..2628e6362 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -22,28 +22,29 @@ import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.objects.CavePlacement; -import art.arcane.iris.builtin.objects.ObjectChunk; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.PlaceableObject; -import art.arcane.iris.builtin.objects.PlacementChanges; import art.arcane.iris.builtin.objects.PlacementSource; -import art.arcane.iris.builtin.objects.PlacementTags; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.iris.modules.objects.CavePlacement; +import art.arcane.iris.modules.objects.TerrainTransaction; +import art.arcane.iris.modules.objects.EffectiveSettings; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.PlacementChanges; +import art.arcane.iris.modules.objects.PlacementTags; +import art.arcane.iris.modules.objects.ProceduralPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisFeature; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Level; import com.volmit.config.SettingsStack; +import com.volmit.object.PlaceableObject; import com.volmit.resource.ResourceId; import com.volmit.stage.MantleStageContext; import com.volmit.world.TerrainSampler; @@ -70,7 +71,7 @@ final class ChunkObjectPlacing { private static final String TREE_FOLDER = "trees/"; private static final String REGEN_THREAD_PREFIX = "Iris-Regen-"; - private final ObjectHost host; + private final ObjectPool objects; private final ModuleLog log; private final MantleStageContext context; private final ObjectChunk chunk; @@ -87,18 +88,18 @@ final class ChunkObjectPlacing { private final int worldHeight; private final int caveLavaHeight; - ChunkObjectPlacing(ObjectHost host, ModuleLog log, MantleStageContext context) { - this.host = host; + ChunkObjectPlacing(ObjectPool objects, EffectiveSettings settings, ModuleLog log, MantleStageContext context) { + this.objects = objects; this.log = log; this.context = context; - this.chunk = host.chunk(context); + this.chunk = new ObjectChunk(context, settings, log); this.terrain = context.terrain(); this.chunkX = context.chunkX(); this.chunkZ = context.chunkZ(); this.centerX = context.originX() + OBJECT_COLUMN_OFFSET_BLOCKS; this.centerZ = context.originZ() + OBJECT_COLUMN_OFFSET_BLOCKS; - this.rng = host.chunkRandom(chunkX, chunkZ); - this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && host.debugging(); + this.rng = objects.chunkRandom(chunkX, chunkZ); + this.traceRegen = Thread.currentThread().getName().startsWith(REGEN_THREAD_PREFIX) && log.debugging(); this.golden = chunk.goldenDebug(chunkX, chunkZ); this.worldHeight = context.mantle().bounds().maxY(); this.caveLavaHeight = Optional.ofNullable(dimensionLevel(CaveLavaHeightSettings.class)).orElseGet(CaveLavaHeightSettings::new).height(); @@ -109,7 +110,7 @@ final class ChunkObjectPlacing { /** Places what originates in this chunk. */ void place() { Column column = readColumn(); - if (host.debugging() && (chunkX & DIAGNOSTIC_CHUNK_MASK) == 0 && (chunkZ & DIAGNOSTIC_CHUNK_MASK) == 0) { + if (log.debugging() && (chunkX & DIAGNOSTIC_CHUNK_MASK) == 0 && (chunkZ & DIAGNOSTIC_CHUNK_MASK) == 0) { logCaveDiagnostics(column); } if (traceRegen) { @@ -286,10 +287,10 @@ final class ChunkObjectPlacing { private void placeObject(Tally tally, ObjectPlacement placement, String scope) { int blockX = context.originX(); int blockZ = context.originZ(); - int density = host.density(placement, rng, blockX, blockZ); + int density = objects.density(placement, rng, blockX, blockZ); for (int i = 0; i < density; i++) { tally.attempts++; - Optional picked = host.pickScaled(placement, rng); + Optional picked = objects.pickScaled(placement, rng); if (picked.isEmpty()) { tally.nullObjects++; traceNullObject(scope, i, density, placement); @@ -301,14 +302,14 @@ final class ChunkObjectPlacing { PlacementChanges changes = effective.forSurface(placement, object); boolean treePlacement = isTreePlacement(object, placement); int id = rng.i(0, Integer.MAX_VALUE); - String goldenTag = golden ? scope + "/" + object.key() : null; + String goldenTag = golden ? scope + "/" + object.name() : null; if (golden) { - log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " densityIndex=" + i + " xx=" + x + " zz=" + z + " mode=" + placement.mode()); } try { PlacementTags tags = tags(object, id, "surface", treePlacement, placement); - int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, rng, goldenTag); + int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, goldenTag); if (result >= 0) { tally.placed++; } else { @@ -317,7 +318,7 @@ final class ChunkObjectPlacing { traceObjectResult(scope, object, result, x, z, i, density); } catch (Throwable failure) { tally.errors++; - log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); } } @@ -327,22 +328,22 @@ final class ChunkObjectPlacing { ResourceId expectedCaveBiome, CaveAnchors anchors) { int minX = context.originX(); int minZ = context.originZ(); - int density = host.density(placement, rng, minX, minZ); + int density = objects.density(placement, rng, minX, minZ); CaveAnchors.Search search = caves.searchFor(placement, profile); for (int i = 0; i < density; i++) { tally.attempts++; - Optional picked = host.pickScaled(placement, rng); + Optional picked = objects.pickScaled(placement, rng); if (picked.isEmpty()) { tally.nullObjects++; traceNullObject(scope, i, density, placement); - CaveRejects.log(host, log, scope, "NULL_OBJECT", chunkX, chunkZ, placement, null, i, density, search, null, null); + CaveRejects.log(log,scope, "NULL_OBJECT", chunkX, chunkZ, placement, null, i, density, search, null, null); continue; } PlaceableObject object = picked.get(); CaveAnchors.Anchor anchor = anchors.find(rng, minX, minZ, search, expectedCaveBiome, placement.underwater()); if (anchor == null) { tally.rejected++; - CaveRejects.log(host, log, scope, "NO_ANCHOR", chunkX, chunkZ, placement, object, i, density, search, null, null); + CaveRejects.log(log,scope, "NO_ANCHOR", chunkX, chunkZ, placement, object, i, density, search, null, null); continue; } int id = rng.i(0, Integer.MAX_VALUE); @@ -350,13 +351,13 @@ final class ChunkObjectPlacing { try { PlacementTags tags = tags(object, id, "cave", isTreePlacement(object, placement), placement); CavePlacement contained = chunk.placeInCave(object, anchor.x(), anchor.y(), anchor.z(), placement, changes, - search.minDepthBelowSurface(), tags, rng, null); + search.minDepthBelowSurface(), tags, null); tallyCave(tally, contained, scope, object, placement, i, density, search, anchor); } catch (Throwable failure) { tally.errors++; - log.error("Regen cave object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + log.error("Regen cave object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); - CaveRejects.log(host, log, scope, "EXCEPTION", chunkX, chunkZ, placement, object, i, density, search, anchor.y(), failure); + CaveRejects.log(log,scope, "EXCEPTION", chunkX, chunkZ, placement, object, i, density, search, anchor.y(), failure); } } } @@ -367,10 +368,10 @@ final class ChunkObjectPlacing { tally.placed++; } else { tally.rejected++; - CaveRejects.log(host, log, scope, rejectReason(contained), chunkX, chunkZ, placement, object, index, density, search, anchor.y(), null); + CaveRejects.log(log,scope, rejectReason(contained), chunkX, chunkZ, placement, object, index, density, search, anchor.y(), null); } if (traceRegen) { - log.debug("Regen cave object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + log.debug("Regen cave object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " resultY=" + contained.resultY() + " anchorY=" + anchor.y() + " px=" + anchor.x() + " pz=" + anchor.z() + " wroteBlocks=" + contained.wroteBlocks() + " densityIndex=" + index + " density=" + density); } @@ -380,7 +381,7 @@ final class ChunkObjectPlacing { if (contained.resultY() < 0) { return "PLACE_NEGATIVE"; } - return contained.commit() == CavePlacement.Commit.REJECTED_BOUNDS ? "CONTAINMENT" : "NO_WRITES"; + return contained.commit() == TerrainTransaction.Commit.REJECTED ? "CONTAINMENT" : "NO_WRITES"; } private void placeProceduralObjects(Column column) { @@ -463,22 +464,22 @@ final class ChunkObjectPlacing { String commit = "n/a"; if (anchor != null) { PlacementChanges changes = effective.forCave(placement, variant, caveProfile); - CavePlacement contained = chunk.placeInCave(variant, x, anchor.y(), z, placement, changes, search.minDepthBelowSurface(), tags, rng, goldenTag); + CavePlacement contained = chunk.placeInCave(variant, x, anchor.y(), z, placement, changes, search.minDepthBelowSurface(), tags, goldenTag); resultY = contained.resultY(); commit = contained.commit().toString(); } else { - resultY = chunk.placeOnSurface(variant, x, z, placement, PlacementChanges.NONE, tags, rng, goldenTag); + resultY = chunk.placeOnSurface(variant, x, z, placement, PlacementChanges.NONE, tags, goldenTag); } if (golden) { log.debug("Goldendebug procedural result: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() - + " variant=" + variant.key() + " xx=" + x + " zz=" + z + " resultY=" + resultY + " commit=" + commit); + + " variant=" + variant.name() + " xx=" + x + " zz=" + z + " resultY=" + resultY + " commit=" + commit); } } private void logProceduralPick(ProceduralPlacement placement, PlaceableObject variant, int index, int x, int z, boolean carving) { List pool = placement.variants(); log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + index - + " variant=" + variant.key() + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() + " xx=" + x + " zz=" + z + + " variant=" + variant.name() + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() + " xx=" + x + " zz=" + z + " mode=" + placement.mode() + " carving=" + carving); } @@ -528,9 +529,9 @@ final class ChunkObjectPlacing { private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) { int minX = context.originX(); int minZ = context.originZ(); - int density = host.density(placement, rng, minX, minZ); + int density = objects.density(placement, rng, minX, minZ); for (int i = 0; i < density; i++) { - Optional picked = host.pickScaled(placement, rng); + Optional picked = objects.pickScaled(placement, rng); if (picked.isEmpty()) { continue; } @@ -546,16 +547,16 @@ final class ChunkObjectPlacing { continue; } int id = rng.i(0, Integer.MAX_VALUE); - PlacementChanges changes = PlacementChanges.NONE.withPlace(List.of(String.valueOf(object.key()))) + PlacementChanges changes = PlacementChanges.NONE.withPlace(List.of(String.valueOf(object.name()))) .withMode(ObjectPlaceMode.CENTER_HEIGHT) .withUpsideDown(true).withCarvingSupport(CarvingMode.ANYWHERE); if (forcePlace) { changes = changes.withForcePlace(true); } PlacementTags tags = tags(object, id, "upper", isTreePlacement(object, placement), placement); - int result = chunk.placeUpper(object, x, anchorY, z, placement, changes, tags, rng); + int result = chunk.placeUpper(object, x, anchorY, z, placement, changes, tags); if (traceRegen) { - log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + " anchorY=" + log.debug("Upper object placement: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " anchorY=" + anchorY + " upperSurfaceY=" + upperSurface.getAsInt() + " resultY=" + result + " forcePlace=" + forcePlace); } } @@ -570,7 +571,7 @@ final class ChunkObjectPlacing { } private String placementMarker(PlaceableObject object, int id, String context) { - String key = object == null ? null : object.key(); + String key = object == null ? null : object.name(); if (key == null || key.isEmpty() || key.equals("null")) { String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); log.warnOnce(fingerprint, "Skipping placement marker write: the object has no loadKey (context=" + context + "). " @@ -581,7 +582,7 @@ final class ChunkObjectPlacing { } private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) { - String key = object == null ? null : object.key(); + String key = object == null ? null : object.name(); return (key != null && key.startsWith(TREE_FOLDER)) || (placement != null && !placement.trees().isEmpty()); } @@ -603,11 +604,11 @@ final class ChunkObjectPlacing { private void traceObjectResult(String scope, PlaceableObject object, int result, int x, int z, int index, int density) { if (golden) { - log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + log.debug("Goldendebug object result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " resultY=" + result + " fallback=surface"); } if (traceRegen) { - log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.key() + log.debug("Regen object placement result: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + " resultY=" + result + " px=" + x + " pz=" + z + " fallback=surface densityIndex=" + index + " density=" + density); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java index 6979b60f1..3eb6ab4db 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -21,9 +21,9 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.objects.PlaceableObject; -import art.arcane.iris.builtin.objects.PlacementChanges; import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.modules.objects.PlacementChanges; +import com.volmit.object.PlaceableObject; import java.util.List; import java.util.Locale; @@ -56,14 +56,14 @@ final class EffectivePlacements { if (profileMode == null) { return changes; } - String key = object.key(); + String key = object.name(); List place = key == null || key.isBlank() ? List.of() : List.of(key); return changes.withPlace(place).withMode(profileMode); } /** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */ private static PlacementChanges withImportedMode(PlacementSource placement, PlaceableObject object, PlacementChanges changes) { - String key = object.key(); + String key = object.name(); if (key == null || key.isBlank() || !isImported(key)) { return changes; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 3ed1d5baa..a0e11901e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -21,13 +21,13 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.modules.floating.FloatingChildSettings; -import art.arcane.iris.builtin.floating.FloatingHost; -import art.arcane.iris.builtin.floating.IslandFootprint; -import art.arcane.iris.builtin.objects.ObjectHost; +import art.arcane.iris.modules.floating.IslandFootprint; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.ObjectSize; -import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ObjectSize; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandBoundarySampler; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.terrain.floating.FloatingWorld; @@ -72,15 +72,15 @@ public final class FloatingObjectPlacing { private static final String BIOME_PATH_PREFIX = "biome/"; private final FloatingWorld world; - private final FloatingHost host; - private final ObjectHost objects; + private final ObjectPool objects; + private final FloatingPlacer placer; private final long mantleSeed; private final ModuleLog log; - FloatingObjectPlacing(FloatingWorld world, long mantleSeed, ModuleLog log) { + FloatingObjectPlacing(FloatingWorld world, ObjectPool objects, FloatingPlacer placer, long mantleSeed, ModuleLog log) { this.world = world; - this.host = world.host(); - this.objects = world.objects(); + this.objects = objects; + this.placer = placer; this.mantleSeed = mantleSeed; this.log = log; } @@ -88,8 +88,8 @@ public final class FloatingObjectPlacing { /** The floating object placing of {@code world}. */ public static FloatingObjectPlacing of(PackWorld world, ModuleLog log) { return world.state(FloatingObjectPlacing.class, - generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), - generating.seed(IrisSeedPurposes.MANTLE), log)); + generating -> new FloatingObjectPlacing(FloatingWorld.of(generating), ObjectPool.of(generating), + new FloatingPlacer(generating, log), generating.seed(IrisSeedPurposes.MANTLE), log)); } /** Places what originates in the chunk of {@code context} into the mantle. */ @@ -206,7 +206,7 @@ public final class FloatingObjectPlacing { continue; } int key = columns.get(rng.i(columns.size())); - host.placeFloating(chunk.context, picked.get(),chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng); + placer.placeFloating(chunk.context, picked.get(), chunk.minX + (key & 15), chunk.minZ + (key >> 4), placement, rng); } } @@ -220,7 +220,7 @@ public final class FloatingObjectPlacing { continue; } PlaceableObject object = picked.get(); - IslandFootprint footprint = host.footprint(object); + IslandFootprint footprint = placer.footprint(object); KList pool = interior.isEmpty() ? columns : interior; int pickedKey = pool.get(rng.i(pool.size())); @@ -241,7 +241,7 @@ public final class FloatingObjectPlacing { int x = pickedX - footprint.tallestX(); int z = pickedZ - footprint.tallestZ(); int y = pickTopY + 1 - footprint.lowestSolidY(); - host.placeOnTop(chunk.context, object,x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng); + placer.placeOnTop(chunk.context, object, x, y, z, placement, IslandFace.top(chunk.resolver, entry, pickTopY, chunk.worldHeight), rng); } } @@ -255,7 +255,7 @@ public final class FloatingObjectPlacing { continue; } PlaceableObject object = picked.get(); - IslandFootprint footprint = host.footprint(object); + IslandFootprint footprint = placer.footprint(object); UndersideTurn turn = new UndersideTurn(rng.i(QUARTER_TURNS) * QUARTER_TURN_DEGREES); Optional anchor = pickBottomAnchor(chunk, footprint, turn, interior.isEmpty() ? columns : interior, entry); @@ -268,7 +268,7 @@ public final class FloatingObjectPlacing { int x = invertedBaseX(chunk.minX, pickedXf, footprint, turn); int z = invertedBaseZ(chunk.minZ, pickedZf, footprint, turn); int y = invertedBaseY(pickBottomY, footprint, turn); - host.placeUnder(chunk.context, object,x, y, z, turn.yRotation(), placement, + placer.placeUnder(chunk.context, object, x, y, z, turn.yRotation(), placement, IslandFace.bottom(chunk.resolver, entry, pickBottomY, chunk.worldHeight), rng); } } @@ -308,7 +308,7 @@ public final class FloatingObjectPlacing { if (scaled.isEmpty() || !entry.hasObjectShrink()) { return scaled; } - return host.shrink(scaled.get(), entry.shrinkFactor(), rng); + return Optional.of(objects.resized(scaled.get(), entry.shrinkFactor())); } static boolean isFootprintFlatBottom(IslandFootprint footprint, UndersideTurn turn, int pickedX, int pickedZ, int pickBottomY, @@ -388,7 +388,7 @@ public final class FloatingObjectPlacing { /** How far, in blocks along X and Z, the floating objects of the pack {@code settings} describe may write beyond their chunk. */ public static int reach(PackSettings settings, ModuleLog log) { - Reach reach = new Reach(settings.extension(ObjectHost.class).orElseThrow(), biomeObjectsOf(settings), log); + Reach reach = new Reach(settings.resources(), biomeObjectsOf(settings), log); int maxObjectExtent = MIN_REACH_BLOCKS; try { for (Entry declared : settings.declared(FloatingChildSettings.class)) { @@ -425,14 +425,14 @@ public final class FloatingObjectPlacing { /** The reach of floating children's objects, each object sized once. */ private static final class Reach { - private final ObjectHost objects; + private final PackResources resources; private final Map biomeObjects; private final ModuleLog log; private final Map> sizes = new HashMap<>(); private final Set warnedLargeObjects = new HashSet<>(); - private Reach(ObjectHost objects, Map biomeObjects, ModuleLog log) { - this.objects = objects; + private Reach(PackResources resources, Map biomeObjects, ModuleLog log) { + this.resources = resources; this.biomeObjects = biomeObjects; this.log = log; } @@ -479,7 +479,7 @@ public final class FloatingObjectPlacing { private int objectReach(String objectKey, ObjectPlacement placement) { try { - Optional size = sizes.computeIfAbsent(objectKey, objects::sizeOf); + Optional size = sizes.computeIfAbsent(objectKey, key -> PlacementReach.sizeOf(resources, key)); if (size.isEmpty()) { return 0; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java new file mode 100644 index 000000000..6cbf96ca8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java @@ -0,0 +1,243 @@ +/* + * 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.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.modules.floating.IslandAnchor; +import art.arcane.iris.modules.floating.IslandFootprint; +import art.arcane.iris.modules.objects.ForwardingTerrain; +import art.arcane.iris.modules.objects.TerrainTransaction; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementTerrain; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Places the objects of floating islands through the pack's placement stages into the mantle of the chunk being + * generated: floating free, or against an island's top or underside, where nothing is written unless every block lands + * where the island lets it. Each object's blocks are recorded as its placement. + */ +final class FloatingPlacer { + private static final ObjectRotation NO_ROTATION = ObjectRotation.of(0, 0, 0); + private static final int SAMPLED_HEIGHT = -1; + private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); + + private final PackWorld world; + private final BlockRegistry blocks; + private final ModuleLog log; + + FloatingPlacer(PackWorld world, ModuleLog log) { + this.world = world; + this.blocks = world.resources().blocks(); + this.log = log; + } + + /** Where {@code object} stands: its solid columns, its tallest column and that column's lowest solid block. */ + IslandFootprint footprint(PlaceableObject object) { + Map columns = new HashMap<>(); + for (ObjectBlock block : object.geometry().blocks()) { + if (!blocks.hasTrait(block.state(), BlockTrait.SOLID)) { + continue; + } + BlockPosition position = block.position(); + int[] column = columns.computeIfAbsent(IslandFootprint.column(position.x(), position.z()), + ignored -> new int[]{position.y(), 0}); + column[0] = Math.min(column[0], position.y()); + column[1]++; + } + if (columns.isEmpty()) { + return new IslandFootprint(0, 0, object.center().y(), new long[0]); + } + long tallest = tallestColumn(columns); + long[] footprint = columns.keySet().stream().mapToLong(Long::longValue).toArray(); + return new IslandFootprint(IslandFootprint.columnX(tallest), IslandFootprint.columnZ(tallest), columns.get(tallest)[0], footprint); + } + + /** The column with the most solid blocks; the lowest bottom wins a tie. */ + private static long tallestColumn(Map columns) { + long best = 0L; + int tallestCount = 0; + int tallestLow = Integer.MAX_VALUE; + for (Map.Entry entry : columns.entrySet()) { + int low = entry.getValue()[0]; + int count = entry.getValue()[1]; + if (count > tallestCount || (count == tallestCount && low < tallestLow)) { + tallestCount = count; + tallestLow = low; + best = entry.getKey(); + } + } + return best; + } + + /** Places {@code object} floating free at the column, into the chunk {@code context} generates. */ + void placeFloating(MantleStageContext context, PlaceableObject object, int worldX, int worldZ, ObjectPlacement placement, + RNG random) { + ObjectPlacement floating = placement.toBuilder().place(List.of(object.name())).build(); + int id = random.i(0, Integer.MAX_VALUE); + try { + place(ObjectRun.of(object, floating, worldX, SAMPLED_HEIGHT, worldZ), context.placementTerrain(), object, id); + } catch (Throwable failure) { + log.error("Failed to place a floating object", failure); + } + } + + /** + * Places {@code object} on an island's top, its lowest block at {@code y}; nothing is written unless every block it + * writes is one {@code anchor} lets it write. + */ + void placeOnTop(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, ObjectPlacement placement, + IslandAnchor anchor, RNG random) { + placeAgainstIsland(context, object, worldX, y, worldZ, placement, NO_ROTATION, anchor, random, "anchored"); + } + + /** Places {@code object} upside down under an island, turned {@code yRotation} degrees about Y, as {@link #placeOnTop} does on top. */ + void placeUnder(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, int yRotation, + ObjectPlacement placement, IslandAnchor anchor, RNG random) { + placeAgainstIsland(context, object, worldX, y, worldZ, placement, ObjectRotation.xFlip180WithY(yRotation), anchor, random, + "inverted"); + } + + private void placeAgainstIsland(MantleStageContext context, PlaceableObject object, int worldX, int y, int worldZ, + ObjectPlacement placement, ObjectRotation rotation, IslandAnchor anchor, RNG random, String kind) { + ObjectPlacement anchored = placement.toBuilder() + .place(List.of(object.name())) + .mode(placement.mode().onFloatingIsland()) + .translate(new ObjectTranslate()) + .rotation(rotation) + .forcePlace(true) + .bottom(false) + .build(); + IslandTransaction transaction = new IslandTransaction(new IslandTerrain(context.placementTerrain(), anchor), anchor); + int id = random.i(0, Integer.MAX_VALUE); + try { + boolean placed = place(ObjectRun.of(object, anchored, worldX, y, worldZ), transaction, object, id); + if (placed) { + transaction.commit(); + } else { + transaction.discard(); + } + } catch (Throwable failure) { + transaction.discard(); + log.error("Failed to place an " + kind + " floating object", failure); + } + } + + /** Places the run and records the object's placement beside each block it wrote that is not air. */ + private boolean place(ObjectRun run, PlacementTerrain terrain, PlaceableObject object, int id) { + if (!run.placeIn(world, terrain).isPlaced()) { + return false; + } + String placementName = object.name() + "@" + id; + for (BlockPosition position : run.objectBlocks()) { + if (placesBlock(terrain.get(position.x(), position.y(), position.z()))) { + terrain.recordPlacement(position.x(), position.y(), position.z(), placementName); + } + } + return true; + } + + private boolean placesBlock(BlockState state) { + return blocks.hasTrait(state, BlockTrait.CUSTOM) || !AIR_MATERIALS.contains(state.material().toString()); + } + + /** + * The mantle as an object placed against an island sees it: heights are the island face's, nothing is under water, + * and only the blocks the anchor lets the object write are written. + */ + private static final class IslandTerrain extends ForwardingTerrain { + private final IslandAnchor anchor; + + private IslandTerrain(PlacementTerrain delegate, IslandAnchor anchor) { + super(delegate); + this.anchor = anchor; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return anchor.faceY(x, z); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public void set(int x, int y, int z, BlockState state) { + if (anchor.writes(x, y, z)) { + delegate().set(x, y, z, state); + } + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + if (anchor.writes(x, y, z)) { + delegate().set(x, y, z, state, blockEntity); + } + } + + @Override + public void recordPlacement(int x, int y, int z, String placement) { + if (anchor.writes(x, y, z)) { + delegate().recordPlacement(x, y, z, placement); + } + } + + @Override + public void mark(PlacedMarker marker) { + BlockPosition position = marker.position(); + if (anchor.writes(position.x(), position.y(), position.z())) { + delegate().mark(marker); + } + } + } + + /** Writes an object placed against an island only when the anchor lets it write every block. */ + private static final class IslandTransaction extends TerrainTransaction { + private final IslandAnchor anchor; + + private IslandTransaction(PlacementTerrain delegate, IslandAnchor anchor) { + super(delegate); + this.anchor = anchor; + } + + @Override + protected boolean accepts(int x, int y, int z) { + return anchor.writes(x, y, z); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java new file mode 100644 index 000000000..519772a98 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/GoldenDebugTerrain.java @@ -0,0 +1,99 @@ +/* + * 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.modules.objects.ForwardingTerrain; +import com.volmit.ModuleLog; +import com.volmit.placement.PlacementTerrain; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +/** + * A terrain that logs the questions a placement asks of it, for the chunks the golden-debug switch names: the + * {@code iris.goldendebug} system property, or else {@code plugins/Iris/goldendebug.txt}, holding + * {@code chunkX,chunkZ[,radius]}. + */ +final class GoldenDebugTerrain extends ForwardingTerrain { + private static final String SWITCH_PROPERTY = "iris.goldendebug"; + private static final File SWITCH_FILE = new File("plugins/Iris/goldendebug.txt"); + private static final int[] TARGET = parseTarget(readSwitch()); + + private final String tag; + private final ModuleLog log; + + GoldenDebugTerrain(PlacementTerrain delegate, String tag, ModuleLog log) { + super(delegate); + this.tag = tag; + this.log = log; + } + + /** Whether the switch names the chunk. */ + static boolean isGoldenDebugChunk(int chunkX, int chunkZ) { + return TARGET != null + && Math.abs(TARGET[0] - chunkX) <= TARGET[2] + && Math.abs(TARGET[1] - chunkZ) <= TARGET[2]; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + int result = delegate().highest(x, z, ignoreFluid); + log.debug("Goldendebug query: tag=" + tag + " getHighest(" + x + "," + z + ",ignoreFluid=" + ignoreFluid + ")=" + result); + return result; + } + + @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; + } + + private static String readSwitch() { + String property = System.getProperty(SWITCH_PROPERTY); + if (property != null && !property.isBlank()) { + return property; + } + if (!SWITCH_FILE.isFile()) { + return null; + } + try { + return Files.readString(SWITCH_FILE.toPath()).trim(); + } catch (IOException | SecurityException unreadable) { + return null; + } + } + + private static int[] parseTarget(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 malformed) { + return null; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java b/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java index 316de43d9..e0e31081d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IslandFace.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.floating.IslandAnchor; +import art.arcane.iris.modules.floating.IslandAnchor; import art.arcane.iris.engine.object.terrain.floating.FloatingIslandSample; import art.arcane.iris.engine.object.terrain.floating.ResolvedFloatingChild; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java new file mode 100644 index 000000000..2ed257e1a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java @@ -0,0 +1,171 @@ +/* + * 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.MatterMantle; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.blocks.ObjectMarkers; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.modules.objects.CarvedSpace; +import art.arcane.iris.modules.objects.CavePlacement; +import art.arcane.iris.modules.objects.CaveTransaction; +import art.arcane.iris.modules.objects.EffectiveSettings; +import art.arcane.iris.modules.objects.ForwardingTerrain; +import art.arcane.iris.modules.objects.PlacementChanges; +import art.arcane.iris.modules.objects.PlacementTags; +import art.arcane.iris.modules.objects.ProceduralPlacement; +import art.arcane.iris.modules.objects.TerrainTransaction; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacementOutcome; +import com.volmit.placement.PlacementTerrain; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; + +/** + * The chunk whose mantle {@code iris:objects} is placing into: the one place its objects are written. Every placement + * here runs the pack's placement stages ({@link com.volmit.placement.Placements}) over the chunk's mantle, then writes the + * placement's tags beside the object's own blocks. + */ +final class ObjectChunk { + private static final int REJECTED = -1; + private static final int SAMPLED_HEIGHT = -1; + + private final PackWorld world; + private final PlacementTerrain terrain; + private final CarvedSpace carved; + private final EffectiveSettings settings; + private final BlockRegistry blocks; + private final ModuleLog log; + private final int worldHeight; + + ObjectChunk(MantleStageContext context, EffectiveSettings settings, ModuleLog log) { + this.world = context.world(); + this.terrain = context.placementTerrain(); + this.worldHeight = context.terrain().bounds().maxY(); + this.carved = new CarvedSpace(context.extension(MatterMantle.class).orElseThrow(), worldHeight); + this.settings = settings; + this.blocks = world.resources().blocks(); + this.log = log; + } + + /** The voids the cave carver planned around the chunk. */ + CarvedSpace carved() { + return carved; + } + + /** Whether the golden-debug switch is on for the chunk, which logs every decision of its placements. */ + boolean goldenDebug(int chunkX, int chunkZ) { + return GoldenDebugTerrain.isGoldenDebugChunk(chunkX, chunkZ); + } + + /** + * Places an object on the terrain, where it sits at the height its place mode finds. + * + * @param goldenTag logs the placement's questions under this tag, or null to leave them + * @return the height the object was placed at, negative when the placement rejected it + */ + int placeOnSurface(PlaceableObject object, int x, int z, PlacementSource placement, PlacementChanges changes, + PlacementTags tags, String goldenTag) { + PlacementTerrain placer = proceduralTerrain(terrain, placement, goldenTag); + return place(ObjectRun.of(object, settings.of(placement, changes), x, SAMPLED_HEIGHT, z), placer, tags); + } + + /** + * Places an object in a cave, anchored at {@code anchorY}, and writes it only when all of it lies inside the cave and + * no deeper than {@code minDepthBelowSurface} under the surface. + * + * @param goldenTag logs the placement's questions under this tag, or null to leave them + */ + CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, PlacementSource placement, PlacementChanges changes, + int minDepthBelowSurface, PlacementTags tags, String goldenTag) { + ObjectPlacement effective = settings.of(placement, changes); + CaveTransaction transaction = new CaveTransaction(proceduralTerrain(terrain, placement, goldenTag), worldHeight, anchorY, + minDepthBelowSurface); + int placeY = anchorY; + if (effective.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { + placeY = Math.max(1, transaction.caveCeiling(x, z) - 1 - Math.floorDiv(object.height(), 2)); + } + int result = place(ObjectRun.of(object, effective, x, placeY, z), transaction, tags); + if (result < 0) { + transaction.discard(); + return new CavePlacement(result, TerrainTransaction.Commit.EMPTY); + } + return new CavePlacement(result, transaction.commit()); + } + + /** Places an object at a given height, which the terrain stacked above uses for the objects hung from it. */ + int placeUpper(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, + PlacementTags tags) { + return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, anchorY, z), terrain, tags); + } + + private int place(ObjectRun run, PlacementTerrain placer, PlacementTags tags) { + PlacementOutcome outcome = run.placeIn(world, placer); + if (!outcome.isPlaced()) { + return REJECTED; + } + writeTags(placer, run, tags); + return run.anchorY().orElse(REJECTED); + } + + /** + * A procedural object's terrain: its leaves decay when it is meant to look real, and the golden-debug switch logs + * its questions. Object placements use the chunk's terrain as it is. + */ + private PlacementTerrain proceduralTerrain(PlacementTerrain base, PlacementSource placement, String goldenTag) { + if (!(placement instanceof ProceduralPlacement procedural)) { + return base; + } + PlacementTerrain decaying = procedural.plausible() ? new DecayingTerrain(base) : base; + return goldenTag == null ? decaying : new GoldenDebugTerrain(decaying, goldenTag, log); + } + + /** Writes the tags beside each of the object's own blocks. */ + private void writeTags(PlacementTerrain placer, ObjectRun run, PlacementTags tags) { + for (BlockPosition position : run.objectBlocks()) { + if (tags.marker() != null) { + placer.recordPlacement(position.x(), position.y(), position.z(), tags.marker()); + if (tags.treeMaterial()) { + placer.mark(ObjectMarkers.treeMaterial(position)); + } + } + if (tags.buriedTreasure() && blocks.hasTrait(placer.get(position.x(), position.y(), position.z()), BlockTrait.STORAGE)) { + placer.mark(ObjectMarkers.buriedTreasure(position)); + } + } + } + + /** A terrain whose leaves decay, for procedural objects meant to look like the real thing. */ + private static final class DecayingTerrain extends ForwardingTerrain { + private DecayingTerrain(PlacementTerrain delegate) { + super(delegate); + } + + @Override + public boolean preventsDecay() { + return false; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java index 9f90c5180..6e6ca6c2a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectLocating.java @@ -18,8 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.modules.objects.Declaration; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import com.volmit.config.Level; @@ -50,7 +49,7 @@ public final class ObjectLocating implements ObjectsAt { PackResources resources = world.resources(); Set biomes = new LinkedHashSet<>(); Set regions = new LinkedHashSet<>(); - for (Declaration declaration : world.extension(ObjectHost.class).orElseThrow().declarations(ObjectSettings.class)) { + for (Declaration declaration : Declaration.allOf(world, ObjectSettings.class)) { if (!placesObject(declaration.settings().objects(), resources, object)) { continue; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 63e55c13a..80570327d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; @@ -79,6 +78,6 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { } private static int reach(PackSettings settings, ModuleLog log) { - return new PlacementReach(settings.extension(ObjectHost.class).orElseThrow(), log).ofPack(settings); + return new PlacementReach(settings.resources(), log).ofPack(settings); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 1246b00ed..3be711ca4 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -18,15 +18,15 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.PlaceableObject; +import art.arcane.iris.modules.objects.EffectiveSettings; +import art.arcane.iris.modules.objects.ObjectPool; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; import com.volmit.config.Level; -import com.volmit.config.PackSettings; import com.volmit.config.SettingsStack; +import com.volmit.object.PlaceableObject; import com.volmit.stage.MantleStageContext; import com.volmit.world.PackWorld; @@ -36,8 +36,7 @@ import java.util.Set; /** * Places the objects the dimension's regions and biomes declare, one chunk at a time, into the mantle of a world: the worker - * of {@link ObjectModule}, one per world. It also works out which objects a chunk would get, without placing them, and how far - * the pack's objects reach. + * of {@link ObjectModule}, one per world. It also works out which objects a chunk would get, without placing them. */ public final class ObjectPlacing { private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; @@ -47,12 +46,13 @@ public final class ObjectPlacing { private static final Level[] GUESSED_LEVELS = {Level.BIOME, Level.REGION}; private final PackWorld world; - private final ObjectHost host; + private final ObjectPool objects; + private final EffectiveSettings settings = new EffectiveSettings(); private final ModuleLog log; private ObjectPlacing(PackWorld world) { this.world = world; - this.host = world.extension(ObjectHost.class).orElseThrow(); + this.objects = ObjectPool.of(world); this.log = world.log(); } @@ -63,12 +63,12 @@ public final class ObjectPlacing { /** Places what originates in the chunk {@code context} generates. */ void place(MantleStageContext context) { - new ChunkObjectPlacing(host, log, context).place(); + new ChunkObjectPlacing(objects, settings, log, context).place(); } /** The keys of the objects the chunk would get, as far as the chunk's surface objects go. */ public Set guess(int chunkX, int chunkZ) { - RNG rng = host.chunkRandom(chunkX, chunkZ); + RNG rng = objects.chunkRandom(chunkX, chunkZ); int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; SettingsStack declared = world.running().orElseThrow().settings().at(ObjectSettings.class, centerX, centerZ); @@ -89,15 +89,10 @@ public final class ObjectPlacing { private Set guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) { Set keys = new HashSet<>(); - for (int i = 0; i < host.density(placement, rng, x, z); i++) { - Optional picked = host.pickScaled(placement, rng); - picked.ifPresent(object -> keys.add(object.key())); + for (int i = 0; i < objects.density(placement, rng, x, z); i++) { + Optional picked = objects.pickScaled(placement, rng); + picked.ifPresent(object -> keys.add(object.name())); } return keys; } - - /** How far, in blocks along X and Z, placements may write beyond their chunk. */ - public int reach(PackSettings settings) { - return new PlacementReach(host, log).ofPack(settings); - } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index e2a4525d8..8852198d4 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -18,14 +18,14 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.ObjectHost.Declaration; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralPlacement; -import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.iris.modules.objects.Declaration; +import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ProceduralPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; import com.volmit.world.PackWorld; @@ -35,28 +35,27 @@ import java.util.List; /** * Builds what object placing would build on first use, for every object placement and procedural object the world's - * biomes and regions declare: the placement's surface warp and density noise, and a procedural object's variants. None - * of it depends on the random it is warmed with; the warp is seeded from the world, the density noise is cached per seed - * and the variants are baked whatever picks one. + * biomes and regions declare: the placement's density noise, and a procedural object's variants. None of it depends on + * the random it is warmed with; the density noise is cached per seed and the variants are baked whatever picks one. */ final class ObjectWarmUp { private static final long ROOT_SEED_SALT = 7777L; private static final Level[] WARMED_LEVELS = {Level.BIOME, Level.REGION}; private final PackWorld world; - private final ObjectHost host; + private final ObjectPool objects; private final RNG root; private int warmed; ObjectWarmUp(PackWorld world) { this.world = world; - this.host = world.extension(ObjectHost.class).orElseThrow(); + this.objects = ObjectPool.of(world); this.root = new RNG(world.seed(IrisSeedPurposes.COMPONENT) + ROOT_SEED_SALT); } void warm() { - List> placements = byKey(host.declarations(ObjectSettings.class)); - List> procedural = byKey(host.declarations(ProceduralObjectSettings.class)); + List> placements = byKey(Declaration.allOf(world, ObjectSettings.class)); + List> procedural = byKey(Declaration.allOf(world, ProceduralObjectSettings.class)); for (Level level : WARMED_LEVELS) { for (Declaration declaration : placements) { if (declaration.level() == level) { @@ -78,7 +77,7 @@ final class ObjectWarmUp { private void warmPlacements(List placements) { for (ObjectPlacement placement : placements) { if (placement != null) { - host.warm(placement, root.nextParallelRNG(warmed++)); + objects.warm(placement, root.nextParallelRNG(warmed++)); } } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java index 13554aa69..af794029f 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -20,20 +20,21 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.PlaceMode; import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.objects.ObjectSize; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.PlaceableObject; -import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.iris.modules.objects.ObjectSize; +import art.arcane.iris.modules.objects.ProceduralPlacement; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; +import com.volmit.geometry.BlockBox; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; import java.util.HashMap; import java.util.HashSet; @@ -48,13 +49,13 @@ final class PlacementReach { private static final int MAX_VACUUM_RADIUS_BLOCKS = 128; private static final double SCALE_PADDING_FACTOR = 2D; - private final ObjectHost host; + private final PackResources resources; private final ModuleLog log; private final Map> sizes = new HashMap<>(); private final Set warnedLargeObjects = new HashSet<>(); - PlacementReach(ObjectHost host, ModuleLog log) { - this.host = host; + PlacementReach(PackResources resources, ModuleLog log) { + this.resources = resources; this.log = log; } @@ -85,7 +86,7 @@ final class PlacementReach { private int ofObject(ObjectPlacement placement, String objectKey) { try { - Optional size = sizes.computeIfAbsent(objectKey, host::sizeOf); + Optional size = sizes.computeIfAbsent(objectKey, key -> sizeOf(resources, key)); if (size.isEmpty()) { return 0; } @@ -100,9 +101,18 @@ final class PlacementReach { } } + /** The size of the pack object {@code objectKey} names; empty when the pack has none. */ + static Optional sizeOf(PackResources resources, String objectKey) { + return resources.objects().sizeOf(resources.idOf(objectKey)).map(PlacementReach::sizeOf); + } + + private static ObjectSize sizeOf(BlockBox box) { + return new ObjectSize(box.maxX() - box.minX(), box.maxY() - box.minY(), box.maxZ() - box.minZ()); + } + private int ofProcedural(ProceduralObjectSettings settings) { int radius = 0; - for (ProceduralPlacement placement : ResolvedProceduralObjects.resolve(settings, host)) { + for (ProceduralPlacement placement : ResolvedProceduralObjects.resolve(settings, resources)) { for (PlaceableObject variant : placement.variants()) { radius = Math.max(radius, of(new ObjectSize(variant.width(), variant.height(), variant.depth()), placement)); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 0e6cc5776..91af66977 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -18,24 +18,30 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.ObjectHost.Declaration; import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.ObjectSink; -import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.TreeMode; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.engine.loot.BlockBiomes; +import art.arcane.iris.modules.objects.Declaration; +import art.arcane.iris.modules.objects.ObjectPool; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import com.volmit.config.Level; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.PlaceableObject; import com.volmit.placement.PlacedBlock; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.StructureVolumes; import com.volmit.resource.ResourceId; import com.volmit.service.SaplingGrowth; -import com.volmit.geometry.BlockPosition; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; @@ -57,7 +63,6 @@ public final class TreeGrowing implements SaplingGrowth { @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { - ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); RunningWorld running = world.running().orElseThrow(); BlockPosition at = sapling.at(); TreeGrowthSettings growth = treeGrowth(running, at); @@ -69,26 +74,26 @@ public final class TreeGrowing implements SaplingGrowth { return Optional.empty(); } List keys = placement.get().place(); - Optional tree = host.object(keys.get(RNG.r.i(keys.size()))); + Optional tree = ObjectPool.of(world).object(keys.get(RNG.r.i(keys.size()))); if (tree.isEmpty()) { return Optional.empty(); } PlaceableObject object = tree.get(); - GrowthSink sink = new GrowthSink(surroundings, running.layout().fluidHeight()); + GrowthTerrain terrain = new GrowthTerrain(surroundings, running.layout().fluidHeight(), world.resources().blocks()); BlockPosition center = sapling.center(); - host.placeInto(object, center.x(), center.y() + object.height() / 2, center.z(), placement.get(), sink, RNG.r); - return Optional.of(new Growth(world.resources().idOf(object.key()), sink.placed())); + ObjectRun run = ObjectRun.of(object, placement.get(), center.x(), center.y() + object.height() / 2, center.z()); + run.placeIn(world, terrain); + return Optional.of(new Growth(world.resources().idOf(object.name()), terrain.placed())); } @Override public TreeObjects treeObjects(PackWorld world) { - ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); Set objects = new HashSet<>(); Set procedural = new HashSet<>(); - for (Declaration declaration : host.declarations(ObjectSettings.class)) { + for (Declaration declaration : Declaration.allOf(world, ObjectSettings.class)) { collectPlacements(declaration.settings().objects(), objects); } - for (Declaration declaration : host.declarations(ProceduralObjectSettings.class)) { + for (Declaration declaration : Declaration.allOf(world, ProceduralObjectSettings.class)) { collectProceduralTrees(declaration.settings().trees(), procedural); } return new TreeObjects(idsOf(world, objects), idsOf(world, procedural)); @@ -153,15 +158,38 @@ public final class TreeGrowing implements SaplingGrowth { } } - /** Places an object into a list of blocks, reading the world around the sapling through the host. */ - private static final class GrowthSink implements ObjectSink { + /** + * The world around a sapling, read through the host, collecting what a tree writes into a list of blocks the host + * then places. Its leaves never decay; it has no caves, water, structures or placement records, and keeps no block + * entities or markers. + */ + private static final class GrowthTerrain implements PlacementTerrain { + private static final StructureVolumes NO_STRUCTURES = new StructureVolumes() { + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + return false; + } + + @Override + public boolean containsWithin(int x, int y, int z, int margin) { + return false; + } + }; + private final Surroundings surroundings; private final int fluidHeight; + private final BlockRegistry blocks; private final List placed = new ArrayList<>(); - private GrowthSink(Surroundings surroundings, int fluidHeight) { + private GrowthTerrain(Surroundings surroundings, int fluidHeight, BlockRegistry blocks) { this.surroundings = surroundings; this.fluidHeight = fluidHeight; + this.blocks = blocks; } private List placed() { @@ -183,9 +211,52 @@ public final class TreeGrowing implements SaplingGrowth { placed.add(new PlacedBlock(new BlockPosition(x, y, z), state, Optional.empty())); } + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + set(x, y, z, state); + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return blocks.hasTrait(get(x, y, z), BlockTrait.SOLID); + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + @Override public int fluidHeight() { return fluidHeight; } + + @Override + public boolean preventsDecay() { + return true; + } + + @Override + public void recordPlacement(int x, int y, int z, String placement) { + } + + @Override + public Optional placementAt(int x, int y, int z) { + return Optional.empty(); + } + + @Override + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return NO_STRUCTURES; + } + + @Override + public void mark(PlacedMarker marker) { + } } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java index 946b40478..2d527b99b 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/AnchorModule.java @@ -18,17 +18,17 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.AnchorHeight; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.placement.CaveSpace; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.ObjectShape; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.placement.PlacementTerrain; -import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.modules.placement.ObjectShape; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; @@ -53,17 +53,17 @@ public final class AnchorModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var graph = setup.stages(); - graph.define(IrisStages.Anchor.HEIGHT) - .requires(IrisStages.Prepare.TRANSFORMS) + graph.define(PlacementStages.Anchor.HEIGHT) + .requires(PlacementStages.Prepare.TRANSFORMS) .produce(AnchorModule::height); - graph.define(IrisStages.Anchor.FINAL) - .requires(IrisStages.Anchor.HEIGHT, IrisStages.Validate.COLLISIONS) + graph.define(PlacementStages.Anchor.FINAL) + .requires(PlacementStages.Anchor.HEIGHT, PlacementStages.Validate.COLLISIONS) .produce(AnchorModule::finalHeight); } private static AnchorHeight height(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); boolean structurePiece = prepared.mode().has(PlaceTrait.RAW_STAMP); if (!settings.fromBottom() && placement.requestedY() < 0) { @@ -88,12 +88,12 @@ public final class AnchorModule implements IrisModule { } private static AnchorHeight finalHeight(PlacementStageContext context) { - int y = context.output(IrisStages.Anchor.HEIGHT).y() + context.output(IrisStages.Prepare.TRANSFORMS).randomY(); - context.extension(ObjectPlacement.class).orElseThrow().anchoredAt(y); + int y = context.output(PlacementStages.Anchor.HEIGHT).y() + context.output(PlacementStages.Prepare.TRANSFORMS).randomY(); + context.output(PlacementStages.Prepare.TRANSFORMS).placement().anchoredAt(y); return new AnchorHeight(y); } - private static int sampled(PlacementStageContext context, ObjectPlacement placement, PreparedPlacement prepared) { + private static int sampled(PlacementStageContext context, RunningPlacement placement, PreparedPlacement prepared) { return switch (prepared.mode().anchor()) { case CENTER -> checked(context, prepared, placement.x(), centerSurface(placement, prepared), placement.z()); case SURFACE -> checked(context, prepared, placement.x(), surface(prepared, placement.x(), placement.z()), placement.z()); @@ -107,8 +107,8 @@ public final class AnchorModule implements IrisModule { } /** The floor of the cave the object is placed in, otherwise the surface at its center. */ - private static int centerSurface(ObjectPlacement placement, PreparedPlacement prepared) { - Optional cave = placement.cave(); + private static int centerSurface(RunningPlacement placement, PreparedPlacement prepared) { + Optional cave = placement.cave(); if (cave.isPresent()) { return cave.get().surface() + prepared.rotatedCenterY(); } @@ -127,7 +127,7 @@ public final class AnchorModule implements IrisModule { } /** The highest or lowest surface under the object's columns, or under its four corners only. */ - private static int extremeSurface(PlacementStageContext context, ObjectPlacement placement, PreparedPlacement prepared, + private static int extremeSurface(PlacementStageContext context, RunningPlacement placement, PreparedPlacement prepared, boolean highest, boolean cornersOnly) { TransformedBounds bounds = prepared.bounds(); int minX = placement.x() + bounds.minX(); @@ -152,7 +152,7 @@ public final class AnchorModule implements IrisModule { /** Whether the placement's carving support forbids anchoring at this block. */ private static boolean rejectsCarvingAnchor(PreparedPlacement prepared, int x, int y, int z) { - PlacementTerrain terrain = prepared.terrain(); + StageTerrain terrain = prepared.terrain(); return switch (prepared.settings().carvingSupport()) { case SURFACE_ONLY -> terrain.isCarved(x, y, z); case CARVING_ONLY -> !carvedWithin(terrain, x, y, z); @@ -160,7 +160,7 @@ public final class AnchorModule implements IrisModule { }; } - private static boolean carvedWithin(PlacementTerrain terrain, int x, int y, int z) { + private static boolean carvedWithin(StageTerrain terrain, int x, int y, int z) { for (int depth = 0; depth < CARVING_CLEARANCE_BLOCKS; depth++) { if (terrain.isCarved(x, y - depth, z)) { return true; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 29eb88f06..6594a008b 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -18,18 +18,19 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.placement.MarkerRule; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.placement.PlacementTerrain; -import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.engine.spawn.SpawnResources; +import art.arcane.iris.modules.blocks.SmartBoreDebugSettings; +import art.arcane.iris.modules.placement.MarkerRule; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; @@ -75,27 +76,28 @@ public final class BlocksModule implements IrisModule { @Override public void setup(ModuleSetup setup) { + setup.registry().registerSettings(SmartBoreDebugSettings.class); var graph = setup.stages(); - graph.define(IrisStages.Blocks.WRITE) - .requires(IrisStages.Prepare.TRANSFORMS, IrisStages.Anchor.FINAL, IrisStages.Bore.CLEAR) + graph.define(PlacementStages.Blocks.WRITE) + .requires(PlacementStages.Prepare.TRANSFORMS, PlacementStages.Anchor.FINAL, PlacementStages.Bore.CLEAR) .accumulate(WrittenBlocks::new, BlocksModule::write); - graph.define(IrisStages.Blocks.MARKERS) - .requires(IrisStages.Blocks.WRITE, IrisStages.Prepare.TRANSFORMS) + graph.define(PlacementStages.Blocks.MARKERS) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Prepare.TRANSFORMS) .run(BlocksModule::placeMarkers); - graph.define(IrisStages.Blocks.COMPLETE) - .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.MARKERS) + graph.define(PlacementStages.Blocks.COMPLETE) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Blocks.MARKERS) .run(context -> { }); } private static void write(BlockStageContext context, WrittenBlocks written) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + RunningPlacement placement = prepared.placement(); PlacementSettings settings = prepared.settings(); PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); ObjectBlock block = context.block(); BlockPosition offset = prepared.transform(block.position()); - int anchorY = context.output(IrisStages.Anchor.FINAL).y(); + int anchorY = context.output(PlacementStages.Anchor.FINAL).y(); BlockState data = sourceState(block, placement, prepared); Optional blockEntity = block.blockEntity(); if (!settings.edit().isEmpty()) { @@ -137,10 +139,10 @@ public final class BlocksModule implements IrisModule { } /** The object block as Iris places it: debug air shows where smart boring bored, and leaves never decay where the placer prevents it. */ - private static BlockState sourceState(ObjectBlock block, ObjectPlacement placement, PreparedPlacement prepared) { + private static BlockState sourceState(ObjectBlock block, RunningPlacement placement, PreparedPlacement prepared) { BlockState data = block.state(); - PlacementTerrain terrain = prepared.terrain(); - if (terrain.debugsSmartBore() && placement.matches(data, VOID_AIR)) { + StageTerrain terrain = prepared.terrain(); + if (placement.matches(data, VOID_AIR) && terrain.debugsSmartBore(placement.x(), placement.z())) { data = VOID_AIR_DEBUG; } if (terrain.preventsDecay() && data.properties().containsKey(DISTANCE) @@ -196,13 +198,13 @@ public final class BlocksModule implements IrisModule { * where the marker either allows anything above or finds two blocks of air. */ private static void placeMarkers(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + RunningPlacement placement = prepared.placement(); PlacementSettings settings = prepared.settings(); if (settings.markers().isEmpty() || !prepared.terrain().hasWorld()) { return; } - WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); + WrittenBlocks written = context.output(PlacementStages.Blocks.WRITE); PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); RNG markerRandom = new RNG(context.random().nextLong()); int salt = 0; @@ -226,7 +228,7 @@ public final class BlocksModule implements IrisModule { } } - private static KList candidates(WrittenBlocks written, MarkerRule rule, ObjectPlacement placement) { + private static KList candidates(WrittenBlocks written, MarkerRule rule, RunningPlacement placement) { KList candidates = new KList<>(); written.forEach((position, state) -> { if (rule.targets().stream().anyMatch(target -> marks(placement, rule, target, state))) { @@ -236,7 +238,7 @@ public final class BlocksModule implements IrisModule { return candidates; } - private static boolean marks(ObjectPlacement placement, MarkerRule rule, BlockState target, BlockState state) { + private static boolean marks(RunningPlacement placement, MarkerRule rule, BlockState target, BlockState state) { return rule.exact() ? placement.matches(target, state) : target.material().equals(state.material()); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java index c795f2086..a403f8c2d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BoreModule.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; @@ -39,19 +39,19 @@ public final class BoreModule implements IrisModule { @Override public void setup(ModuleSetup setup) { - setup.stages().define(IrisStages.Bore.CLEAR) - .requires(IrisStages.Anchor.FINAL, IrisStages.Validate.COLLISIONS) + setup.stages().define(PlacementStages.Bore.CLEAR) + .requires(PlacementStages.Anchor.FINAL, PlacementStages.Validate.COLLISIONS) .run(BoreModule::clear); } private static void clear(PlacementStageContext context) { - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (!settings.bore()) { return; } - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.FINAL).y()); + RunningPlacement placement = prepared.placement(); + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(PlacementStages.Anchor.FINAL).y()); PlacementWorld world = new PlacementWorld(context.access(), prepared.traits()); for (int x = volume.minX(); x <= volume.maxX(); x++) { for (int y = volume.minY() - settings.boreExtendMinY(); y <= volume.maxY() + settings.boreExtendMaxY(); y++) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java index 780dd222d..fcc552afd 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/IrisSurfaceSupport.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.placement.PlacementTerrain; +import art.arcane.iris.modules.placement.StageTerrain; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectSpinKernel; import art.arcane.iris.builtin.prepare.ObjectTranslate; @@ -21,7 +21,7 @@ public final class IrisSurfaceSupport { private IrisSurfaceSupport() { } - public static boolean isUnsupported(PlacementTerrain terrain, int x, int z, + public static boolean isUnsupported(StageTerrain terrain, int x, int z, ObjectTranslate translate, ObjectRotation rotation, int spinX, int spinY, int spinZ, List supportOffsets, int buffer, int minSolidDepth) { @@ -162,7 +162,7 @@ public final class IrisSurfaceSupport { } /** Centre-outward so the common failure, a hole right under the anchor, costs one column. */ - private boolean anyColumnUnsupported(PlacementTerrain terrain, int x, int z, int minSolidDepth) { + private boolean anyColumnUnsupported(StageTerrain terrain, int x, int z, int minSolidDepth) { int maxRing = Math.max( Math.max(centerX, width - 1 - centerX), Math.max(centerZ, depth - 1 - centerZ)); @@ -194,7 +194,7 @@ public final class IrisSurfaceSupport { return false; } - private boolean isColumnUnsupported(PlacementTerrain terrain, int x, int z, + private boolean isColumnUnsupported(StageTerrain terrain, int x, int z, int stencilX, int stencilZ, int minSolidDepth) { if (stencilX < 0 || stencilX >= width || stencilZ < 0 || stencilZ >= depth || !cells[(stencilX * depth) + stencilZ]) { diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java index 166b8fed2..1d4f0022d 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ObjectEdits.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.blocks.ObjectReplace; -import art.arcane.iris.builtin.placement.ObjectPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; @@ -39,7 +39,7 @@ final class ObjectEdits { /** The result's block entity is the last replacement's, if it has one. */ static Edited apply(List edits, BlockState data, Optional blockEntity, RNG rng, - double x, double y, double z, ResolvedReplaces replaces, ObjectPlacement placement) { + double x, double y, double z, ResolvedReplaces replaces, RunningPlacement placement) { BlockState edited = data; Optional editedEntity = blockEntity; for (ObjectReplace settings : edits) { @@ -61,13 +61,13 @@ final class ObjectEdits { return new Edited(edited, editedEntity); } - private static boolean finds(ObjectPlacement placement, ResolvedReplace replace, BlockState find, BlockState data) { + private static boolean finds(RunningPlacement placement, ResolvedReplace replace, BlockState find, BlockState data) { return replace.exact() ? placement.matches(find, data) : find.material().equals(data.material()); } - private static BlockState replaced(ObjectPlacement placement, BlockState data, BlockState replacement) { + private static BlockState replaced(RunningPlacement placement, BlockState data, BlockState replacement) { boolean sameMaterial = replacement.material().equals(data.material()); if (sameMaterial && !placement.hasTrait(replacement, BlockTrait.CUSTOM) && !placement.hasTrait(data, BlockTrait.CUSTOM)) { return placement.merge(data, replacement); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java index fcc10c1cb..56f71a811 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PlacementWorld.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.placement.BlockTraits; +import art.arcane.iris.modules.placement.BlockTraits; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.object.BlockEntityData; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java index d5df41e61..5689a5e1e 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/PrepareModule.java @@ -18,20 +18,20 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.placement.BlockTraits; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.ObjectShape; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.placement.PlacementTerrain; -import art.arcane.iris.builtin.placement.SurfaceWarp; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectSpinKernel; import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.modules.placement.BlockTraits; +import art.arcane.iris.modules.placement.ObjectShape; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import art.arcane.iris.modules.placement.SurfaceWarp; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; @@ -61,14 +61,14 @@ public final class PrepareModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var graph = setup.stages(); - graph.define(IrisStages.Prepare.SLOPE).produce(PrepareModule::slope); - graph.define(IrisStages.Prepare.TRANSFORMS) - .requires(IrisStages.Prepare.SLOPE) + graph.define(PlacementStages.Prepare.SLOPE).produce(PrepareModule::slope); + graph.define(PlacementStages.Prepare.TRANSFORMS) + .requires(PlacementStages.Prepare.SLOPE) .produce(PrepareModule::transforms); } private static ObjectRotation slope(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); + RunningPlacement placement = RunningPlacement.of(context); PlacementSettings settings = placement.settings(); ObjectRotation requested = settings.rotation(); boolean checksSlope = !settings.forcePlace() && !settings.slopeCondition().isDefault(); @@ -86,8 +86,8 @@ public final class PrepareModule implements IrisModule { } /** A copy of {@code requested} whose Y rotation faces the lowest side of the rectangle around the object. */ - private static ObjectRotation turnedDownhill(ObjectPlacement placement, ObjectRotation requested) { - PlacementTerrain terrain = placement.terrain(); + private static ObjectRotation turnedDownhill(RunningPlacement placement, ObjectRotation requested) { + StageTerrain terrain = placement.terrain(); ObjectShape object = placement.object(); int x = placement.x(); int z = placement.z(); @@ -108,12 +108,12 @@ public final class PrepareModule implements IrisModule { } private static PreparedPlacement transforms(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); + RunningPlacement placement = RunningPlacement.of(context); PlacementSettings settings = placement.settings(); - ObjectRotation rotation = context.output(IrisStages.Prepare.SLOPE); + ObjectRotation rotation = context.output(PlacementStages.Prepare.SLOPE); ObjectShape object = placement.object(); RNG rng = new RNG(context.random().nextLong()); - PlacementTerrain terrain = placement.terrainFor(rng); + StageTerrain terrain = placement.terrainFor(rng); int spinX = rng.imax() / SPIN_DIVISOR; int spinY = rng.imax() / SPIN_DIVISOR; int spinZ = rng.imax() / SPIN_DIVISOR; @@ -130,7 +130,7 @@ public final class PrepareModule implements IrisModule { Optional surfaceWarp = placement.surfaceWarp(rng); int warpMargin = surfaceWarp.map(warp -> (int) Math.ceil(Math.abs(warp.multiplier()) / 2D)).orElse(0); TransformedBounds bounds = transformedBounds(object, spin, translation, settings.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN), warpMargin); - return new PreparedPlacement(placement, rotation, new BlockTraits(placement), terrain, spin, + return new PreparedPlacement(placement, rotation, new BlockTraits(context.world().resources().blocks()), terrain, spin, spinX, spinY, spinZ, translation, rotatedCenter.getBlockY(), translatedCenter.getBlockY(), randomY, warpMargin, bounds, surfaceWarp.orElse(null)); } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java index e3d4a4ed8..ba03e286e 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/SnowModule.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -50,16 +50,16 @@ public final class SnowModule implements IrisModule { @Override public void setup(ModuleSetup setup) { - setup.stages().define(IrisStages.Snow.COVER) - .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) - .softAfter(IrisStages.Stilt.FILL, IrisStages.Vacuum.TERRAIN) + setup.stages().define(PlacementStages.Snow.COVER) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Blocks.COMPLETE, PlacementStages.Prepare.TRANSFORMS) + .softAfter(PlacementStages.Stilt.FILL, PlacementStages.Vacuum.TERRAIN) .run(SnowModule::cover); } private static void cover(PlacementStageContext context) { - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); double snow = prepared.settings().snow(); - WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); + WrittenBlocks written = context.output(PlacementStages.Blocks.WRITE); if (!(snow > 0) || written.isEmpty()) { return; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java index 5ef55b48c..2ac6363e0 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/StiltModule.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.StiltShape; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.stilt.StiltLayers; import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -71,18 +71,18 @@ public final class StiltModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var graph = setup.stages(); - graph.define(IrisStages.Stilt.LAYERS) - .requires(IrisStages.Prepare.TRANSFORMS) + graph.define(PlacementStages.Stilt.LAYERS) + .requires(PlacementStages.Prepare.TRANSFORMS) // Ordered after boring only so it shares the block pass that writes the object. - .softAfter(IrisStages.Bore.CLEAR) + .softAfter(PlacementStages.Bore.CLEAR) .accumulate(StiltLayers::new, StiltModule::collectLayer); - graph.define(IrisStages.Stilt.FILL) - .requires(IrisStages.Stilt.LAYERS, IrisStages.Anchor.FINAL, IrisStages.Blocks.COMPLETE) + graph.define(PlacementStages.Stilt.FILL) + .requires(PlacementStages.Stilt.LAYERS, PlacementStages.Anchor.FINAL, PlacementStages.Blocks.COMPLETE) .run(StiltModule::fill); } private static void collectLayer(BlockStageContext context, StiltLayers layers) { - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); if (prepared.mode().stilt() == StiltShape.NONE) { return; } @@ -103,9 +103,9 @@ public final class StiltModule implements IrisModule { } private static void fill(PlacementStageContext context) { - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); StiltShape shape = prepared.mode().stilt(); - StiltLayers layers = context.output(IrisStages.Stilt.LAYERS); + StiltLayers layers = context.output(PlacementStages.Stilt.LAYERS); if (shape == StiltShape.NONE || layers.isEmpty()) { return; } @@ -118,7 +118,7 @@ public final class StiltModule implements IrisModule { /** One placement's stilt, grown column by column under (or above) the blocks of its repeated layer. */ private static final class StiltColumns { - private final ObjectPlacement placement; + private final RunningPlacement placement; private final PreparedPlacement prepared; private final PlacementSettings config; private final StiltSettings settings; @@ -132,7 +132,7 @@ public final class StiltModule implements IrisModule { private final ErodeShape erode; private StiltColumns(PlacementStageContext context, PreparedPlacement prepared, StiltLayers layers) { - this.placement = context.extension(ObjectPlacement.class).orElseThrow(); + this.placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); this.prepared = prepared; this.context = context; this.config = prepared.settings(); @@ -140,7 +140,7 @@ public final class StiltModule implements IrisModule { this.shape = prepared.mode().stilt(); this.world = new PlacementWorld(context.access(), prepared.traits()); this.rng = new RNG(context.random().nextLong()); - this.anchorY = context.output(IrisStages.Anchor.FINAL).y(); + this.anchorY = context.output(PlacementStages.Anchor.FINAL).y(); this.palette = settings == null ? null : paletteBlock(settings); this.layerY = shape == StiltShape.CEILING ? layers.topY() : layers.bottomY(); this.erode = shape == StiltShape.ERODE ? ErodeShape.of(layers.bottom()) : null; diff --git a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java index f263a2ae9..690b8cf13 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/VacuumModule.java @@ -18,14 +18,14 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.VacuumProfile; import art.arcane.iris.builtin.blocks.WrittenBlocks; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.PlacementTerrain; -import art.arcane.iris.builtin.placement.PlaneNoise; -import art.arcane.iris.builtin.prepare.PreparedPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; +import art.arcane.iris.modules.placement.EdgeSimplex; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.builtin.vacuum.VacuumSettings; import com.volmit.IrisModule; @@ -57,15 +57,15 @@ public final class VacuumModule implements IrisModule { @Override public void setup(ModuleSetup setup) { - setup.stages().define(IrisStages.Vacuum.TERRAIN) - .requires(IrisStages.Blocks.WRITE, IrisStages.Blocks.COMPLETE, IrisStages.Prepare.TRANSFORMS) + setup.stages().define(PlacementStages.Vacuum.TERRAIN) + .requires(PlacementStages.Blocks.WRITE, PlacementStages.Blocks.COMPLETE, PlacementStages.Prepare.TRANSFORMS) .reach(IrisObjectVacuum.MAX_RADIUS_BLOCKS) .run(VacuumModule::bendTerrain); } private static void bendTerrain(PlacementStageContext context) { - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); - WrittenBlocks written = context.output(IrisStages.Blocks.WRITE); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); + WrittenBlocks written = context.output(PlacementStages.Blocks.WRITE); if (!prepared.mode().bendsTerrain() || written.isEmpty() || !prepared.terrain().hasWorld()) { return; } @@ -76,9 +76,9 @@ public final class VacuumModule implements IrisModule { /** One placement's terrain bend over the columns within its radius of the object's footprint. */ private static final class Bend { - private final ObjectPlacement placement; + private final RunningPlacement placement; private final PreparedPlacement prepared; - private final PlacementTerrain terrain; + private final StageTerrain terrain; private final PlacementWorld world; private final PlacementStageContext context; private final int radius; @@ -87,13 +87,13 @@ public final class VacuumModule implements IrisModule { private final int jitter; private final double waveAmplitude; private final double waveScale; - private final PlaneNoise waves; + private final EdgeSimplex waves; private final int lowestY; private final int highestY; private Bend(PlacementStageContext context, PreparedPlacement prepared) { VacuumProfile vacuum = prepared.mode().vacuum(); - this.placement = context.extension(ObjectPlacement.class).orElseThrow(); + this.placement = prepared.placement(); this.prepared = prepared; this.terrain = prepared.terrain(); this.world = new PlacementWorld(context.access(), prepared.traits()); @@ -105,7 +105,7 @@ public final class VacuumModule implements IrisModule { this.jitter = settings != null ? Math.max(0, settings.organicJitter()) : DEFAULT_ORGANIC_JITTER; this.waveAmplitude = IrisObjectVacuum.resolveWaveAmplitude(settings); this.waveScale = IrisObjectVacuum.resolveWaveScale(settings); - this.waves = vacuum.edge() == VacuumProfile.Edge.WAVY && waveAmplitude > 0 ? placement.simplex(WAVE_SEED) : null; + this.waves = vacuum.edge() == VacuumProfile.Edge.WAVY && waveAmplitude > 0 ? new EdgeSimplex(WAVE_SEED) : null; this.lowestY = IrisObjectVacuum.LOWEST_TARGET_Y; this.highestY = terrain.worldHeight() - 1; } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java index 487e21d8f..321e20eb4 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/ValidateModule.java @@ -18,17 +18,17 @@ package art.arcane.iris.engine.object.placement; -import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.placement.CaveSpace; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.ObjectShape; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.placement.PlacementTerrain; -import art.arcane.iris.builtin.placement.StructureVolumes; -import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.terrain.BedrockSettings; +import art.arcane.iris.modules.placement.ObjectShape; +import art.arcane.iris.modules.placement.PlacementSettings; +import art.arcane.iris.modules.placement.PlacementStages; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; +import art.arcane.iris.modules.placement.StageTerrain; +import com.volmit.placement.StructureVolumes; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLog; @@ -62,28 +62,28 @@ public final class ValidateModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var graph = setup.stages(); - graph.define(IrisStages.Validate.SURFACE) - .requires(IrisStages.Anchor.HEIGHT) + graph.define(PlacementStages.Validate.SURFACE) + .requires(PlacementStages.Anchor.HEIGHT) .run(ValidateModule::checkSurface); - graph.define(IrisStages.Validate.LIMITS) - .requires(IrisStages.Validate.SURFACE, IrisStages.Anchor.HEIGHT) + graph.define(PlacementStages.Validate.LIMITS) + .requires(PlacementStages.Validate.SURFACE, PlacementStages.Anchor.HEIGHT) .run(ValidateModule::checkLimits); - graph.define(IrisStages.Validate.STRUCTURES) - .requires(IrisStages.Validate.LIMITS, IrisStages.Anchor.HEIGHT) + graph.define(PlacementStages.Validate.STRUCTURES) + .requires(PlacementStages.Validate.LIMITS, PlacementStages.Anchor.HEIGHT) .run(ValidateModule::checkNativeStructures); - graph.define(IrisStages.Validate.COLLISIONS) - .requires(IrisStages.Validate.STRUCTURES, IrisStages.Anchor.HEIGHT) + graph.define(PlacementStages.Validate.COLLISIONS) + .requires(PlacementStages.Validate.STRUCTURES, PlacementStages.Anchor.HEIGHT) .run(ValidateModule::checkCollisions); } private static void checkSurface(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.forcePlace() || settings.fromBottom() || prepared.mode().has(PlaceTrait.FREE_HEIGHT)) { return; } - int y = context.output(IrisStages.Anchor.HEIGHT).y(); + int y = context.output(PlacementStages.Anchor.HEIGHT).y(); boolean sampled = placement.requestedY() < 0; if (sampled && settings.carvingSupport().supportsSurface() && isOnBedrock(context, prepared, y)) { warnImplausibleBedrockPlacement(placement, settings, y, context.log()); @@ -106,7 +106,7 @@ public final class ValidateModule implements IrisModule { return world.settings().declared(BedrockSettings.class).dimension().map(BedrockSettings::bedrock).orElse(true); } - private static boolean lacksSurfaceSupport(ObjectPlacement placement, PreparedPlacement prepared) { + private static boolean lacksSurfaceSupport(RunningPlacement placement, PreparedPlacement prepared) { PlacementSettings settings = prepared.settings(); return IrisSurfaceSupport.isUnsupported(prepared.terrain(), placement.x(), placement.z(), settings.translate(), prepared.rotation(), prepared.spinX(), prepared.spinY(), prepared.spinZ(), @@ -114,16 +114,16 @@ public final class ValidateModule implements IrisModule { } private static void checkLimits(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP)) { return; } - int y = context.output(IrisStages.Anchor.HEIGHT).y(); + int y = context.output(PlacementStages.Anchor.HEIGHT).y(); int rotated = prepared.rotatedCenterY(); int translated = prepared.translatedCenterY(); - Optional cave = placement.cave(); + Optional cave = placement.cave(); if (placement.requestedY() < 0 && !prepared.mode().has(PlaceTrait.FREE_HEIGHT) && !settings.underwater() && !settings.onwater() && prepared.terrain().isUnderwater(placement.x(), placement.z())) { context.reject("underwater-anchor"); @@ -138,19 +138,19 @@ public final class ValidateModule implements IrisModule { } private static void checkNativeStructures(PlacementStageContext context) { - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); if (prepared.mode().has(PlaceTrait.RAW_STAMP)) { return; } - int y = context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY(); - if (meetsNativeStructure(context, context.extension(ObjectPlacement.class).orElseThrow(), prepared, y)) { + int y = context.output(PlacementStages.Anchor.HEIGHT).y() + prepared.randomY(); + if (meetsNativeStructure(context, context.output(PlacementStages.Prepare.TRANSFORMS).placement(), prepared, y)) { context.reject("native-structure"); } } - private static boolean meetsNativeStructure(PlacementStageContext context, ObjectPlacement placement, + private static boolean meetsNativeStructure(PlacementStageContext context, RunningPlacement placement, PreparedPlacement prepared, int y) { - PlacementTerrain terrain = prepared.terrain(); + StageTerrain terrain = prepared.terrain(); if (!terrain.hasWorld()) { return false; } @@ -162,9 +162,8 @@ public final class ValidateModule implements IrisModule { return false; } boolean painted = WorldVolume.isPainted(placement, prepared); - int worldY = y + terrain.minWorldY(); - int envelopeMinY = painted ? Integer.MIN_VALUE : worldY - margin; - int envelopeMaxY = painted ? Integer.MAX_VALUE : worldY + margin; + int envelopeMinY = painted ? Integer.MIN_VALUE : y - margin; + int envelopeMaxY = painted ? Integer.MAX_VALUE : y + margin; if (!volumes.intersects(x - margin, envelopeMinY, z - margin, x + margin, envelopeMaxY, z + margin)) { return false; } @@ -179,8 +178,7 @@ public final class ValidateModule implements IrisModule { ? offset.y() + Math.floorDiv(placement.object().height(), 2) + terrain.highest(blockX, blockZ, prepared.settings().underwater()) : y + offset.y(); - int worldBlockY = blockY + terrain.minWorldY(); - if (volumes.containsWithin(blockX, worldBlockY, blockZ, prepared.warpMargin())) { + if (volumes.containsWithin(blockX, blockY, blockZ, prepared.warpMargin())) { return true; } } @@ -202,20 +200,20 @@ public final class ValidateModule implements IrisModule { } private static void checkCollisions(PlacementStageContext context) { - ObjectPlacement placement = context.extension(ObjectPlacement.class).orElseThrow(); - PreparedPlacement prepared = context.output(IrisStages.Prepare.TRANSFORMS); + RunningPlacement placement = context.output(PlacementStages.Prepare.TRANSFORMS).placement(); + PreparedPlacement prepared = context.output(PlacementStages.Prepare.TRANSFORMS); PlacementSettings settings = prepared.settings(); if (settings.forcePlace() || prepared.mode().has(PlaceTrait.RAW_STAMP) || (settings.allowedCollisions().isEmpty() && settings.forbiddenCollisions().isEmpty())) { return; } - WorldVolume volume = WorldVolume.of(placement, prepared, context.output(IrisStages.Anchor.HEIGHT).y() + prepared.randomY()); + WorldVolume volume = WorldVolume.of(placement, prepared, context.output(PlacementStages.Anchor.HEIGHT).y() + prepared.randomY()); if (collidesWithForbiddenObject(prepared.terrain(), settings, volume)) { context.reject("object-collision"); } } - private static boolean collidesWithForbiddenObject(PlacementTerrain terrain, PlacementSettings settings, WorldVolume volume) { + private static boolean collidesWithForbiddenObject(StageTerrain terrain, PlacementSettings settings, WorldVolume volume) { Set forbidden = settings.forbiddenCollisions(); Set allowed = settings.allowedCollisions(); for (int x = volume.minX(); x <= volume.maxX(); x++) { @@ -231,7 +229,7 @@ public final class ValidateModule implements IrisModule { return false; } - private static void warnImplausibleBedrockPlacement(ObjectPlacement placement, PlacementSettings settings, int y, ModuleLog log) { + private static void warnImplausibleBedrockPlacement(RunningPlacement placement, PlacementSettings settings, int y, ModuleLog log) { String key = placement.object().id().map(ResourceId::toString).orElse(null); String fingerprint = (key == null ? "" : key) + "|" + settings.mode(); long now = System.currentTimeMillis(); diff --git a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java index ee170f8c4..46ef966e0 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/WorldVolume.java @@ -19,8 +19,8 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.anchor.AnchorSampling; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.prepare.PreparedPlacement; +import art.arcane.iris.modules.placement.PreparedPlacement; +import art.arcane.iris.modules.placement.RunningPlacement; import art.arcane.iris.builtin.prepare.TransformedBounds; /** @@ -28,7 +28,7 @@ import art.arcane.iris.builtin.prepare.TransformedBounds; * object follows the surface column by column, so its volume spans every surface height under it. */ record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { - static WorldVolume of(ObjectPlacement placement, PreparedPlacement prepared, int anchorY) { + static WorldVolume of(RunningPlacement placement, PreparedPlacement prepared, int anchorY) { TransformedBounds bounds = prepared.bounds(); int minX = placement.x() + bounds.minX(); int maxX = placement.x() + bounds.maxX(); @@ -52,7 +52,7 @@ record WorldVolume(int minX, int maxX, int minY, int maxY, int minZ, int maxZ) { } /** Whether each block of the placement follows the surface of its own column. */ - static boolean isPainted(ObjectPlacement placement, PreparedPlacement prepared) { + static boolean isPainted(RunningPlacement placement, PreparedPlacement prepared) { return placement.requestedY() < 0 && prepared.mode().anchor() == AnchorSampling.SURFACE; } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java index df094fa56..1901c28e5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.math.Vector3i; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java index eb247cca9..515d2cbf5 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java @@ -18,9 +18,7 @@ package art.arcane.iris.engine.object.procedural; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ProceduralObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; @@ -28,7 +26,8 @@ import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; - +import art.arcane.iris.modules.objects.ProceduralPlacement; +import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import java.util.ArrayList; @@ -44,29 +43,29 @@ public final class ResolvedProceduralObjects { /** The placements {@code settings} declare in {@code world}, resolved the first time the world asks. */ public static List of(PackWorld world, ProceduralObjectSettings settings) { - ObjectHost host = world.extension(ObjectHost.class).orElseThrow(); + PackResources resources = world.resources(); return world.state(ResolvedByDeclaration.class, ignored -> new ResolvedByDeclaration()).placements - .computeIfAbsent(settings, declared -> resolve(declared, host)); + .computeIfAbsent(settings, declared -> resolve(declared, resources)); } /** The placements {@code settings} declare, resolved anew, for work outside any world such as working out the pack's reach. */ - public static List resolve(ProceduralObjectSettings settings, ObjectHost host) { + public static List resolve(ProceduralObjectSettings settings, PackResources resources) { List all = new ArrayList<>(); for (Tree tree : settings.trees()) { - all.add(new ResolvedTree(tree, host)); + all.add(new ResolvedTree(tree, resources)); } - addAll(all, settings.ruins(), host, ResolvedRuin::new); - addAll(all, settings.formations(), host, ResolvedFormation::new); - addAll(all, settings.coral(), host, ResolvedCoral::new); - addAll(all, settings.fungi(), host, ResolvedFungus::new); - addAll(all, settings.crystals(), host, ResolvedCrystal::new); + addAll(all, settings.ruins(), resources, ResolvedRuin::new); + addAll(all, settings.formations(), resources, ResolvedFormation::new); + addAll(all, settings.coral(), resources, ResolvedCoral::new); + addAll(all, settings.fungi(), resources, ResolvedFungus::new); + addAll(all, settings.crystals(), resources, ResolvedCrystal::new); return List.copyOf(all); } - private static void addAll(List all, List settings, ObjectHost host, - BiFunction resolve) { + private static void addAll(List all, List settings, PackResources resources, + BiFunction resolve) { for (S entry : settings) { - all.add(resolve.apply(entry, host)); + all.add(resolve.apply(entry, resources)); } } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java index 6bf87e22a..1cd7fb26d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java @@ -21,17 +21,17 @@ package art.arcane.iris.engine.object.procedural; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.PlaceableObject; -import art.arcane.iris.builtin.objects.ProceduralPlacement; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.stilt.StiltSettings; import art.arcane.iris.builtin.vacuum.VacuumSettings; import art.arcane.iris.builtin.validate.ObjectLimit; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ProceduralPlacement; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; import java.util.ArrayList; import java.util.List; @@ -39,7 +39,7 @@ import java.util.Optional; /** * A procedural object's settings made placeable: bakes a deterministic pool of variants from them, once, through the - * host's object builder, and hands the placement options to {@code iris:objects}. + * pack's objects ({@link ObjectBuilder}), and hands the placement options to {@code iris:objects}. */ public abstract class ResolvedProceduralPlacement implements ProceduralPlacement { private static final long VARIANT_SEED_STRIDE = 7919L; @@ -51,12 +51,12 @@ public abstract class ResolvedProceduralPlacement implements ProceduralPlacement } private final Shape shape; - private final ObjectHost host; + private final PackResources resources; private final AtomicCache> variantCache = new AtomicCache<>(); - protected ResolvedProceduralPlacement(Shape shape, ObjectHost host) { + protected ResolvedProceduralPlacement(Shape shape, PackResources resources) { this.shape = shape; - this.host = host; + this.resources = resources; } /** The shape variant {@code index} is baked as, from its own seeded stream; null when it has no blocks. */ @@ -139,7 +139,7 @@ public abstract class ResolvedProceduralPlacement implements ProceduralPlacement @Override public List variants() { - return variantCache.aquire(() -> bake(host.builder())); + return variantCache.aquire(() -> bake(new ObjectBuilder(resources))); } @Override diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java index 1699235d9..a4cd84155 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.coral; import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java index 8e99c0bbd..19f89c398 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java @@ -19,20 +19,20 @@ package art.arcane.iris.engine.object.procedural.coral; import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.PackResources; /** A coral reef made placeable: its variants are baked by {@link CoralGenerator}. */ public final class ResolvedCoral extends ResolvedProceduralPlacement { private final Coral settings; - public ResolvedCoral(Coral settings, ObjectHost host) { + public ResolvedCoral(Coral settings, PackResources resources) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); this.settings = settings; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java index 2ce127cc0..581d78498 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.crystal; import art.arcane.iris.builtin.objects.crystal.Crystal; import com.volmit.block.PaletteSpec; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java index 5a8243174..c82fa1141 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java @@ -19,20 +19,20 @@ package art.arcane.iris.engine.object.procedural.crystal; import art.arcane.iris.builtin.objects.crystal.Crystal; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.PackResources; /** A crystal cluster made placeable: its variants are baked by {@link CrystalGenerator}. */ public final class ResolvedCrystal extends ResolvedProceduralPlacement { private final Crystal settings; - public ResolvedCrystal(Crystal settings, ObjectHost host) { + public ResolvedCrystal(Crystal settings, PackResources resources) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); this.settings = settings; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java index 32e59ecdc..d7a8cacb7 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.object.procedural.formation; import com.volmit.block.PaletteSpec; import java.util.Optional; import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java index 40cbd260e..e0454ae3c 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.formation; import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java index 0f1c8c775..6dd0651a9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java @@ -19,20 +19,20 @@ package art.arcane.iris.engine.object.procedural.formation; import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.PackResources; /** A rock formation made placeable: its variants are baked by {@link FormationGenerator}. */ public final class ResolvedFormation extends ResolvedProceduralPlacement { private final Formation settings; - public ResolvedFormation(Formation settings, ObjectHost host) { + public ResolvedFormation(Formation settings, PackResources resources) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); this.settings = settings; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java index f0892715e..f28209979 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.fungi; import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java index 14f29c521..d2152469f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.builtin.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; import java.util.ArrayList; import java.util.List; @@ -33,10 +33,10 @@ import java.util.List; public final class ResolvedFungus extends ResolvedProceduralPlacement { private final Fungus settings; - public ResolvedFungus(Fungus settings, ObjectHost host) { + public ResolvedFungus(Fungus settings, PackResources resources) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); this.settings = settings; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java index ede9c4bdc..cb4f24a49 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java @@ -19,20 +19,20 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.PackResources; /** A ruin made placeable: its variants are baked by {@link RuinGenerator}. */ public final class ResolvedRuin extends ResolvedProceduralPlacement { private final Ruin settings; - public ResolvedRuin(Ruin settings, ObjectHost host) { + public ResolvedRuin(Ruin settings, PackResources resources) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); this.settings = settings; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java index 8930ed718..5f4b7dd73 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.builtin.objects.ruin.RuinDecorator; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java index 72fdd68da..da71d9853 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.ruin; import art.arcane.iris.builtin.objects.ruin.RuinDecorator; import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java index 32565c3b2..949e9739a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java index bd47810ec..e4b460df6 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.ObjectHost; -import art.arcane.iris.builtin.objects.PlaceableObject; import art.arcane.iris.builtin.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; +import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; import java.util.ArrayList; import java.util.List; @@ -37,10 +37,10 @@ public final class ResolvedTree extends ResolvedProceduralPlacement { private final Tree settings; - public ResolvedTree(Tree settings, ObjectHost host) { + public ResolvedTree(Tree settings, PackResources resources) { super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), host); + settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); this.settings = settings; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java index 82c944f9d..66bf85553 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; import art.arcane.iris.builtin.objects.tree.TreeDecorator; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import com.volmit.block.PaletteSpec; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.builtin.objects.tree.Tree; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java index 71e441cc6..07615ecaf 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.builtin.objects.tree.Tree; -import art.arcane.iris.builtin.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectBuilder; import com.volmit.block.BlockState; import java.util.ArrayDeque; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index e78e4d125..452451160 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -26,7 +26,6 @@ import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.modules.floating.FloatingChildSettings; import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; -import art.arcane.iris.builtin.objects.ObjectHost; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import com.volmit.noise.NoiseFactory; @@ -50,7 +49,6 @@ public final class FloatingWorld { private static final long BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; private final FloatingHost host; - private final ObjectHost objects; private final PackResources resources; private final RunningWorld running; private final long baseSeed; @@ -59,10 +57,9 @@ public final class FloatingWorld { private final List dimensionCarving; private final Map resolved = new ConcurrentHashMap<>(); - FloatingWorld(FloatingHost host, ObjectHost objects, PackResources resources, RunningWorld running, long terrainSeed, + FloatingWorld(FloatingHost host, PackResources resources, RunningWorld running, long terrainSeed, long carveSeed, int minWorldY, List dimensionCarving) { this.host = host; - this.objects = objects; this.resources = resources; this.running = running; this.baseSeed = terrainSeed ^ BASE_SEED_SALT; @@ -77,8 +74,7 @@ public final class FloatingWorld { } private static FloatingWorld create(PackWorld world) { - return new FloatingWorld(world.extension(FloatingHost.class).orElseThrow(), world.extension(ObjectHost.class).orElseThrow(), - world.resources(), world.running().orElseThrow(), world.seed(IrisSeedPurposes.TERRAIN), world.seed(IrisSeedPurposes.CARVE), + return new FloatingWorld(world.extension(FloatingHost.class).orElseThrow(), world.resources(), world.running().orElseThrow(), world.seed(IrisSeedPurposes.TERRAIN), world.seed(IrisSeedPurposes.CARVE), world.minWorldY(), dimensionCarvingOf(world)); } @@ -92,10 +88,6 @@ public final class FloatingWorld { return host; } - public ObjectHost objects() { - return objects; - } - public NoiseFactory noise() { return resources.noise(); } diff --git a/src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java b/src/main/java/art/arcane/iris/modules/blocks/SmartBoreDebugSettings.java similarity index 53% rename from src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java rename to src/main/java/art/arcane/iris/modules/blocks/SmartBoreDebugSettings.java index 71a92b00f..7568d1247 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/StructureVolumes.java +++ b/src/main/java/art/arcane/iris/modules/blocks/SmartBoreDebugSettings.java @@ -16,15 +16,24 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.placement; +package art.arcane.iris.modules.blocks; -/** The world-space bounds of the native structure pieces around a placement, in the world's real Y. */ -public interface StructureVolumes { - boolean isEmpty(); +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.config.Level; - /** Whether any piece meets the box, bounds inclusive. */ - boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ); +/** Whether a dimension shows the air smart boring writes as cobwebs, written as {@code "debugSmartBore": true}. */ +@Desc("Write the air that smart boring places as cobwebs, to see where it bored.") +@Feature(id = "iris:blocks/debug-smart-bore", name = "Debug smart bore", key = "debugSmartBore", root = "show", targets = Level.DIMENSION) +public final class SmartBoreDebugSettings implements IrisFeature { + @Desc("Write the air that smart boring places as cobwebs, to see where it bored.") + private boolean show = false; - /** Whether any piece contains the block or comes within {@code margin} blocks of it. */ - boolean containsWithin(int x, int y, int z, int margin); + public SmartBoreDebugSettings() { + } + + public boolean show() { + return show; + } } diff --git a/src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java b/src/main/java/art/arcane/iris/modules/floating/IslandAnchor.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java rename to src/main/java/art/arcane/iris/modules/floating/IslandAnchor.java index 90c8d2086..a8f2de170 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/IslandAnchor.java +++ b/src/main/java/art/arcane/iris/modules/floating/IslandAnchor.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; /** * The face of one island an object is placed against, as {@code iris:floating} samples it: how high the face is, which diff --git a/src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java b/src/main/java/art/arcane/iris/modules/floating/IslandFootprint.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java rename to src/main/java/art/arcane/iris/modules/floating/IslandFootprint.java index 3f25bebc8..de9b8133e 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/IslandFootprint.java +++ b/src/main/java/art/arcane/iris/modules/floating/IslandFootprint.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; /** * Where an object stands, in its own block positions: the columns holding a solid block ({@link #column} packs each), the diff --git a/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java b/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java new file mode 100644 index 000000000..a48f2fa49 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java @@ -0,0 +1,114 @@ +/* + * 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.modules.objects; + +import art.arcane.iris.builtin.MatterMantle; +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.MatterSlice; + +import java.util.Optional; + +/** + * The voids the cave carver planned in the mantle around the chunk being placed, which cave objects anchor in. Heights + * are above the dimension's bottom; outside the mantle the invocation reaches nothing is carved. + */ +public final class CarvedSpace { + private static final int CHUNK_SHIFT = 4; + private static final int SECTION_SHIFT = 4; + private static final int SECTION_HEIGHT = 16; + private static final int LOCAL_MASK = 15; + private static final byte CARVED = 1; + + private final MatterMantle mantle; + private final int worldHeight; + + public CarvedSpace(MatterMantle mantle, int worldHeight) { + this.mantle = mantle; + this.worldHeight = worldHeight; + } + + /** Whether the position is carved. */ + public boolean isCarved(int x, int y, int z) { + return cavernData(x, y, z) != null; + } + + /** Whether each height from 0 up to {@code height} is carved at the column, 1 for carved and 0 for not. */ + public byte[] column(int x, int z, int height) { + int cappedHeight = Math.min(Math.max(height, 0), worldHeight); + byte[] carvedColumn = new byte[cappedHeight]; + if (cappedHeight <= 0) { + return carvedColumn; + } + MantleChunk chunk = mantle.chunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); + if (chunk == null) { + return carvedColumn; + } + int localX = x & LOCAL_MASK; + int localZ = z & LOCAL_MASK; + int lastSection = (cappedHeight - 1) >> SECTION_SHIFT; + for (int section = 0; section <= lastSection; section++) { + MatterSlice slice = cavernSlice(chunk, section); + if (slice == null) { + continue; + } + int sectionBaseY = section << SECTION_SHIFT; + int sectionMaxY = Math.min(cappedHeight, sectionBaseY + SECTION_HEIGHT); + for (int y = sectionBaseY; y < sectionMaxY; y++) { + if (slice.get(localX, y & LOCAL_MASK, localZ) != null) { + carvedColumn[y] = CARVED; + } + } + } + return carvedColumn; + } + + /** The void at the position; empty where nothing was carved. */ + public Optional cavernAt(int x, int y, int z) { + MatterCavern cavern = cavernData(x, y, z); + if (cavern == null || !cavern.isCavern()) { + return Optional.empty(); + } + return Optional.of(new Cavern(cavern.isAir(), cavern.getLiquid())); + } + + private MatterCavern cavernData(int x, int y, int z) { + if (y < 0 || y >= worldHeight) { + return null; + } + MantleChunk chunk = mantle.chunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); + if (chunk == null) { + return null; + } + MatterSlice slice = cavernSlice(chunk, y >> SECTION_SHIFT); + return slice == null ? null : slice.get(x & LOCAL_MASK, y & LOCAL_MASK, z & LOCAL_MASK); + } + + private static MatterSlice cavernSlice(MantleChunk chunk, int section) { + if (!chunk.exists(section)) { + return null; + } + Matter matter = chunk.get(section); + if (matter == null || !matter.hasSlice(MatterCavern.class)) { + return null; + } + return matter.getSlice(MatterCavern.class); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java b/src/main/java/art/arcane/iris/modules/objects/CavePlacement.java similarity index 66% rename from src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java rename to src/main/java/art/arcane/iris/modules/objects/CavePlacement.java index 221ba5b30..bf86622e7 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/CavePlacement.java +++ b/src/main/java/art/arcane/iris/modules/objects/CavePlacement.java @@ -16,25 +16,17 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; /** * The outcome of placing an object in a cave. * * @param resultY the height the object was placed at, negative when the placement rejected it - * @param commit what became of the blocks the object wrote + * @param commit what became of the blocks the object wrote; {@link TerrainTransaction.Commit#EMPTY} for a rejected + * placement, {@link TerrainTransaction.Commit#REJECTED} when some block lay outside the cave */ -public record CavePlacement(int resultY, Commit commit) { - public enum Commit { - /** The blocks were written. */ - COMMITTED, - /** The object wrote no blocks, or the placement was rejected. */ - EMPTY, - /** Some block lay outside the cave, so nothing was written. */ - REJECTED_BOUNDS - } - +public record CavePlacement(int resultY, TerrainTransaction.Commit commit) { public boolean wroteBlocks() { - return commit == Commit.COMMITTED; + return commit == TerrainTransaction.Commit.COMMITTED; } } diff --git a/src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java b/src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java new file mode 100644 index 000000000..e1c569a2a --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/CaveTransaction.java @@ -0,0 +1,86 @@ +/* + * 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.modules.objects; + +import art.arcane.volmlib.util.cache.CacheKey; +import com.volmit.placement.PlacementTerrain; + +import java.util.HashMap; +import java.util.Map; + +/** + * Holds back what a cave object writes until all of it is known to lie inside the cave: in the world, no shallower than + * the burial depth under the surface and under the cave's ceiling at its column. + */ +public final class CaveTransaction extends TerrainTransaction { + private final int worldHeight; + private final int anchorY; + private final int minDepthBelowSurface; + private final Map surfaceHeights = new HashMap<>(); + private final Map caveCeilings = new HashMap<>(); + + /** @param worldHeight the dimension's height in blocks */ + public CaveTransaction(PlacementTerrain delegate, int worldHeight, int anchorY, int minDepthBelowSurface) { + super(delegate); + this.worldHeight = worldHeight; + this.anchorY = anchorY; + this.minDepthBelowSurface = Math.max(0, minDepthBelowSurface); + } + + /** The first height above the anchor that the cave does not reach at the column. */ + public int caveCeiling(int x, int z) { + return caveCeilings.computeIfAbsent(CacheKey.key(x, z), ignored -> findCaveCeiling(x, z)); + } + + /** The highest height an object buried {@code minDepthBelowSurface} under {@code surfaceY} may reach. */ + public static int maxBuriedY(int worldHeight, int surfaceY, int minDepthBelowSurface) { + return Math.min(worldHeight - 1, surfaceY - Math.max(0, minDepthBelowSurface)); + } + + @Override + protected boolean accepts(int x, int y, int z) { + if (y < 0 || y >= worldHeight) { + return false; + } + if (y > maxBuriedY(worldHeight, surfaceHeight(x, z), minDepthBelowSurface)) { + return false; + } + return y < caveCeiling(x, z); + } + + private int surfaceHeight(int x, int z) { + return surfaceHeights.computeIfAbsent(CacheKey.key(x, z), ignored -> delegate().highest(x, z, true)); + } + + 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, surfaceHeight(x, z))); + for (int y = anchorY + 1; y <= scanLimit; y++) { + if (!delegate().isCarved(x, y, z)) { + return y; + } + } + return Math.min(worldHeight, scanLimit + 1); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/Cavern.java b/src/main/java/art/arcane/iris/modules/objects/Cavern.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/Cavern.java rename to src/main/java/art/arcane/iris/modules/objects/Cavern.java index 8a524fea3..032ee8011 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/Cavern.java +++ b/src/main/java/art/arcane/iris/modules/objects/Cavern.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; /** * A carved void of the mantle, as the cave carver left it. diff --git a/src/main/java/art/arcane/iris/modules/objects/Declaration.java b/src/main/java/art/arcane/iris/modules/objects/Declaration.java new file mode 100644 index 000000000..73ae17e85 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/Declaration.java @@ -0,0 +1,53 @@ +/* + * 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.modules.objects; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; + +/** + * One region's or biome's declaration of settings, named by the id a {@link com.volmit.world.BiomeSample} gives the + * region or biome ({@code overworld:desert/dunes}) rather than the source id of its settings entry + * ({@code overworld:biome/desert/dunes}). + */ +public record Declaration(Level level, ResourceId id, F settings) { + private static final char KIND_SEPARATOR = '/'; + + /** Every region and every reachable biome of {@code world}'s dimension that declares the settings, regions first. */ + public static List> allOf(PackWorld world, Class type) { + List> found = new ArrayList<>(); + for (Entry entry : world.settings().declared(type)) { + if (entry.level() == Level.REGION || entry.level() == Level.BIOME) { + found.add(new Declaration<>(entry.level(), sampleId(entry.source()), entry.value())); + } + } + return found; + } + + private static ResourceId sampleId(ResourceId source) { + String path = source.path(); + return new ResourceId(source.namespace(), path.substring(path.indexOf(KIND_SEPARATOR) + 1)); + } +} diff --git a/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java b/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java new file mode 100644 index 000000000..f4dbbab50 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java @@ -0,0 +1,101 @@ +/* + * 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.modules.objects; + +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.builtin.prepare.AxisRotationClamp; +import art.arcane.iris.builtin.prepare.ObjectRotation; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The object placement settings a placement is made with: an object placement's own, or the options a procedural object + * is scattered with, with the changes {@code iris:objects} makes for where it places them. One per world, so each + * procedural object's options are made once. + */ +public final class EffectiveSettings { + private static final double UPSIDE_DOWN_TURN_DEGREES = 180D; + private static final double QUARTER_TURN_DEGREES = 90D; + + private final Map proceduralOptions = new ConcurrentHashMap<>(); + + /** The settings {@code placement} places with, with {@code changes} made to a copy of them. */ + public ObjectPlacement of(PlacementSource placement, PlacementChanges changes) { + ObjectPlacement base = placement instanceof ObjectPlacement settings + ? settings + : proceduralOptions.computeIfAbsent((ProceduralPlacement) placement, EffectiveSettings::optionsOf); + return withChanges(base, changes); + } + + /** {@code base} with {@code changes} made to a copy of it; {@code base} itself when there are none. */ + public static ObjectPlacement withChanges(ObjectPlacement base, PlacementChanges changes) { + if (changes.isNone()) { + return base; + } + ObjectPlacement.Builder changed = base.toBuilder(); + if (changes.place() != null) { + changed.place(changes.place()); + } + if (changes.mode() != null) { + changed.mode(changes.mode()); + } + if (changes.upsideDown() != null && changes.upsideDown()) { + changed.rotation(upsideDownRotation()); + } + if (changes.carvingSupport() != null) { + changed.carvingSupport(changes.carvingSupport()); + } + if (changes.requireSurfaceSupport() != null) { + changed.requireSurfaceSupport(changes.requireSurfaceSupport()); + } + if (changes.surfaceSupportBuffer() != null) { + changed.surfaceSupportBuffer(changes.surfaceSupportBuffer()); + } + if (changes.forcePlace() != null) { + changed.forcePlace(changes.forcePlace()); + } + return changed.build(); + } + + /** The options a procedural object is scattered with, as an object placement. */ + private static ObjectPlacement optionsOf(ProceduralPlacement procedural) { + return ObjectPlacement.builder() + .mode(procedural.mode()) + .rotation(procedural.rotation()) + .clamp(procedural.clamp()) + .carvingSupport(procedural.carvingSupport()) + .underwater(procedural.underwater()) + .translate(procedural.translate()) + .stiltSettings(procedural.stiltSettings().orElse(null)) + .vacuumSettings(procedural.vacuumSettings().orElse(null)) + .chance(procedural.chance()) + .density(procedural.density()) + .surfaceSupportBuffer(procedural.surfaceSupportBuffer()) + .build(); + } + + private static ObjectRotation upsideDownRotation() { + return ObjectRotation.of(true, + AxisRotationClamp.of(true, true, UPSIDE_DOWN_TURN_DEGREES, UPSIDE_DOWN_TURN_DEGREES, QUARTER_TURN_DEGREES), + AxisRotationClamp.of(true, false, 0D, 0D, QUARTER_TURN_DEGREES), + new AxisRotationClamp()); + } +} diff --git a/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java b/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java new file mode 100644 index 000000000..d849582bf --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java @@ -0,0 +1,106 @@ +/* + * 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.modules.objects; + +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.StructureVolumes; + +import java.util.Objects; +import java.util.Optional; + +/** A terrain that answers everything as another does; subclasses change what they need. */ +public abstract class ForwardingTerrain implements PlacementTerrain { + private final PlacementTerrain delegate; + + protected ForwardingTerrain(PlacementTerrain delegate) { + this.delegate = Objects.requireNonNull(delegate, "delegate"); + } + + protected final PlacementTerrain delegate() { + return delegate; + } + + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return delegate.highest(x, z, ignoreFluid); + } + + @Override + public BlockState get(int x, int y, int z) { + return delegate.get(x, y, z); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + delegate.set(x, y, z, state); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + delegate.set(x, y, z, state, blockEntity); + } + + @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 isUnderwater(int x, int z) { + return delegate.isUnderwater(x, z); + } + + @Override + public int fluidHeight() { + return delegate.fluidHeight(); + } + + @Override + public boolean preventsDecay() { + return delegate.preventsDecay(); + } + + @Override + public void recordPlacement(int x, int y, int z, String placement) { + delegate.recordPlacement(x, y, z, placement); + } + + @Override + public Optional placementAt(int x, int y, int z) { + return delegate.placementAt(x, y, z); + } + + @Override + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return delegate.structureVolumes(minX, minZ, maxX, maxZ); + } + + @Override + public void mark(PlacedMarker marker) { + delegate.mark(marker); + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java b/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java similarity index 51% rename from src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java rename to src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java index 066662abc..7fd89c85a 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectBuilder.java +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java @@ -15,29 +15,49 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; + +import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; import com.volmit.object.ObjectBlock; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; import java.util.List; /** - * Builds objects block by block for a module, with blocks as the platform has them: a state the builder handed out - * keeps what the platform knows about it when a property is set or the object is built, so a content plugin's block - * stays itself. One builder serves one bake on one thread. + * Builds objects block by block for the procedural objects, with blocks as the platform has them: the registry keeps a + * content plugin's block itself when a property is set on it or the object is built ({@link BlockRegistry}). */ -public interface ObjectBuilder { +public final class ObjectBuilder { + private final BlockRegistry blocks; + private final PackObjects objects; + + public ObjectBuilder(PackResources resources) { + this.blocks = resources.blocks(); + this.objects = resources.objects(); + } + /** The platform's state for {@code key}; null when the platform has no such block. */ - BlockState block(String key); + public BlockState block(String key) { + return blocks.find(key).orElse(null); + } /** The block {@code palette} gives at the position when its noise is seeded with {@code seed}. */ - BlockState pick(PaletteSpec palette, long seed, int x, int y, int z); + public BlockState pick(PaletteSpec palette, long seed, int x, int y, int z) { + return blocks.palette(palette, seed).at(x, y, z); + } /** {@code state} with the property set, as the platform sets it. */ - BlockState withProperty(BlockState state, String name, String value); + public BlockState withProperty(BlockState state, String name, String value) { + return blocks.withProperty(state, name, value); + } /** The object of {@code blocks}, put in their order, {@code width} by {@code height} by {@code depth}, placeable like the pack's objects. */ - PlaceableObject build(String loadKey, int width, int height, int depth, List blocks); + public PlaceableObject build(String name, int width, int height, int depth, List blocks) { + return objects.build(name, width, height, depth, blocks); + } } diff --git a/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java b/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java new file mode 100644 index 000000000..ec6d049c9 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java @@ -0,0 +1,136 @@ +/* + * 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.modules.objects; + +import art.arcane.iris.builtin.LegacyStreams; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectScale; +import art.arcane.iris.builtin.objects.ScaleInterpolation; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.object.ScaleMethod; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * The pack's objects as object placements pick them: by key, scaled the way a placement scales them, and as many at a + * column as its density says, drawn from Iris's own streams so existing worlds keep their objects. + */ +public final class ObjectPool { + private static final double NO_SCALE = 1D; + private static final int MAX_SCALE_VARIANTS = 32; + + private final PackResources resources; + private final LegacyStreams streams; + + private ObjectPool(PackResources resources, LegacyStreams streams) { + this.resources = resources; + this.streams = streams; + } + + /** The objects of {@code world}'s pack. */ + public static ObjectPool of(PackWorld world) { + return new ObjectPool(world.resources(), world.extension(LegacyStreams.class).orElseThrow()); + } + + /** The random a chunk's objects are placed with. */ + public RNG chunkRandom(int chunkX, int chunkZ) { + return streams.objectChunkRandom(chunkX, chunkZ); + } + + /** The pack object {@code key} names. */ + public Optional object(String key) { + return objects().object(resources.idOf(key)); + } + + /** An object of the placement, picked with {@code rng} and scaled the way the placement scales it; empty when it has none. */ + public Optional pickScaled(ObjectPlacement placement, RNG rng) { + List keys = placement.place(); + if (keys.isEmpty()) { + return Optional.empty(); + } + return object(keys.get(rng.nextInt(keys.size()))).map(origin -> scaled(origin, placement.scale(), rng)); + } + + /** {@code origin} shrunk or grown by exactly {@code factor}, without filling between its blocks. */ + public PlaceableObject resized(PlaceableObject origin, double factor) { + return factor == NO_SCALE ? origin : objects().scaled(origin, factor, ScaleMethod.NONE); + } + + /** How many objects the placement places at the column, when its chance check passes. */ + public int density(ObjectPlacement placement, RNG rng, double x, double z) { + return streams.density(placement, rng, x, z); + } + + /** Builds the noise the placement draws its density from, so the first chunk to place it does not wait. */ + public void warm(ObjectPlacement placement, RNG rng) { + streams.density(placement, rng, 0, 0); + } + + private PlaceableObject scaled(PlaceableObject origin, ObjectScale scale, RNG rng) { + if (!shouldScale(scale)) { + return origin; + } + int variants = variantCount(scale); + int variant = variants == 1 ? 0 : rng.nextInt(variants); + return objects().scaled(origin, scaleAt(scale, variant, variants), methodOf(scale.interpolation())); + } + + private PackObjects objects() { + return resources.objects(); + } + + private static boolean shouldScale(ObjectScale scale) { + if (scale.size() != NO_SCALE) { + return true; + } + return scale.variations() > 0 && (scale.minimumScale() != NO_SCALE || scale.maximumScale() != NO_SCALE); + } + + /** How many evenly spread factors the scale picks from. */ + private static int variantCount(ObjectScale scale) { + if (scale.size() != NO_SCALE || scale.minimumScale() == scale.maximumScale()) { + return 1; + } + return Math.max(1, Math.min(scale.variations(), MAX_SCALE_VARIANTS)); + } + + private static double scaleAt(ObjectScale scale, int variant, int variants) { + if (scale.size() != NO_SCALE) { + return scale.size(); + } + if (scale.minimumScale() == scale.maximumScale()) { + return scale.minimumScale(); + } + return scale.minimumScale() + (((scale.maximumScale() - scale.minimumScale()) / variants) * variant); + } + + private static ScaleMethod methodOf(ScaleInterpolation interpolation) { + return switch (interpolation) { + case NONE -> ScaleMethod.NONE; + case TRILINEAR -> ScaleMethod.TRILINEAR; + case TRICUBIC -> ScaleMethod.TRICUBIC; + case TRIHERMITE -> ScaleMethod.TRIHERMITE; + }; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java b/src/main/java/art/arcane/iris/modules/objects/ObjectSize.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java rename to src/main/java/art/arcane/iris/modules/objects/ObjectSize.java index 62a0119dc..178479646 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectSize.java +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectSize.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; /** The size of an object, in blocks. */ public record ObjectSize(int width, int height, int depth) { diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java b/src/main/java/art/arcane/iris/modules/objects/PlacementChanges.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java rename to src/main/java/art/arcane/iris/modules/objects/PlacementChanges.java index 38348fa33..a6c098223 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/PlacementChanges.java +++ b/src/main/java/art/arcane/iris/modules/objects/PlacementChanges.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java b/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java rename to src/main/java/art/arcane/iris/modules/objects/PlacementTags.java index cefef139c..f2f095030 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/PlacementTags.java +++ b/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; /** * What a placement writes into the mantle besides the blocks, beside each block of the object. diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java rename to src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java index 6f2adeb0e..c8be43476 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ProceduralPlacement.java +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java @@ -16,9 +16,11 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.objects.PlacementSource; +import com.volmit.object.PlaceableObject; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.builtin.prepare.ObjectRotation; diff --git a/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java b/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java new file mode 100644 index 000000000..fbe9bb8c9 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java @@ -0,0 +1,161 @@ +/* + * 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.modules.objects; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementTerrain; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Holds back what an object writes until all of it is known to be acceptable, then writes everything in the order it was + * written, or nothing. Reads see the held writes. Subclasses say which blocks are acceptable. + */ +public abstract class TerrainTransaction extends ForwardingTerrain { + private final List writes = new ArrayList<>(); + private final Map heldBlocks = new HashMap<>(); + private int blockWrites; + + public enum Commit { + /** Everything was written. */ + COMMITTED, + /** No block was written, so nothing was. */ + EMPTY, + /** Some write was not acceptable, so nothing was written. */ + REJECTED + } + + protected TerrainTransaction(PlacementTerrain delegate) { + super(delegate); + } + + /** Whether the transaction may write the block. */ + protected abstract boolean accepts(int x, int y, int z); + + public final Commit commit() { + if (blockWrites == 0) { + discard(); + return Commit.EMPTY; + } + for (Write write : writes) { + BlockPosition position = write.position(); + if (!accepts(position.x(), position.y(), position.z())) { + discard(); + return Commit.REJECTED; + } + } + for (Write write : writes) { + write.applyTo(delegate()); + } + discard(); + return Commit.COMMITTED; + } + + public final void discard() { + writes.clear(); + heldBlocks.clear(); + blockWrites = 0; + } + + @Override + public BlockState get(int x, int y, int z) { + BlockState held = heldBlocks.get(new BlockPosition(x, y, z)); + return held == null ? delegate().get(x, y, z) : held; + } + + @Override + public void set(int x, int y, int z, BlockState state) { + holdBlock(new BlockWrite(new BlockPosition(x, y, z), state, null)); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + holdBlock(new BlockWrite(new BlockPosition(x, y, z), state, blockEntity)); + } + + @Override + public void recordPlacement(int x, int y, int z, String placement) { + writes.add(new PlacementRecord(new BlockPosition(x, y, z), placement)); + } + + @Override + public Optional placementAt(int x, int y, int z) { + BlockPosition position = new BlockPosition(x, y, z); + for (int index = writes.size() - 1; index >= 0; index--) { + if (writes.get(index) instanceof PlacementRecord record && record.position().equals(position)) { + return Optional.of(record.placement()); + } + } + return delegate().placementAt(x, y, z); + } + + @Override + public void mark(PlacedMarker marker) { + writes.add(new MarkerWrite(marker)); + } + + private void holdBlock(BlockWrite write) { + writes.add(write); + heldBlocks.put(write.position(), write.state()); + blockWrites++; + } + + private sealed interface Write permits BlockWrite, PlacementRecord, MarkerWrite { + BlockPosition position(); + + void applyTo(PlacementTerrain terrain); + } + + private record BlockWrite(BlockPosition position, BlockState state, BlockEntityData blockEntity) implements Write { + @Override + public void applyTo(PlacementTerrain terrain) { + if (blockEntity == null) { + terrain.set(position.x(), position.y(), position.z(), state); + } else { + terrain.set(position.x(), position.y(), position.z(), state, blockEntity); + } + } + } + + private record PlacementRecord(BlockPosition position, String placement) implements Write { + @Override + public void applyTo(PlacementTerrain terrain) { + terrain.recordPlacement(position.x(), position.y(), position.z(), placement); + } + } + + private record MarkerWrite(PlacedMarker marker) implements Write { + @Override + public BlockPosition position() { + return marker.position(); + } + + @Override + public void applyTo(PlacementTerrain terrain) { + terrain.mark(marker); + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java b/src/main/java/art/arcane/iris/modules/placement/BlockTraits.java similarity index 80% rename from src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java rename to src/main/java/art/arcane/iris/modules/placement/BlockTraits.java index 89cc8057b..49ba4e5df 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/BlockTraits.java +++ b/src/main/java/art/arcane/iris/modules/placement/BlockTraits.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.placement; +package art.arcane.iris.modules.placement; +import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; @@ -25,30 +26,30 @@ import java.util.IdentityHashMap; import java.util.Map; /** - * The traits of the block states one placement handles, asked of the placement once per state instance. A placement + * The traits of the block states one placement handles, asked of the block registry once per state instance. A placement * reads the same few states over and over and the platform looks every state up by its value, so the answers are kept by * identity. For one placement on one thread. */ public final class BlockTraits { - private final ObjectPlacement placement; + private final BlockRegistry blocks; private final Map answers = new IdentityHashMap<>(); - public BlockTraits(ObjectPlacement placement) { - this.placement = placement; + public BlockTraits(BlockRegistry blocks) { + this.blocks = blocks; } public boolean has(BlockState state, BlockTrait trait) { - return answers.computeIfAbsent(state, ignored -> new TraitAnswers()).has(placement, state, trait); + return answers.computeIfAbsent(state, ignored -> new TraitAnswers()).has(blocks, state, trait); } private static final class TraitAnswers { private int asked; private int held; - boolean has(ObjectPlacement placement, BlockState state, BlockTrait trait) { + boolean has(BlockRegistry blocks, BlockState state, BlockTrait trait) { int flag = 1 << trait.ordinal(); if ((asked & flag) == 0) { - if (placement.hasTrait(state, trait)) { + if (blocks.hasTrait(state, trait)) { held |= flag; } asked |= flag; diff --git a/src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java b/src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java new file mode 100644 index 000000000..272da3ed2 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/EdgeSimplex.java @@ -0,0 +1,86 @@ +/* + * 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.modules.placement; + +import art.arcane.volmlib.util.math.RNG; + +/** + * Single-octave simplex noise over a plane that swings between -1 and 1, the rolling wave of a terrain bend's edge. It + * is a copy of the two-dimensional simplex of Iris's {@code SimplexNoise} and draws exactly what that draws for the same + * seed, so worlds bent before keep their edges; Iris pins the two against each other in a test. + */ +public final class EdgeSimplex { + private static final double FREQUENCY = 0.01; + private static final double F2 = 0.5 * (Math.sqrt(3.0) - 1.0); + private static final double G2 = (3.0 - Math.sqrt(3.0)) / 6.0; + private static final long X_PRIME = 1619; + private static final long Y_PRIME = 31337; + private static final long HASH_MULTIPLIER = 60493; + private static final double SCALE = 50; + private static final double[] GRADIENTS = {-1D, -1D, 1D, -1D, -1D, 1D, 1D, 1D, 0D, -1D, -1D, 0D, 0D, 1D, 1D, 0D}; + + private final long seed; + + public EdgeSimplex(long seed) { + this.seed = new RNG(seed).lmax(); + } + + public double signed(double x, double z) { + return simplex(x * FREQUENCY, z * FREQUENCY); + } + + private double simplex(double x, double y) { + double skew = (x + y) * F2; + long i = floor(x + skew); + long j = floor(y + skew); + double unskew = (i + j) * G2; + double x0 = x - (i - unskew); + double y0 = y - (j - unskew); + long i1 = x0 > y0 ? 1 : 0; + long j1 = x0 > y0 ? 0 : 1; + double x1 = x0 - i1 + G2; + double y1 = y0 - j1 + G2; + double x2 = x0 - 1 + (2 * G2); + double y2 = y0 - 1 + (2 * G2); + return SCALE * (corner(i, j, x0, y0) + corner(i + i1, j + j1, x1, y1) + corner(i + 1, j + 1, x2, y2)); + } + + private double corner(long cellX, long cellY, double x, double y) { + double falloff = 0.5 - x * x - y * y; + if (falloff < 0) { + return 0; + } + falloff *= falloff; + return falloff * falloff * gradient(cellX, cellY, x, y); + } + + private double gradient(long cellX, long cellY, double x, double y) { + long hash = seed; + hash ^= X_PRIME * cellX; + hash ^= Y_PRIME * cellY; + hash = hash * hash * hash * HASH_MULTIPLIER; + hash = (hash >> 13) ^ hash; + int index = ((int) hash & 7) << 1; + return (x * GRADIENTS[index]) + (y * GRADIENTS[index + 1]); + } + + private static long floor(double value) { + return value >= 0 ? (long) value : (long) value - 1; + } +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java b/src/main/java/art/arcane/iris/modules/placement/MarkerRule.java similarity index 60% rename from src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java rename to src/main/java/art/arcane/iris/modules/placement/MarkerRule.java index 560ddae3b..1258fc375 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/MarkerRule.java +++ b/src/main/java/art/arcane/iris/modules/placement/MarkerRule.java @@ -16,22 +16,22 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.placement; +package art.arcane.iris.modules.placement; import com.volmit.block.BlockState; import java.util.List; -/** One marker of a placement, an entry of its {@code markers}: the blocks it marks and how many. */ -public interface MarkerRule { - /** The pack's marker to add. */ - String marker(); - - /** The blocks to mark. */ - List targets(); - - /** Whether a block must match a target exactly; otherwise its material is enough. */ - boolean exact(); - - int maximum(); +/** + * One marker of a placement, an entry of its {@code markers}, with its blocks resolved in the pack. + * + * @param marker the pack's marker to add + * @param targets the blocks to mark + * @param exact whether a block must match a target exactly; otherwise its material is enough + * @param maximum how many blocks to mark at most + */ +public record MarkerRule(String marker, List targets, boolean exact, int maximum) { + public MarkerRule { + targets = List.copyOf(targets); + } } diff --git a/src/main/java/art/arcane/iris/modules/placement/ObjectShape.java b/src/main/java/art/arcane/iris/modules/placement/ObjectShape.java new file mode 100644 index 000000000..a7bf9451b --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/ObjectShape.java @@ -0,0 +1,73 @@ +/* + * 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.modules.placement; + +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** The object being placed as the placement stages see it: its declared size, the block its offsets count from, and where it must stand on solid ground. */ +public final class ObjectShape { + private final PlaceableObject object; + private final PackWorld world; + + ObjectShape(PlaceableObject object, PackWorld world) { + this.object = object; + this.world = world; + } + + public int width() { + return object.width(); + } + + public int height() { + return object.height(); + } + + public int depth() { + return object.depth(); + } + + /** The block the object's offsets count from, relative to its corner. */ + public int centerX() { + return object.center().x(); + } + + public int centerY() { + return object.center().y(); + } + + public int centerZ() { + return object.center().z(); + } + + /** The pack object this is, by the id the pack gives its name. */ + public Optional id() { + return Optional.of(world.resources().idOf(object.name())); + } + + /** The columns of the object's lowest solid layer, as offsets from its anchor before any transform; empty for the origin only. */ + public List surfaceSupportOffsets() { + return SurfaceSupportOffsets.of(world).of(object, world.resources().blocks()); + } +} diff --git a/src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java b/src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java new file mode 100644 index 000000000..efaa7fcb4 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/PlacementSettings.java @@ -0,0 +1,169 @@ +/* + * 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.modules.placement; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; +import art.arcane.iris.builtin.carve.CarvingMode; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectTranslate; +import art.arcane.iris.builtin.prepare.SlopeClip; +import art.arcane.iris.builtin.stilt.StiltSettings; +import art.arcane.iris.builtin.vacuum.VacuumSettings; +import art.arcane.iris.builtin.validate.ObjectLimit; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** The settings of one object placement as the placement stages read them, its markers and collisions resolved in the pack. */ +public final class PlacementSettings { + private final ObjectPlacement config; + private final PackResources resources; + + public PlacementSettings(ObjectPlacement config, PackResources resources) { + this.config = config; + this.resources = resources; + } + + public boolean forcePlace() { + return config.forcePlace(); + } + + public SlopeClip slopeCondition() { + return config.slopeCondition(); + } + + public boolean rotateTowardsSlope() { + return config.rotateTowardsSlope(); + } + + public ObjectRotation rotation() { + return config.rotation(); + } + + public ObjectTranslate translate() { + return config.translate(); + } + + public ObjectPlaceMode mode() { + return config.mode(); + } + + public boolean fromBottom() { + return config.fromBottom(); + } + + /** Whether the object places from the ground up instead of by height checks. */ + public boolean bottom() { + return config.bottom(); + } + + public CarvingMode carvingSupport() { + return config.carvingSupport(); + } + + public boolean underwater() { + return config.underwater(); + } + + public boolean onwater() { + return config.onwater(); + } + + public boolean requireSurfaceSupport() { + return config.requireSurfaceSupport(); + } + + public int surfaceSupportBuffer() { + return config.surfaceSupportBuffer(); + } + + public int surfaceSupportDepth() { + return config.surfaceSupportDepth(); + } + + public ObjectLimit clamp() { + return config.clamp(); + } + + /** Whether air is placed before the object. */ + public boolean bore() { + return config.bore(); + } + + public int boreExtendMinY() { + return config.boreExtendMinY(); + } + + public int boreExtendMaxY() { + return config.boreExtendMaxY(); + } + + public List edit() { + return config.edit(); + } + + public boolean waterloggable() { + return config.waterloggable(); + } + + public boolean meld() { + return config.meld(); + } + + public List markers() { + return config.markers().stream() + .map(marker -> new MarkerRule(marker.marker(), marker.mark().stream().map(spec -> resources.blocks().resolve(spec)).toList(), + marker.exact(), marker.maximumMarkers())) + .toList(); + } + + public Optional stilt() { + return config.stiltSettings(); + } + + public Optional vacuum() { + return config.vacuumSettings(); + } + + /** The snow filter's depth, 0 for none. */ + public double snow() { + return config.snow(); + } + + /** The pack objects the placement may overlap even when {@link #forbiddenCollisions()} names them. */ + public Set allowedCollisions() { + return objectIds(config.allowedCollisions()); + } + + /** The pack objects the placement may not overlap. */ + public Set forbiddenCollisions() { + return objectIds(config.forbiddenCollisions()); + } + + private Set objectIds(List keys) { + return keys.stream().filter(Objects::nonNull).map(resources::idOf).collect(Collectors.toUnmodifiableSet()); + } +} diff --git a/src/main/java/art/arcane/iris/modules/placement/PlacementStages.java b/src/main/java/art/arcane/iris/modules/placement/PlacementStages.java new file mode 100644 index 000000000..a7c088427 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/PlacementStages.java @@ -0,0 +1,121 @@ +/* + * 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.modules.placement; + +import art.arcane.iris.builtin.anchor.AnchorHeight; +import art.arcane.iris.builtin.blocks.WrittenBlocks; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.stilt.StiltLayers; +import com.volmit.stage.BlockStage; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; + +/** + * The stages of Iris's built-in object placement modules, one nested class per module, in the order a placement runs + * them. The stage graph decides the actual order. + */ +public final class PlacementStages { + private PlacementStages() { + } + + /** Module {@code iris:prepare}: what a placement decides before it looks for its height. */ + public static final class Prepare { + /** The rotation the placement uses: the requested one, turned downhill when the settings ask to face the slope. Rejects {@code slope}. */ + public static final PlacementStage SLOPE = Stage.placement("iris:prepare/slope", ObjectRotation.class); + /** The random rotation, translation and height offset, chosen once per placement. */ + public static final PlacementStage TRANSFORMS = Stage.placement("iris:prepare/transforms", PreparedPlacement.class); + + private Prepare() { + } + } + + /** Module {@code iris:anchor}: the height an object is placed at. */ + public static final class Anchor { + /** The requested or sampled height the checks judge. Rejects {@code carving-anchor}. */ + public static final PlacementStage HEIGHT = Stage.placement("iris:anchor/height", AnchorHeight.class); + /** The height the object's blocks are written at: the checked height plus the random offset. */ + public static final PlacementStage FINAL = Stage.placement("iris:anchor/final", AnchorHeight.class); + + private Anchor() { + } + } + + /** Module {@code iris:validate}: the checks that reject a placement before anything is written, in this order. */ + public static final class Validate { + /** Rejects {@code bedrock-anchor} and {@code surface-support}. */ + public static final PlacementStage SURFACE = Stage.placement("iris:validate/surface"); + /** Rejects {@code underwater-anchor}, {@code cave-clearance}, {@code fluid-height} and {@code height-clamp}. */ + public static final PlacementStage LIMITS = Stage.placement("iris:validate/limits"); + /** Rejects {@code native-structure}, even for placements that force their way past the other checks. */ + public static final PlacementStage STRUCTURES = Stage.placement("iris:validate/structures"); + /** Rejects {@code object-collision}. */ + public static final PlacementStage COLLISIONS = Stage.placement("iris:validate/collisions"); + + private Validate() { + } + } + + /** Module {@code iris:bore}: clearing the object's volume before its blocks are written. */ + public static final class Bore { + public static final PlacementStage CLEAR = Stage.placement("iris:bore/clear"); + + private Bore() { + } + } + + /** Module {@code iris:blocks}: writing the object's blocks. */ + public static final class Blocks { + /** Writes each object block where the placement puts it. */ + public static final BlockStage WRITE = Stage.placementBlock("iris:blocks/write", WrittenBlocks.class); + /** Marks some written blocks with the placement's markers. */ + public static final PlacementStage MARKERS = Stage.placement("iris:blocks/markers"); + /** Milestone: stages requiring it run after the object and its markers are written. */ + public static final PlacementStage COMPLETE = Stage.placement("iris:blocks/complete"); + + private Blocks() { + } + } + + /** Module {@code iris:stilt}: the stilts of the stilt and ceiling placement modes. */ + public static final class Stilt { + /** Finds the layers to repeat. */ + public static final BlockStage LAYERS = Stage.placementBlock("iris:stilt/layers", StiltLayers.class); + /** Grows the stilt once the object is written. */ + public static final PlacementStage FILL = Stage.placement("iris:stilt/fill"); + + private Stilt() { + } + } + + /** Module {@code iris:vacuum}: bending the terrain to meet objects of the vacuum placement modes. */ + public static final class Vacuum { + public static final PlacementStage TERRAIN = Stage.placement("iris:vacuum/terrain"); + + private Vacuum() { + } + } + + /** Module {@code iris:snow}: snow on the object, after its stilt or terrain bend. */ + public static final class Snow { + public static final PlacementStage COVER = Stage.placement("iris:snow/cover"); + + private Snow() { + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java b/src/main/java/art/arcane/iris/modules/placement/PreparedPlacement.java similarity index 84% rename from src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java rename to src/main/java/art/arcane/iris/modules/placement/PreparedPlacement.java index e973a53a8..40e625caf 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/PreparedPlacement.java +++ b/src/main/java/art/arcane/iris/modules/placement/PreparedPlacement.java @@ -16,32 +16,30 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.prepare; +package art.arcane.iris.modules.placement; import art.arcane.iris.builtin.anchor.PlaceMode; import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.placement.BlockTraits; -import art.arcane.iris.builtin.placement.ObjectPlacement; -import art.arcane.iris.builtin.placement.PlacementSettings; -import art.arcane.iris.builtin.placement.PlacementTerrain; -import art.arcane.iris.builtin.placement.SurfaceWarp; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.prepare.ObjectSpinKernel; +import art.arcane.iris.builtin.prepare.TransformedBounds; import art.arcane.volmlib.util.math.IrisBlockVector; import com.volmit.block.BlockState; import com.volmit.geometry.BlockPosition; /** - * What one placement chose before it is anchored: the settings it uses, the rotation it ended up with, the terrain - * that answers its height, water and carving questions, its random spin and height offsets, and the bounds of the - * transformed object around its anchor. Object blocks are transformed by rotating them, flipping them for a ceiling - * hang and translating them. + * What one placement chose before it is anchored: the placement it belongs to, the settings it uses, the rotation it + * ended up with, the terrain that answers its height, water and carving questions, its random spin and height offsets, + * and the bounds of the transformed object around its anchor. Object blocks are transformed by rotating them, flipping + * them for a ceiling hang and translating them. */ public final class PreparedPlacement { - private final ObjectPlacement placement; + private final RunningPlacement placement; private final PlacementSettings settings; private final PlaceMode mode; private final ObjectRotation rotation; private final BlockTraits traits; - private final PlacementTerrain terrain; + private final StageTerrain terrain; private final ObjectSpinKernel spin; private final int spinX; private final int spinY; @@ -55,7 +53,7 @@ public final class PreparedPlacement { private final SurfaceWarp surfaceWarp; /** Everything the preparation worked out; {@code translation} and {@code surfaceWarp} are null when the placement has none. */ - public PreparedPlacement(ObjectPlacement placement, ObjectRotation rotation, BlockTraits traits, PlacementTerrain terrain, + public PreparedPlacement(RunningPlacement placement, ObjectRotation rotation, BlockTraits traits, StageTerrain terrain, ObjectSpinKernel spin, int spinX, int spinY, int spinZ, IrisBlockVector translation, int rotatedCenterY, int translatedCenterY, int randomY, int warpMargin, TransformedBounds bounds, SurfaceWarp surfaceWarp) { this.placement = placement; @@ -77,6 +75,11 @@ public final class PreparedPlacement { this.surfaceWarp = surfaceWarp; } + /** The placement being run. */ + public RunningPlacement placement() { + return placement; + } + /** The settings the placement was asked for; the rotation may differ, see {@link #rotation()}. */ public PlacementSettings settings() { return settings; @@ -93,7 +96,7 @@ public final class PreparedPlacement { } /** Answers height, water and carving questions; a heightmap placement answers heights from its noise. */ - public PlacementTerrain terrain() { + public StageTerrain terrain() { return terrain; } diff --git a/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java b/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java new file mode 100644 index 000000000..6f14cbc36 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java @@ -0,0 +1,185 @@ +/* + * 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.modules.placement; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.LegacyStreams; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.block.BlockTurn; +import com.volmit.geometry.BlockPosition; +import com.volmit.placement.PlacementContext; +import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.Optional; + +/** + * The object placement being run, as Iris's built-in placement stages see it: what is placed and with which settings + * ({@link ObjectRun}, the run's input), the terrain it is placed on, and the block operations of the pack's registry. + * Heights are above the dimension's bottom. + */ +public final class RunningPlacement { + private static final double QUARTER_TURN_DEGREES = 90D; + private static final double FULL_TURN_DEGREES = 360D; + + private final PlacementContext context; + private final ObjectRun run; + private final ObjectShape object; + private final PlacementSettings settings; + private final StageTerrain terrain; + + private RunningPlacement(PlacementContext context, ObjectRun run) { + this.context = context; + this.run = run; + this.object = new ObjectShape(run.object(), context.world()); + this.settings = new PlacementSettings(run.settings(), context.world().resources()); + this.terrain = StageTerrain.of(context); + } + + /** The placement {@code context} runs. */ + public static RunningPlacement of(PlacementContext context) { + ObjectRun run = context.input(ObjectRun.class).orElseThrow(() -> new IllegalStateException( + "Iris's object placement stages place an object run, and this placement was started without one")); + return new RunningPlacement(context, run); + } + + public ObjectShape object() { + return object; + } + + /** The settings as the caller passed them; the stages derive what they change (the rotation) themselves. */ + public PlacementSettings settings() { + return settings; + } + + public int x() { + return run.x(); + } + + /** The height the caller asked for, negative when the placement samples it. */ + public int requestedY() { + return run.requestedY(); + } + + public int z() { + return run.z(); + } + + /** The cave the object is placed in; empty outside caves. */ + public Optional cave() { + return run.cave(); + } + + /** Answers the questions of the terrain the placement was asked to place on. */ + public StageTerrain terrain() { + return terrain; + } + + /** + * The terrain the placement anchors against: {@link #terrain()}, or, when the settings place on a heightmap, the same + * terrain with its heights from the heightmap's noise, seeded from {@code rng}. + */ + public StageTerrain terrainFor(RNG rng) { + ObjectPlacement config = run.settings(); + if (config.heightmap().isEmpty()) { + return terrain; + } + long heightmapSeed = rng.nextLong() + run.requestedY() + run.z() - run.x(); + LegacyStreams streams = world().extension(LegacyStreams.class).orElseThrow(); + return terrain.withHeights((x, z) -> streams.heightmapSurface(config, heightmapSeed, x, z)); + } + + /** + * The noise that warps the placement's columns; empty when the settings do not warp. A generated world seeds it from + * the world, so every placement of the world warps alike; a placement without one seeds it from {@code rng}. + */ + public Optional surfaceWarp(RNG rng) { + ObjectPlacement config = run.settings(); + if (!ObjectRun.warps(config.warp())) { + return Optional.empty(); + } + PackWorld world = world(); + long seed = world.running().isPresent() ? world.seed(IrisSeedPurposes.OBJECT_WARP) : rng.getSeed(); + return Optional.of(new SurfaceWarp(world.resources().noise().sampler(config.warp(), seed), config.warp().multiplier())); + } + + /** {@code state} turned with the object by {@code rotation}, as the platform turns stairs, logs and other facing blocks. */ + public BlockState rotate(BlockState state, ObjectRotation rotation, int spinX, int spinY, int spinZ) { + if (!rotation.canRotate()) { + return state; + } + int turnsX = wholeQuarterTurns(spinX); + int turnsY = wholeQuarterTurns(spinY); + int turnsZ = wholeQuarterTurns(spinZ); + BlockTurn turn = (x, y, z) -> { + IrisBlockVector turned = rotation.rotate(new IrisBlockVector(x, y, z), turnsX, turnsY, turnsZ); + return new BlockTurn.Direction(turned.getX(), turned.getY(), turned.getZ()); + }; + return blocks().rotate(state, turn); + } + + /** {@code update} laid over {@code base}: the platform's merge of two states of one block, else {@code update}. */ + public BlockState merge(BlockState base, BlockState update) { + return blocks().merge(base, update); + } + + /** Whether {@code state} matches {@code other} as the platform compares them. */ + public boolean matches(BlockState state, BlockState other) { + return blocks().matches(state, other); + } + + public boolean hasTrait(BlockState state, BlockTrait trait) { + return blocks().hasTrait(state, trait); + } + + /** The resources of the object's pack, where the placement's markers are found. */ + public PackResources resources() { + return world().resources(); + } + + /** Reports a buffered write as one of the object's own blocks, which the placing module reads once the object is placed. */ + public void objectBlockWritten(BlockPosition position) { + run.objectBlockWritten(position); + } + + /** Reports the height the object was anchored at, which the placement returns to its caller. */ + public void anchoredAt(int y) { + run.anchoredAt(y); + } + + private BlockRegistry blocks() { + return world().resources().blocks(); + } + + private PackWorld world() { + return context.world(); + } + + /** The spin in whole quarter turns, as the platform turns blocks: any part of a quarter turn counts as one. */ + private static int wholeQuarterTurns(int degrees) { + return (int) (QUARTER_TURN_DEGREES * Math.ceil(Math.abs((degrees % FULL_TURN_DEGREES) / QUARTER_TURN_DEGREES))); + } +} diff --git a/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java b/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java new file mode 100644 index 000000000..55130be38 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java @@ -0,0 +1,132 @@ +/* + * 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.modules.placement; + +import art.arcane.iris.builtin.structure.StructurePlacementMarker; +import art.arcane.iris.modules.blocks.SmartBoreDebugSettings; +import com.volmit.placement.PlacementContext; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.StructureVolumes; +import com.volmit.resource.ResourceId; +import com.volmit.world.TerrainSampler; + +import java.util.Optional; +import java.util.function.IntBinaryOperator; + +/** + * What a placement stage asks of the terrain and the world around it: heights, carving and water at a column, the + * terrain's shape, and the world's own facts. A placement made without a world ({@link #hasWorld()} is false) answers + * its terrain questions from the placement's terrain alone. + */ +public final class StageTerrain { + private static final String PROCEDURAL_PREFIX = "procedural/"; + + private final PlacementTerrain terrain; + private final PlacementContext context; + private final IntBinaryOperator heightmap; + + private StageTerrain(PlacementTerrain terrain, PlacementContext context, IntBinaryOperator heightmap) { + this.terrain = terrain; + this.context = context; + this.heightmap = heightmap; + } + + static StageTerrain of(PlacementContext context) { + return new StageTerrain(context.placementTerrain(), context, null); + } + + /** This terrain with its heights from {@code heightmap}, for a placement that sits on a virtual heightmap. */ + StageTerrain withHeights(IntBinaryOperator heightmap) { + return new StageTerrain(terrain, context, heightmap); + } + + /** The surface height of the column, counting fluid unless {@code ignoreFluid}. */ + public int highest(int x, int z, boolean ignoreFluid) { + return heightmap != null ? heightmap.applyAsInt(x, z) : terrain.highest(x, z, ignoreFluid); + } + + public boolean isCarved(int x, int y, int z) { + return terrain.isCarved(x, y, z); + } + + /** Whether the block is real, solid ground; the height field alone cannot say at mantle time. */ + public boolean isSurfaceSolid(int x, int y, int z) { + return terrain.isSurfaceSolid(x, y, z); + } + + public boolean isUnderwater(int x, int z) { + return terrain.isUnderwater(x, z); + } + + /** The height up to which the dimension is filled with fluid. */ + public int fluidHeight() { + return terrain.fluidHeight(); + } + + /** Whether leaves the placement writes never decay. */ + public boolean preventsDecay() { + return terrain.preventsDecay(); + } + + /** Whether bored air is written as a visible block, to see where smart boring bored. */ + public boolean debugsSmartBore(int x, int z) { + return context.settings().at(SmartBoreDebugSettings.class, x, z).dimension().map(SmartBoreDebugSettings::show).orElse(false); + } + + /** Whether the placement is made in a world the host generates, rather than a tool's world. */ + public boolean hasWorld() { + return context.world().running().isPresent(); + } + + /** The terrain's slope at the column, as the dimension's slope field gives it. */ + public double slopeAt(int x, int z) { + return sampler().column(x, z).slope(); + } + + /** The terrain height at a position between columns: the height of the column the position lies in, counted toward zero. */ + public double heightAt(double x, double z) { + return sampler().surfaceY((int) x, (int) z); + } + + /** The dimension's height in blocks. */ + public int worldHeight() { + return sampler().bounds().maxY(); + } + + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return terrain.structureVolumes(minX, minZ, maxX, maxZ); + } + + /** The pack object placed at the block; empty when none was, or when a procedural object was. */ + public Optional objectAt(int x, int y, int z) { + Optional recorded = terrain.placementAt(x, y, z); + if (recorded.isEmpty()) { + return Optional.empty(); + } + StructurePlacementMarker.Decoded marker = StructurePlacementMarker.decode(recorded.get()); + if (marker == null || marker.objectKey().startsWith(PROCEDURAL_PREFIX)) { + return Optional.empty(); + } + return Optional.of(context.world().resources().idOf(marker.objectKey())); + } + + private TerrainSampler sampler() { + return context.terrain(); + } +} diff --git a/src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java b/src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java new file mode 100644 index 000000000..a6927511d --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/SurfaceSupportOffsets.java @@ -0,0 +1,113 @@ +/* + * 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.modules.placement; + +import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.world.PackWorld; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The columns of each object's lowest solid layer, worked out once per object of a world and kept while the object is: an + * object stands on these when its placement needs surface support. Foliage does not count as solid. + */ +final class SurfaceSupportOffsets { + private final ReferenceQueue collected = new ReferenceQueue<>(); + private final Map> offsets = new ConcurrentHashMap<>(); + + static SurfaceSupportOffsets of(PackWorld world) { + return world.state(SurfaceSupportOffsets.class, ignored -> new SurfaceSupportOffsets()); + } + + /** {@code blocks} tells which of the object's blocks are solid. */ + List of(PlaceableObject object, BlockRegistry blocks) { + forgetCollected(); + return offsets.computeIfAbsent(new ObjectKey(object, collected), ignored -> lowestSolidLayer(object, blocks)); + } + + private static List lowestSolidLayer(PlaceableObject object, BlockRegistry blocks) { + Map supporting = new HashMap<>(); + int lowestY = Integer.MAX_VALUE; + List layer = new ArrayList<>(); + for (ObjectBlock block : object.geometry().blocks()) { + if (!supporting.computeIfAbsent(block.state(), state -> supports(state, blocks))) { + continue; + } + BlockPosition position = block.position(); + if (position.y() < lowestY) { + lowestY = position.y(); + layer.clear(); + } + if (position.y() == lowestY) { + layer.add(new IrisBlockVector(position.x(), position.y(), position.z())); + } + } + return List.copyOf(layer); + } + + private static boolean supports(BlockState state, BlockRegistry blocks) { + return blocks.hasTrait(state, BlockTrait.SOLID) && !blocks.hasTrait(state, BlockTrait.FOLIAGE); + } + + private void forgetCollected() { + Object gone; + while ((gone = collected.poll()) != null) { + offsets.remove((ObjectKey) gone); + } + } + + /** An object by identity, held weakly so its entry goes once the object is collected. */ + private static final class ObjectKey extends WeakReference { + private final int hash; + + private ObjectKey(PlaceableObject object, ReferenceQueue queue) { + super(object, queue); + this.hash = System.identityHashCode(object); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof ObjectKey key)) { + return false; + } + PlaceableObject object = get(); + return object != null && object == key.get(); + } + + @Override + public int hashCode() { + return hash; + } + } +} diff --git a/src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java b/src/main/java/art/arcane/iris/modules/placement/SurfaceWarp.java similarity index 64% rename from src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java rename to src/main/java/art/arcane/iris/modules/placement/SurfaceWarp.java index d5b47456a..ec234eeaf 100644 --- a/src/main/java/art/arcane/iris/builtin/placement/SurfaceWarp.java +++ b/src/main/java/art/arcane/iris/modules/placement/SurfaceWarp.java @@ -16,13 +16,18 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.placement; +package art.arcane.iris.modules.placement; -/** Noise that moves the columns of a placement sideways, so a square object warps like a flag. */ -public interface SurfaceWarp { - /** How far, in blocks, the warp may move a column in total. */ - double multiplier(); +import com.volmit.noise.NoiseSampler; +/** + * Noise that moves the columns of a placement sideways, so a square object warps like a flag. + * + * @param multiplier how far, in blocks, the warp may move a column in total + */ +public record SurfaceWarp(NoiseSampler noise, double multiplier) { /** The noise at the position, fitted to the range from {@code min} to {@code max}. */ - double fit(double min, double max, double x, double y, double z); + public double fit(double min, double max, double x, double y, double z) { + return min + noise.sample(x, y, z) * (max - min); + } } From 14acc4f37b3af9efcd941a3beafbff4469707261 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 01:58:47 +0100 Subject: [PATCH 110/139] Batch 7 stage 4a: floating islands shape and paint through the api FloatingWorld asks the running layout for a biome's height, and the island stage paints sky biomes with TerrainSampler.skyBiome and Mantle.setPlatformBiome. FloatingHost is deleted. --- README.md | 17 +++++---- .../iris/builtin/floating/FloatingHost.java | 37 ------------------- .../iris/engine/modifier/FloatingIslands.java | 22 ++++++++--- .../floating/FloatingIslandSample.java | 2 +- .../terrain/floating/FloatingWorld.java | 16 ++++---- 5 files changed, 33 insertions(+), 61 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java diff --git a/README.md b/README.md index 1404c8a15..4f8fe366a 100644 --- a/README.md +++ b/README.md @@ -136,10 +136,11 @@ workers: `ResolvedOre`/`ResolvedOres` (blocks and chance noise per world, `Terra (`carvingBiome`, a band's biome, a floating child's target and carving) implement `LinkedBiomes`, which is how Iris's biome tree and the biomes a dimension reaches learn of them without reading the settings classes; and `iris:carve` provides the `CaveBiomes` service (`CaveBiomeBands`), which Iris asks for the dimension's carving band at a position and for a biome's minimum cave depth. -`iris:floating` ships in the built-ins jar: `FloatingWorld` holds a world's floating children, noise and seeds, and what a jar -cannot do Iris does through `FloatingHost` (`art.arcane.iris.builtin.floating`): the surface biome of a column, a biome's -height for the `BIOME` top shape, painting the sky biome, an object's footprint and shrinking, and placing an object -floating, on an island's top or hung under it, where the jar's `IslandAnchor` says where the island face is. +`iris:floating` ships in the built-ins jar: `FloatingWorld` holds a world's floating children, noise and seeds. It asks the +API alone: the running world's layout for a column's surface biome and a biome's height for the `BIOME` top shape +(`TerrainSampler.biomeHeight`), the chunk's terrain for a child's sky biome (`skyBiome`), which it writes with +`Mantle.setPlatformBiome`, and `PackWorld.placements()` to place an object floating, on an island's top or hung under it, +where the jar's `IslandAnchor` says where the island face is. Packs write each settings feature under the short key it declares: `deposits` (dimension, region, biome; a list), `decorators` (biome; a list), `importedStructures` (dimension; an object of `disabled`, `adjustments` and the rest) and `structures` @@ -165,7 +166,7 @@ Iris includes this build (`includeBuild('../IrisModule')` in its `settings.gradl 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 assembler, locator, fitting and placer -(behind `StructureHost`), and the object placers behind `ObjectHost` and `FloatingHost`. A module this build holds +(behind `StructureHost`), and the placement service behind `PackWorld.placements()`. A module this build holds but the jar does not, such as `iris:structure`, is one Iris registers with its own modules (`IrisModuleHost`): its classes are then the ones Iris's own code sees. @@ -201,9 +202,9 @@ none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps e `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never -through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`ObjectHost`, -`FloatingHost`, `StructureHost`, `spawn.SpawnCooldowns`), `context.extension(X.class)` for what belongs to one invocation (`ObjectPlacement` -in a placement stage, `MatterMantle` in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out +through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`LegacyStreams`, +`StructureHost`, `spawn.SpawnCooldowns`), `context.extension(X.class)` for what belongs to one invocation (`MatterMantle` +in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), which Iris answers with the seeds its worlds always had, so existing worlds generate the same; `spawn.SpawnCooldowns` (the spawner cooldowns diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java b/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java deleted file mode 100644 index 314079b65..000000000 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingHost.java +++ /dev/null @@ -1,37 +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.builtin.floating; - -import art.arcane.volmlib.util.math.RNG; -import com.volmit.resource.ResourceId; - -/** - * What {@code iris:floating} asks of Iris beyond the API: a biome's own terrain height and the sky biome an island - * paints. Iris offers it as an extension of its worlds: {@code world.extension(FloatingHost.class)}. - */ -public interface FloatingHost { - /** The height the terrain generators of {@code biome} give the column, as Iris shapes the biome's terrain with {@code seed}. */ - double biomeHeight(ResourceId biome, int worldX, int worldZ, long seed); - - /** - * Paints the sky biome {@code biome} stands for at the column into the blocks {@code ys} of the mantle, where the biome - * pass finds it. {@code random} seeds the biome's generator the first time the biome is asked. - */ - void paintSkyBiome(ResourceId biome, int worldX, int worldZ, int[] ys, RNG random); -} diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index 0285e5b90..caab1ccab 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -45,6 +45,7 @@ import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; import com.volmit.config.FeatureSettings; import com.volmit.hunk.Hunk; +import com.volmit.mantle.Mantle; import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStageContext; import com.volmit.world.BiomeKind; @@ -55,6 +56,7 @@ import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; /** * Fills and decorates the floating islands of the dimension's floating child biomes for {@link FloatingModule}: @@ -141,7 +143,7 @@ final class FloatingIslands { } fillLocalFluid(chunk, sample, xf, zf); - paintSkyBiomes(parent, wx, wz, sample, chunk.height); + paintSkyBiomes(chunk, parent, wx, wz, sample); } private void fillLocalFluid(Chunk chunk, FloatingIslandSample sample, int xf, int zf) { @@ -397,7 +399,7 @@ final class FloatingIslands { } /** Paints, for each child the column's island is made of, its biome's sky biome into the child's solid blocks. */ - private void paintSkyBiomes(ResourceId parent, int wx, int wz, FloatingIslandSample sample, int chunkHeight) { + private void paintSkyBiomes(Chunk chunk, ResourceId parent, int wx, int wz, FloatingIslandSample sample) { try { Map> solidYsByEntry = new IdentityHashMap<>(); for (int k = 0; k <= sample.topIdx; k++) { @@ -405,7 +407,7 @@ final class FloatingIslands { continue; } int y = sample.islandBaseY + k; - if (y < 0 || y >= chunkHeight) { + if (y < 0 || y >= chunk.height) { continue; } solidYsByEntry.computeIfAbsent(sample.entryAt(k), ignored -> new ArrayList<>()).add(y); @@ -416,8 +418,13 @@ final class FloatingIslands { if (target == null) { continue; } - int[] ys = solid.getValue().stream().mapToInt(Integer::intValue).toArray(); - world.host().paintSkyBiome(target, wx, wz, ys, rng); + Optional skyBiome = chunk.terrain.skyBiome(target, wx, wz); + if (skyBiome.isEmpty()) { + continue; + } + for (int y : solid.getValue()) { + chunk.mantle.setPlatformBiome(wx, y, wz, skyBiome.get()); + } } } catch (Throwable e) { log.error("Failed to write the sky biomes of a floating island", e); @@ -438,6 +445,8 @@ final class FloatingIslands { final PaletteExplosion explosion; final ColumnSlope slope; final FloatingIslandBoundarySampler boundarySampler; + final TerrainSampler terrain; + final Mantle mantle; Chunk(ChunkStageContext context) { this.originX = context.originX(); @@ -447,7 +456,8 @@ final class FloatingIslands { this.blocks = context.world().resources().blocks(); this.settings = context.settings(); this.explosion = PaletteExplosion.of(settings, context.centreX(), context.centreZ()); - TerrainSampler terrain = context.terrain(); + this.terrain = context.terrain(); + this.mantle = context.mantle(); this.slope = (x, z) -> terrain.column((int) x, (int) z).slope(); this.boundarySampler = new FloatingIslandBoundarySampler(world::surfaceBiome); } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 0a010c637..810abe4cc 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -782,7 +782,7 @@ public final class FloatingIslandSample { if (target == null) { yield maxTopHeight / 2; } - double h = world.host().biomeHeight(target, wx, wz, world.baseSeed()); + double h = world.biomeHeight(target, wx, wz); int rounded = (int) Math.round(h); if (rounded < 0) { yield 0; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index 452451160..264708eeb 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -24,7 +24,6 @@ import art.arcane.iris.modules.carve.CarvingSettings; import art.arcane.iris.builtin.carve.CaveProfile; import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.modules.floating.FloatingChildSettings; -import art.arcane.iris.builtin.floating.FloatingHost; import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; @@ -41,14 +40,13 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; /** - * What the floating islands of one world are made from: the world's hosts, layout, noise and seeds, the floating children + * What the floating islands of one world are made from: the world's layout, noise and seeds, the floating children * each biome declares, and the {@link ResolvedFloatingChild} of every child met, one per decoded entry. One per world * ({@link #of}). */ public final class FloatingWorld { private static final long BASE_SEED_SALT = 0x5EED_F107_00F1B10CL; - private final FloatingHost host; private final PackResources resources; private final RunningWorld running; private final long baseSeed; @@ -57,9 +55,8 @@ public final class FloatingWorld { private final List dimensionCarving; private final Map resolved = new ConcurrentHashMap<>(); - FloatingWorld(FloatingHost host, PackResources resources, RunningWorld running, long terrainSeed, + FloatingWorld(PackResources resources, RunningWorld running, long terrainSeed, long carveSeed, int minWorldY, List dimensionCarving) { - this.host = host; this.resources = resources; this.running = running; this.baseSeed = terrainSeed ^ BASE_SEED_SALT; @@ -74,8 +71,8 @@ public final class FloatingWorld { } private static FloatingWorld create(PackWorld world) { - return new FloatingWorld(world.extension(FloatingHost.class).orElseThrow(), world.resources(), world.running().orElseThrow(), world.seed(IrisSeedPurposes.TERRAIN), world.seed(IrisSeedPurposes.CARVE), - world.minWorldY(), dimensionCarvingOf(world)); + return new FloatingWorld(world.resources(), world.running().orElseThrow(), world.seed(IrisSeedPurposes.TERRAIN), + world.seed(IrisSeedPurposes.CARVE), world.minWorldY(), dimensionCarvingOf(world)); } private static List dimensionCarvingOf(PackWorld world) { @@ -84,8 +81,9 @@ public final class FloatingWorld { .orElse(List.of()); } - public FloatingHost host() { - return host; + /** The height the terrain generators of {@code biome} give the column when shaped with {@link #baseSeed}. */ + public double biomeHeight(ResourceId biome, int worldX, int worldZ) { + return running.layout().biomeHeight(biome, worldX, worldZ, baseSeed); } public NoiseFactory noise() { From 826e9421238e6121dd21c09c6a868e2c595b4ada Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 02:22:19 +0100 Subject: [PATCH 111/139] Move jar-only snippet types out of the exposed package All 50 @Snippet names become iris// (iris/decorant/ decorator, iris/objects/procedural-objects, ...), which the pack snippet-path rule needs for a snippet type loaded from the jar. 43 types move from art.arcane.iris.builtin to art.arcane.iris.modules: 20 snippets (carve: CarvingEntry, CaveProfile; deposit: generator and variant; floating: FloatingChildBiome; loot: BlockDrop; objects: ProceduralObjectSettings and the coral, crystal, formation, fungus, ruin and procedural tree types), the three floating enums and 20 helpers and enums beside them. TreeOverride, TreeSize, AxisRotationClamp, the loot entry types and the spawn cluster stay: ObjectPlacement, ObjectRotation, ObjectLoot and PlacementMarker hold them, and an exposed type cannot hold a jar-only one. --- README.md | 11 +++++------ .../iris/builtin/blocks/ObjectReplace.java | 2 +- .../arcane/iris/builtin/decorant/Decorator.java | 4 ++-- .../iris/builtin/loot/ItemAttributeModifier.java | 2 +- .../iris/builtin/loot/LootEnchantment.java | 2 +- .../art/arcane/iris/builtin/loot/LootEntry.java | 2 +- .../arcane/iris/builtin/loot/LootSettings.java | 2 +- .../art/arcane/iris/builtin/loot/ObjectLoot.java | 2 +- .../iris/builtin/loot/ObjectVanillaLoot.java | 2 +- .../iris/builtin/objects/HeightmapNoise.java | 2 +- .../iris/builtin/objects/ObjectPlacement.java | 2 +- .../arcane/iris/builtin/objects/ObjectScale.java | 2 +- .../iris/builtin/objects/TreeGrowthSettings.java | 2 +- .../iris/builtin/objects/TreeOverride.java | 2 +- .../arcane/iris/builtin/objects/TreeSize.java | 2 +- .../iris/builtin/prepare/AxisRotationClamp.java | 2 +- .../iris/builtin/prepare/ObjectRotation.java | 2 +- .../iris/builtin/prepare/ObjectTranslate.java | 2 +- .../arcane/iris/builtin/prepare/SlopeClip.java | 2 +- .../arcane/iris/builtin/spawn/AmbientEffect.java | 2 +- .../iris/builtin/spawn/EffectCommands.java | 2 +- .../arcane/iris/builtin/spawn/EntitySpawn.java | 2 +- .../iris/builtin/spawn/PlacementMarker.java | 2 +- .../arcane/iris/builtin/spawn/SpawnCommand.java | 2 +- .../arcane/iris/builtin/spawn/SpawnDuration.java | 2 +- .../art/arcane/iris/builtin/spawn/SpawnRate.java | 2 +- .../iris/builtin/spawn/SpawnTimeBlock.java | 2 +- .../arcane/iris/builtin/stilt/StiltSettings.java | 2 +- .../iris/builtin/terrain/PaletteLayer.java | 4 ++-- .../iris/builtin/vacuum/VacuumSettings.java | 2 +- .../iris/builtin/validate/ObjectLimit.java | 2 +- .../arcane/iris/engine/loot/BlockDropping.java | 2 +- .../iris/engine/loot/ResolvedBlockDrop.java | 2 +- .../engine/mantle/components/CaveCarving.java | 2 +- .../engine/mantle/components/CaveSettings.java | 2 +- .../mantle/components/ChunkObjectPlacing.java | 4 ++-- .../mantle/components/EffectivePlacements.java | 2 +- .../mantle/components/FloatingObjectPlacing.java | 2 +- .../mantle/components/IrisCaveCarver3D.java | 2 +- .../engine/mantle/components/ObjectModule.java | 2 +- .../engine/mantle/components/ObjectWarmUp.java | 2 +- .../engine/mantle/components/PlacementReach.java | 2 +- .../engine/mantle/components/TreeGrowing.java | 4 ++-- .../arcane/iris/engine/modifier/CarveModule.java | 2 +- .../iris/engine/modifier/DepositModule.java | 2 +- .../iris/engine/modifier/DepositPlacer.java | 8 ++++---- .../iris/engine/modifier/FloatingIslands.java | 2 +- .../iris/engine/modifier/ResolvedDeposit.java | 6 +++--- .../engine/modifier/ResolvedDepositVariant.java | 2 +- .../procedural/ResolvedProceduralObjects.java | 4 ++-- .../object/procedural/coral/CoralGenerator.java | 2 +- .../object/procedural/coral/ResolvedCoral.java | 2 +- .../procedural/crystal/CrystalBaseBuilder.java | 2 +- .../procedural/crystal/CrystalGenerator.java | 2 +- .../procedural/crystal/CrystalGeometry.java | 2 +- .../procedural/crystal/CrystalShardBuilder.java | 4 ++-- .../procedural/crystal/ResolvedCrystal.java | 2 +- .../formation/FormationBlockResolver.java | 2 +- .../procedural/formation/FormationGenerator.java | 2 +- .../procedural/formation/FormationProfiles.java | 2 +- .../formation/FormationShapeBuilder.java | 2 +- .../procedural/formation/ResolvedFormation.java | 2 +- .../procedural/fungi/FungusCapBuilder.java | 4 ++-- .../object/procedural/fungi/FungusGenerator.java | 2 +- .../procedural/fungi/FungusShelfBuilder.java | 2 +- .../procedural/fungi/FungusStemBuilder.java | 2 +- .../object/procedural/fungi/ResolvedFungus.java | 2 +- .../object/procedural/ruin/ResolvedRuin.java | 2 +- .../procedural/ruin/RuinDecoratorApplier.java | 2 +- .../object/procedural/ruin/RuinGenerator.java | 6 +++--- .../procedural/tree/ProceduralTreeGenerator.java | 2 +- .../object/procedural/tree/ResolvedTree.java | 2 +- .../procedural/tree/TreeBlockResolver.java | 10 +++++----- .../procedural/tree/TreeCanopyBuilder.java | 14 +++++++------- .../procedural/tree/TreeDecoratorApplier.java | 4 ++-- .../object/procedural/tree/TreeFunctions.java | 8 ++++---- .../object/procedural/tree/TreePlausibility.java | 2 +- .../object/procedural/tree/TreeProfiles.java | 2 +- .../object/procedural/tree/TreeRootBuilder.java | 4 ++-- .../object/procedural/tree/TreeTrunkBuilder.java | 4 ++-- .../object/terrain/carving/CarvingResolver.java | 2 +- .../terrain/carving/CaveProfileSampler.java | 2 +- .../terrain/carving/DeclaredCaveProfiles.java | 2 +- .../terrain/carving/ResolvedCarvingEntry.java | 2 +- .../terrain/floating/FloatingIslandSample.java | 2 +- .../object/terrain/floating/FloatingWorld.java | 6 +++--- .../terrain/floating/ResolvedFloatingChild.java | 6 +++--- .../{builtin => modules}/carve/CarvingEntry.java | 4 ++-- .../iris/modules/carve/CarvingSettings.java | 1 - .../{builtin => modules}/carve/CaveProfile.java | 8 +++++--- .../deposit/DepositBiomeScope.java | 2 +- .../deposit/DepositGenerator.java | 6 +++--- .../deposit/DepositHeightDistribution.java | 2 +- .../deposit/DepositPlacementScope.java | 2 +- .../iris/modules/deposit/DepositSettings.java | 1 - .../deposit/DepositShape.java | 2 +- .../deposit/DepositVariant.java | 4 ++-- .../modules/deposit/DepositVariantSettings.java | 1 - .../floating/FloatingBottomPaletteMode.java | 2 +- .../floating/FloatingChildBiome.java | 4 ++-- .../modules/floating/FloatingChildSettings.java | 1 - .../floating/OverrideMode.java | 2 +- .../floating/TopShapeMode.java | 2 +- .../{builtin => modules}/loot/BlockDrop.java | 5 +++-- .../iris/modules/loot/BlockDropSettings.java | 1 - .../objects/ProceduralObjectSettings.java | 16 ++++++++-------- .../objects/coral/Coral.java | 4 ++-- .../objects/coral/CoralBranchAzimuth.java | 2 +- .../objects/coral/CoralForm.java | 2 +- .../objects/crystal/Crystal.java | 4 ++-- .../objects/crystal/CrystalDistribution.java | 2 +- .../objects/crystal/CrystalSurface.java | 2 +- .../objects/formation/Formation.java | 4 ++-- .../objects/formation/FormationForm.java | 2 +- .../objects/formation/FormationProfile.java | 2 +- .../objects/fungi/Fungus.java | 4 ++-- .../objects/fungi/FungusCapShape.java | 2 +- .../{builtin => modules}/objects/ruin/Ruin.java | 4 ++-- .../objects/ruin/RuinDecorator.java | 4 ++-- .../objects/ruin/RuinDecoratorTarget.java | 2 +- .../objects/ruin/RuinForm.java | 2 +- .../{builtin => modules}/objects/tree/Tree.java | 4 ++-- .../objects/tree/TreeAzimuthMode.java | 2 +- .../objects/tree/TreeBranchProbability.java | 2 +- .../objects/tree/TreeBranches.java | 4 ++-- .../objects/tree/TreeCanopy.java | 4 ++-- .../objects/tree/TreeDecorator.java | 4 ++-- .../objects/tree/TreeDecoratorTarget.java | 2 +- .../objects/tree/TreeFunction.java | 2 +- .../objects/tree/TreeLayer.java | 4 ++-- .../objects/tree/TreeLeafMode.java | 2 +- .../objects/tree/TreeProfile.java | 2 +- .../objects/tree/TreeRootStyle.java | 2 +- .../objects/tree/TreeSecondaryLeaf.java | 4 ++-- .../objects/tree/TreeSubBranches.java | 4 ++-- 135 files changed, 199 insertions(+), 202 deletions(-) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/CarvingEntry.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/carve/CaveProfile.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositBiomeScope.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositGenerator.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositHeightDistribution.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositPlacementScope.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositShape.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/deposit/DepositVariant.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/FloatingBottomPaletteMode.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/FloatingChildBiome.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/OverrideMode.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/floating/TopShapeMode.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/loot/BlockDrop.java (95%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ProceduralObjectSettings.java (88%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/coral/Coral.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/coral/CoralBranchAzimuth.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/coral/CoralForm.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/crystal/Crystal.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/crystal/CrystalDistribution.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/crystal/CrystalSurface.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/formation/Formation.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/formation/FormationForm.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/formation/FormationProfile.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/fungi/Fungus.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/fungi/FungusCapShape.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ruin/Ruin.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ruin/RuinDecorator.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ruin/RuinDecoratorTarget.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/ruin/RuinForm.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/Tree.java (99%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeAzimuthMode.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeBranchProbability.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeBranches.java (98%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeCanopy.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeDecorator.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeDecoratorTarget.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeFunction.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeLayer.java (94%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeLeafMode.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeProfile.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeRootStyle.java (96%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeSecondaryLeaf.java (94%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/tree/TreeSubBranches.java (96%) diff --git a/README.md b/README.md index 4f8fe366a..63a08a3c2 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,8 @@ mantle components outside the stage graph any more. Their stage constants, and t types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live beside the features they replace. Settings and helper types that only the jar's modules read, which Iris itself never touches, live in `art.arcane.iris.modules` instead, which Iris does not expose: the jar loads its own copy. -A type a pack writes as a snippet stays in `art.arcane.iris.builtin` even when only the jar reads it, because the snippet folder of -a type the host does not share must start with its module's id (`snippet/iris/carve/...`), and packs keep theirs where they always -were (`snippet/cave-profile/...`). +Every built-in snippet is named under its module's id, `iris//` (folder `snippet/iris/carve/cave-profile/`), so a +snippet type may live in either package. A type stays in `art.arcane.iris.builtin` only when Iris reads it or an exposed type holds it. Two of those modules are not in this project: `iris:biome` (writes the layout's platform biomes into the chunk) and `iris:custom` (records the platform's custom blocks of content plugins) are Iris itself, so their classes live in Iris @@ -88,8 +87,8 @@ regions and biomes. The loot tables, spawners, entities and markers are plain mo the `IrisChunk` their invocation offers (`context.extension(IrisChunk.class)`, then `state(...)`) or `engine.getGeneration().state(...)`. Settings move off Iris's classes one feature at a time. `iris:deposit` is the first whose settings are IrisApi types -only: `DepositSettings` (`art.arcane.iris.modules.deposit`) holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it in -`art.arcane.iris.builtin.deposit`, since packs write generators as `snippet/deposit/...`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the +only: `DepositSettings` (`art.arcane.iris.modules.deposit`) holds `DepositGenerator`s (blocks as `BlockSpec`, its enums beside it; packs write generators as +`snippet/iris/deposit/deposit/...`), and packs write `"deposits": [...]`, as they always have (`@Feature(key = "deposits", root = "generators")`: the key holds the one option's list). What needs Iris (resolving the palette, ore checks, clump shapes per world seed) lives in the module's own code, `ResolvedDeposit`. The deposits run one generator after the other, each with a random of its own; they used to spread over threads on a multicore pregen, which no module can do (stages run on the host's threads). @@ -126,7 +125,7 @@ from the random of whoever asks first, as it always was. The slope limit of a la object placement is the one `SlopeClip`. Caves, floating islands and ores are settings of their modules too, written under the keys they always had. `iris:carve` owns -`caveProfile` (dimension, region, biome; an object, or a `snippet/cave-profile/...` reference), `carving` (dimension; a list of bands) and +`caveProfile` (dimension, region, biome; an object, or a `snippet/iris/carve/cave-profile/...` reference), `carving` (dimension; a list of bands) and `carvingEnabled` (dimension; a boolean), `carvingBiome` (biome; a biome key) and `caveMinDepthBelowSurface` (biome; a number). `iris:floating` owns `floatingChildBiomes` (biome; a list) and `mergeFloatingChildBiomes` (biome; a boolean). `iris:terrain` owns `ores` (dimension, region, biome; a list of generators) and `hideOresForHiddenOre` (dimension; a boolean); `iris:deposit` owns `depositVariants` (dimension, region, biome; a list) diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java index 091b70635..b93ef154e 100644 --- a/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java +++ b/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java @@ -31,7 +31,7 @@ import java.util.Collections; import java.util.List; /** One find-and-replace of an object placement's blocks, an entry of the placement's {@code edit}. */ -@Snippet("object-block-replacer") +@Snippet("iris/blocks/object-block-replacer") @Desc("Find and replace object materials") public final class ObjectReplace { @MinItems(1) diff --git a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java index db788c086..13228e44b 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java @@ -34,10 +34,10 @@ import java.util.Optional; /** * One decorator of a biome, as packs write it in the {@code "decorators"} list or under - * {@code snippet/decorator/}: which blocks it places, where, how often and how tall. A value of IrisApi types only; the + * {@code snippet/iris/decorant/decorator/}: which blocks it places, where, how often and how tall. A value of IrisApi types only; the * decorant module resolves the blocks and builds the noise. */ -@Snippet("decorator") +@Snippet("iris/decorant/decorator") @Desc("A biome decorator is used for placing flowers, grass, cacti and so on") public final class Decorator { private static final String STATIC_NOISE = "STATIC"; diff --git a/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java b/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java index f5a87fe35..0a660809f 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ItemAttributeModifier.java @@ -24,7 +24,7 @@ import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.Snippet; -@Snippet("attribute-modifier") +@Snippet("iris/loot/attribute-modifier") @Desc("Represents an attribute modifier for an item or an entity. This allows you to create modifications to basic game attributes such as MAX_HEALTH or ARMOR_VALUE.") public final class ItemAttributeModifier { @Required diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java b/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java index 0e8d2d405..fdb4d10ac 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootEnchantment.java @@ -26,7 +26,7 @@ import com.volmit.config.Reference; import com.volmit.config.Required; import com.volmit.config.Snippet; -@Snippet("enchantment") +@Snippet("iris/loot/enchantment") @Desc("Represents an enchantment & level") public final class LootEnchantment { @Required diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java b/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java index b90fa6d8d..1f31eed44 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java @@ -31,7 +31,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; -@Snippet("loot") +@Snippet("iris/loot/loot") @Desc("Represents a loot entry") public final class LootEntry { public static final int MAX_AMOUNT = 64; diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java index bee988938..64cc01d93 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java @@ -35,7 +35,7 @@ import java.util.List; * {@code "loot": {"mode": "ADD", "tables": [...], "multiplier": 1}}. Levels stack, dimension first, then region and * biome; {@link LootMode} says what each does with the tables before it. An entity's {@code loot} has the same shape. */ -@Snippet("loot-registry") +@Snippet("iris/loot/loot-registry") @Desc("Reference loot tables in this area") @Feature(id = "iris:loot", name = "Loot", key = "loot", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class LootSettings implements IrisFeature { diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java index c83c52464..1a185f10f 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -29,7 +29,7 @@ import com.volmit.config.Snippet; import java.util.Collections; import java.util.List; -@Snippet("object-loot") +@Snippet("iris/loot/object-loot") @Desc("Represents loot within this object") public final class ObjectLoot implements ObjectLootEntry { @MinItems(1) diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java index 45351c4d1..5d1db49da 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java @@ -30,7 +30,7 @@ import com.volmit.config.Snippet; import java.util.Collections; import java.util.List; -@Snippet("object-vanilla-loot") +@Snippet("iris/loot/object-vanilla-loot") @Desc("Represents vanilla loot within this object") public final class ObjectVanillaLoot implements ObjectLootEntry { @MinItems(1) diff --git a/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java b/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java index 2c1c85628..5db32494e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java +++ b/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java @@ -30,7 +30,7 @@ import java.util.Collections; import java.util.List; /** The virtual heightmap an object placement may sit on instead of the terrain, written as the placement's {@code heightmap}. */ -@Snippet("generator") +@Snippet("iris/objects/generator") @Desc("A noise generator") public final class HeightmapNoise { @MinNumber(0.0001) diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index f012c04ad..db704f5fe 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -62,7 +62,7 @@ import java.util.Optional; * surface support); Iris's placement stages read the rest from the placement itself, so this keeps the JSON the placement * was written as ({@link #json()}) for Iris to read it again the way it reads placements everywhere else. */ -@Snippet("object-placer") +@Snippet("iris/objects/object-placer") @Desc("Represents an iris object placer. It places objects.") @JsonAdapter(ObjectPlacement.KeepingItsJson.class) public final class ObjectPlacement implements PlacementSource { diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java index 2390f0654..67330c549 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectScale.java @@ -24,7 +24,7 @@ import com.volmit.config.MinNumber; import com.volmit.config.Snippet; /** How an object placement scales its objects, written as the placement's {@code scale}. */ -@Snippet("object-scale") +@Snippet("iris/objects/object-scale") @Desc("Scale Objects") public final class ObjectScale { private static final double NO_SCALE = 1; diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java b/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java index 0bec6667c..b78ef1507 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java @@ -26,7 +26,7 @@ import com.volmit.config.Required; import com.volmit.config.Snippet; /** Whether a dimension's saplings grow the trees of its object placements, written as {@code "treeSettings": {...}}. */ -@Snippet("tree-settings") +@Snippet("iris/objects/tree-settings") @Desc("Tree growth override settings") @Feature(id = "iris:objects/trees", name = "Tree growth", key = "treeSettings", targets = Level.DIMENSION) public final class TreeGrowthSettings implements IrisFeature { diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java b/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java index 398959a35..a7d6a5baa 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java @@ -27,7 +27,7 @@ import java.util.Collections; import java.util.List; /** The trees an object placement overrides when their saplings grow, an entry of the placement's {@code trees}. */ -@Snippet("tree") +@Snippet("iris/objects/tree") @Desc("Tree replace options for this object placer") public final class TreeOverride { @Required diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java b/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java index 3c6edd7b9..25b6e4928 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeSize.java @@ -23,7 +23,7 @@ import com.volmit.config.Required; import com.volmit.config.Snippet; /** The size of a sapling area, in saplings, that a tree override applies to. */ -@Snippet("tree-size") +@Snippet("iris/objects/tree-size") @Desc("Sapling override object picking options") public final class TreeSize { @Required diff --git a/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java b/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java index 52e7040aa..5a2ab46e4 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/AxisRotationClamp.java @@ -27,7 +27,7 @@ import com.volmit.config.Snippet; import java.util.Objects; /** One axis of an object rotation, with the angles it may turn by and the steps between them. */ -@Snippet("axis-rotation") +@Snippet("iris/prepare/axis-rotation") @Desc("Represents a rotation axis with intervals and maxes. The x and z axis values are defaulted to disabled. The Y axis defaults to on, rotating by 90 degree increments.") public final class AxisRotationClamp { private static final double FULL_TURN_DEGREES = 360D; diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java index 9e3c51289..12ad4e3b7 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectRotation.java @@ -30,7 +30,7 @@ import java.util.Objects; * How an object is turned around each axis, written as a placement's {@code rotation}. Positions turn around X, then Z, * then Y; an axis locked to a multiple of a quarter turn swaps coordinates exactly instead of turning by an angle. */ -@Snippet("object-rotator") +@Snippet("iris/prepare/object-rotator") @Desc("Configures rotation for iris") public final class ObjectRotation { private static final double QUARTER_TURN_DEGREES = 90; diff --git a/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java b/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java index f1f542d3b..a67eadbc2 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/ObjectTranslate.java @@ -25,7 +25,7 @@ import com.volmit.config.Required; import com.volmit.config.Snippet; /** How far an object is shifted from where it would be placed, written as a placement's {@code translate}. */ -@Snippet("object-translator") +@Snippet("iris/prepare/object-translator") @Desc("Translate objects") public final class ObjectTranslate { @MinNumber(-128) diff --git a/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java b/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java index c5686d1c6..3ce6bbf12 100644 --- a/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java +++ b/src/main/java/art/arcane/iris/builtin/prepare/SlopeClip.java @@ -24,7 +24,7 @@ import com.volmit.config.MinNumber; import com.volmit.config.Snippet; /** The terrain slopes an object placement, a decorator or a terrain layer may sit on, written as its {@code slopeCondition}. */ -@Snippet("slope-clip") +@Snippet("iris/prepare/slope-clip") @Desc("Limits placement to a minimum and maximum terrain slope") public final class SlopeClip { private static final double DEFAULT_MINIMUM_SLOPE = 0; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java b/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java index 090e3ee97..044ac6ffd 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/AmbientEffect.java @@ -30,7 +30,7 @@ import com.volmit.config.Snippet; * A sound, particles, potion effect or commands that play now and then around the players in an area. The same * settings make the effect an entity shows when it appears ({@link EntityDefinition#spawnEffect()}). */ -@Snippet("effect") +@Snippet("iris/spawn/effect") @Desc("An iris effect") public final class AmbientEffect { @Ref(Reference.POTION_EFFECT) diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java b/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java index 48ed35cc8..e8a9a0c90 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java @@ -28,7 +28,7 @@ import com.volmit.config.Snippet; import java.util.Collections; import java.util.List; -@Snippet("command-registry") +@Snippet("iris/spawn/command-registry") @Desc("Represents a casting location for a command") public final class EffectCommands { @Required diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java index b775563fc..6ab4badac 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java @@ -24,7 +24,7 @@ import com.volmit.config.Required; import com.volmit.config.Ref; import com.volmit.config.Snippet; -@Snippet("entity-spawn") +@Snippet("iris/spawn/entity-spawn") @Desc("Represents an entity spawn during initial chunk generation") public final class EntitySpawn { @Ref(kind = EntityDefinition.class) diff --git a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java index fae838c59..3ba8d4eda 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -31,7 +31,7 @@ import java.util.Collections; import java.util.List; /** Blocks of an object placement that get a {@link SpawnMarker}, an entry of the placement's {@code markers}. */ -@Snippet("object-marker") +@Snippet("iris/spawn/object-marker") @Desc("Find blocks to mark") public final class PlacementMarker { @MinItems(1) diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java index cfd8f5b64..03960400e 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java @@ -26,7 +26,7 @@ import com.volmit.config.Snippet; import java.util.Collections; import java.util.List; -@Snippet("command") +@Snippet("iris/spawn/command") @Desc("Represents a set of Iris commands") public final class SpawnCommand { @Required diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java index afe1263b5..8ae3a109b 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnDuration.java @@ -23,7 +23,7 @@ import com.volmit.config.Snippet; import java.util.concurrent.TimeUnit; -@Snippet("duration") +@Snippet("iris/spawn/duration") @Desc("Represents a combined duration. Fill each property to add time into a single duration") public final class SpawnDuration { private static final long MILLISECONDS_PER_MINECRAFT_TICK = 50L; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java index 05e226551..5ebbd6225 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnRate.java @@ -21,7 +21,7 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.Snippet; -@Snippet("rate") +@Snippet("iris/spawn/rate") @Desc("Represents a count of something per time duration") public final class SpawnRate { @Desc("The amount of things. Leave 0 for infinite (meaning always spawn whenever)") diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java index 5fc38b4b9..ff9110133 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnTimeBlock.java @@ -21,7 +21,7 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.Snippet; -@Snippet("time-block") +@Snippet("iris/spawn/time-block") @Desc("Represents a time of day (24h time, not 12h am/pm). Set both to the same number for any time. If they are both set to -1, it will always be not allowed.") public final class SpawnTimeBlock { private static final double NEVER = -1; diff --git a/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java b/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java index 41fad88d1..1c2e87894 100644 --- a/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java +++ b/src/main/java/art/arcane/iris/builtin/stilt/StiltSettings.java @@ -27,7 +27,7 @@ import com.volmit.config.Snippet; import java.util.Optional; /** How far and with which blocks an object stilts into the ground, written as the placement's {@code stiltSettings}. */ -@Snippet("stilt-settings") +@Snippet("iris/stilt/stilt-settings") @Desc("Defines stilting behaviour.") public final class StiltSettings { @MinNumber(0) diff --git a/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java b/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java index a6d68d388..c0d30cb1a 100644 --- a/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java +++ b/src/main/java/art/arcane/iris/builtin/terrain/PaletteLayer.java @@ -32,10 +32,10 @@ import java.util.List; /** * One layer of surface or subsurface material of a biome, as packs write it in the biome's layers, sea layers, cave - * ceiling layers, slab and wall, in a floating island's bottom palette or under {@code snippet/biome-palette/}. A value of + * ceiling layers, slab and wall, in a floating island's bottom palette or under {@code snippet/iris/terrain/biome-palette/}. A value of * IrisApi types only; the terrain module resolves the blocks and builds the noise. */ -@Snippet("biome-palette") +@Snippet("iris/terrain/biome-palette") @Desc("A layer of surface / subsurface material in biomes") public final class PaletteLayer { private static final String STATIC_NOISE = "STATIC"; diff --git a/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java index 26e63793c..159e8eb58 100644 --- a/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java +++ b/src/main/java/art/arcane/iris/builtin/vacuum/VacuumSettings.java @@ -24,7 +24,7 @@ import com.volmit.config.MinNumber; import com.volmit.config.Snippet; /** How a VACUUM place mode bends terrain to meet an object's base, written as the placement's {@code vacuumSettings}. */ -@Snippet("vacuum-settings") +@Snippet("iris/vacuum/vacuum-settings") @Desc("Defines how a VACUUM place mode bends terrain to meet an object's base.") public final class VacuumSettings { @MinNumber(0) diff --git a/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java b/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java index 3c09f1090..76c15f177 100644 --- a/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java +++ b/src/main/java/art/arcane/iris/builtin/validate/ObjectLimit.java @@ -24,7 +24,7 @@ import com.volmit.config.MinNumber; import com.volmit.config.Snippet; /** The heights an object placement may sit between, written as the placement's {@code clamp}. */ -@Snippet("object-limit") +@Snippet("iris/validate/object-limit") @Desc("Limits object placement by minimum and maximum world height") public final class ObjectLimit { @MinNumber(-2048) diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java index b34e0641e..6f0e4caf8 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockDropping.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.loot.BlockDrop; +import art.arcane.iris.modules.loot.BlockDrop; import art.arcane.iris.modules.loot.BlockDropSettings; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootResolver; diff --git a/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java b/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java index a33b046b6..64eec7bc3 100644 --- a/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java +++ b/src/main/java/art/arcane/iris/engine/loot/ResolvedBlockDrop.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.loot; -import art.arcane.iris.builtin.loot.BlockDrop; +import art.arcane.iris.modules.loot.BlockDrop; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockSpec; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index d6ca52145..8ab9da2b0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.MatterMantle; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java index cff789b80..9a9de5bb7 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.builtin.objects.PlacementSource; /** What a cave object placement takes from the cave profile that applies to it. */ diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 2628e6362..c573acc2c 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -21,11 +21,11 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.objects.PlacementSource; -import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java index 3eb6ab4db..e3b62a18d 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.builtin.objects.PlacementSource; import art.arcane.iris.modules.objects.PlacementChanges; import com.volmit.object.PlaceableObject; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index a0e11901e..81bc3aacc 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.modules.floating.FloatingChildBiome; import art.arcane.iris.modules.floating.FloatingChildSettings; import art.arcane.iris.modules.floating.IslandFootprint; import art.arcane.iris.builtin.objects.ObjectPlacement; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java index 91b0e9cfd..a2c5b881f 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CaveFieldModule; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 80570327d..d24a97442 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.TreeGrowthSettings; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index 8852198d4..d7b81c6cb 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.iris.modules.objects.Declaration; import art.arcane.iris.modules.objects.ObjectPool; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java index af794029f..c9789c24b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.PlaceMode; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 91af66977..888e75e1e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -21,10 +21,10 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.ProceduralObjectSettings; +import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.TreeMode; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.loot.BlockBiomes; import art.arcane.iris.modules.objects.Declaration; import art.arcane.iris.modules.objects.ObjectPool; diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 12e70ddf9..a8033e0a7 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -26,7 +26,7 @@ import art.arcane.iris.modules.carve.CarvingEnabledSettings; import art.arcane.iris.modules.carve.CarvingSettings; import art.arcane.iris.modules.carve.CaveDepthSettings; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings; import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index aa349a945..5805b67de 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.deposit.DepositGenerator; +import art.arcane.iris.modules.deposit.DepositGenerator; import art.arcane.iris.modules.deposit.DepositSettings; import art.arcane.iris.modules.deposit.DepositVariantSettings; import art.arcane.iris.modules.deposit.OreFrequencySettings; diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 5772d7452..1fd4657fd 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.deposit.DepositGenerator; -import art.arcane.iris.builtin.deposit.DepositHeightDistribution; -import art.arcane.iris.builtin.deposit.DepositPlacementScope; -import art.arcane.iris.builtin.deposit.DepositVariant; +import art.arcane.iris.modules.deposit.DepositGenerator; +import art.arcane.iris.modules.deposit.DepositHeightDistribution; +import art.arcane.iris.modules.deposit.DepositPlacementScope; +import art.arcane.iris.modules.deposit.DepositVariant; import art.arcane.iris.modules.deposit.DepositVariantSettings; import art.arcane.iris.modules.deposit.OreFrequencySettings; import art.arcane.iris.modules.deposit.OreSizeSettings; diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java index caab1ccab..82dcf9b44 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingIslands.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.decorant.DecorantSettings; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.iris.builtin.floating.FloatingBottomPaletteMode; +import art.arcane.iris.modules.floating.FloatingBottomPaletteMode; import art.arcane.iris.builtin.prepare.SlopeClip; import art.arcane.iris.modules.terrain.BiomeLayers; import art.arcane.iris.modules.terrain.ColumnSlope; diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java index e3d542703..79725a107 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDeposit.java @@ -17,9 +17,9 @@ */ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.deposit.DepositBiomeScope; -import art.arcane.iris.builtin.deposit.DepositGenerator; -import art.arcane.iris.builtin.deposit.DepositShape; +import art.arcane.iris.modules.deposit.DepositBiomeScope; +import art.arcane.iris.modules.deposit.DepositGenerator; +import art.arcane.iris.modules.deposit.DepositShape; import art.arcane.volmlib.util.collection.KSet; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java index 5fd4d549d..587aac973 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java +++ b/src/main/java/art/arcane/iris/engine/modifier/ResolvedDepositVariant.java @@ -17,7 +17,7 @@ */ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.deposit.DepositVariant; +import art.arcane.iris.modules.deposit.DepositVariant; import art.arcane.volmlib.util.cache.AtomicCache; import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java index 515d2cbf5..f71fe1b9a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural; -import art.arcane.iris.builtin.objects.ProceduralObjectSettings; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.ProceduralObjectSettings; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java index a4cd84155..ea6bce10f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.coral; -import art.arcane.iris.builtin.objects.coral.Coral; +import art.arcane.iris.modules.objects.coral.Coral; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java index 19f89c398..c256d20b4 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.coral; -import art.arcane.iris.builtin.objects.coral.Coral; +import art.arcane.iris.modules.objects.coral.Coral; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.modules.objects.ObjectBuilder; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java index 65e8924c8..93d1ca854 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.modules.objects.crystal.Crystal; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; public final class CrystalBaseBuilder { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java index 581d78498..341650cb3 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.modules.objects.crystal.Crystal; import com.volmit.block.PaletteSpec; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java index 00043d8ad..8f21be72b 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.builtin.objects.crystal.CrystalSurface; +import art.arcane.iris.modules.objects.crystal.CrystalSurface; public final class CrystalGeometry { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java index 1515e981f..08055b8c1 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.builtin.objects.crystal.CrystalDistribution; -import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.modules.objects.crystal.CrystalDistribution; +import art.arcane.iris.modules.objects.crystal.Crystal; import art.arcane.volmlib.util.math.RNG; public final class CrystalShardBuilder { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java index c82fa1141..03f036794 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.crystal; -import art.arcane.iris.builtin.objects.crystal.Crystal; +import art.arcane.iris.modules.objects.crystal.Crystal; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.modules.objects.ObjectBuilder; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java index d7a8cacb7..a1111167d 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java @@ -20,7 +20,7 @@ package art.arcane.iris.engine.object.procedural.formation; import com.volmit.block.PaletteSpec; import java.util.Optional; -import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.modules.objects.formation.Formation; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java index e0454ae3c..e20f622b9 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.modules.objects.formation.Formation; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java index bc857176d..9bd54a7c0 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.modules.objects.formation.Formation; public final class FormationProfiles { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java index 80fb7e15c..109db16d0 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.modules.objects.formation.Formation; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java index 6dd0651a9..54a7a44e3 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.formation; -import art.arcane.iris.builtin.objects.formation.Formation; +import art.arcane.iris.modules.objects.formation.Formation; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.modules.objects.ObjectBuilder; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java index c42949d6d..418a26c3a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java @@ -20,8 +20,8 @@ package art.arcane.iris.engine.object.procedural.fungi; import com.volmit.block.PaletteSpec; import java.util.Optional; -import art.arcane.iris.builtin.objects.fungi.FungusCapShape; -import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.modules.objects.fungi.FungusCapShape; +import art.arcane.iris.modules.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.volmlib.util.math.Vector3i; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java index f28209979..43beea35e 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.modules.objects.fungi.Fungus; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java index cdb2f1a48..6708e7edc 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.modules.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java index 2a4429d19..aba9fe361 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.modules.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.Vector3i; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java index d2152469f..a59cf7130 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.fungi; -import art.arcane.iris.builtin.objects.fungi.Fungus; +import art.arcane.iris.modules.objects.fungi.Fungus; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.modules.objects.ObjectBuilder; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java index cb4f24a49..f5fcab16a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.ruin; -import art.arcane.iris.builtin.objects.ruin.Ruin; +import art.arcane.iris.modules.objects.ruin.Ruin; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.modules.objects.ObjectBuilder; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java index 5f4b7dd73..8136ffc49 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.ruin; -import art.arcane.iris.builtin.objects.ruin.RuinDecorator; +import art.arcane.iris.modules.objects.ruin.RuinDecorator; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java index da71d9853..ff0058a79 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.ruin; -import art.arcane.iris.builtin.objects.ruin.RuinDecorator; -import art.arcane.iris.builtin.objects.ruin.Ruin; +import art.arcane.iris.modules.objects.ruin.RuinDecorator; +import art.arcane.iris.modules.objects.ruin.Ruin; import art.arcane.iris.modules.objects.ObjectBuilder; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; @@ -126,7 +126,7 @@ public final class RuinGenerator { return; } int decoratorIndex = 0; - for (art.arcane.iris.builtin.objects.ruin.RuinDecorator decorator : ruin.accents()) { + for (art.arcane.iris.modules.objects.ruin.RuinDecorator decorator : ruin.accents()) { RuinDecoratorApplier.apply(canvas, decorator, blocks, ruin.seed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); decoratorIndex++; } diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java index 949e9739a..48bbd4304 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java index e4b460df6..f6560470a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.ProceduralShape; import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; import art.arcane.iris.modules.objects.ObjectBuilder; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java index 66bf85553..745cf7d85 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java @@ -18,12 +18,12 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf; -import art.arcane.iris.builtin.objects.tree.TreeDecorator; +import art.arcane.iris.modules.objects.tree.TreeSecondaryLeaf; +import art.arcane.iris.modules.objects.tree.TreeDecorator; import art.arcane.iris.modules.objects.ObjectBuilder; import com.volmit.block.PaletteSpec; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.Tree; import com.volmit.block.BlockState; import art.arcane.volmlib.util.math.RNG; @@ -111,7 +111,7 @@ public final class TreeBlockResolver { private static String pickWeighted(Tree tree, RNG rng) { int total = 0; - for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { + for (art.arcane.iris.modules.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { total += Math.max(0, s.weight()); } if (total <= 0) { @@ -119,7 +119,7 @@ public final class TreeBlockResolver { } double r = rng.nextDouble() * total; double cumulative = 0; - for (art.arcane.iris.builtin.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { + for (art.arcane.iris.modules.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { cumulative += Math.max(0, s.weight()); if (r < cumulative) { return s.block(); diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java index 37a9cc223..fb5e8dd97 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java @@ -18,13 +18,13 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeSubBranches; -import art.arcane.iris.builtin.objects.tree.TreeLayer; -import art.arcane.iris.builtin.objects.tree.TreeCanopy; -import art.arcane.iris.builtin.objects.tree.TreeBranches; -import art.arcane.iris.builtin.objects.tree.TreeProfile; -import art.arcane.iris.builtin.objects.tree.TreeLeafMode; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.TreeSubBranches; +import art.arcane.iris.modules.objects.tree.TreeLayer; +import art.arcane.iris.modules.objects.tree.TreeCanopy; +import art.arcane.iris.modules.objects.tree.TreeBranches; +import art.arcane.iris.modules.objects.tree.TreeProfile; +import art.arcane.iris.modules.objects.tree.TreeLeafMode; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java index c014ec309..4f648781f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeDecorator; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.TreeDecorator; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.math.RNG; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java index 0ab4640a9..7e7eb9afd 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeBranches; -import art.arcane.iris.builtin.objects.tree.TreeFunction; -import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.TreeBranches; +import art.arcane.iris.modules.objects.tree.TreeFunction; +import art.arcane.iris.modules.objects.tree.TreeAzimuthMode; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; public final class TreeFunctions { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java index 07615ecaf..c2e09d7d3 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.procedural.tree; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.modules.objects.ObjectBuilder; import com.volmit.block.BlockState; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java index 7dc66cba2..f5ece60ca 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeProfile; +import art.arcane.iris.modules.objects.tree.TreeProfile; public final class TreeProfiles { diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java index a20e80dfb..7ae8c976f 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeRootStyle; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.TreeRootStyle; +import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.volmlib.util.math.RNG; import java.util.ArrayList; diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java index 29b2462b9..b66b10e5a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java +++ b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.object.procedural.tree; -import art.arcane.iris.builtin.objects.tree.TreeAzimuthMode; +import art.arcane.iris.modules.objects.tree.TreeAzimuthMode; import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.tree.Tree; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java index 8611e7f36..4a598c434 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CarvingResolver.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CarvingEntry; import art.arcane.iris.modules.carve.CarvingSettings; import com.volmit.ModuleLog; import com.volmit.config.Range; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java index 6432cc232..2ef0abc12 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/CaveProfileSampler.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.object.terrain.carving; import art.arcane.iris.builtin.carve.CaveFieldModule; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.volmlib.util.math.M; import com.volmit.config.Range; import com.volmit.noise.NoiseFactory; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java index 36431ece9..b0d132f78 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/DeclaredCaveProfiles.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.terrain.carving; -import art.arcane.iris.builtin.carve.CaveProfile; +import art.arcane.iris.modules.carve.CaveProfile; import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index 87ab09e23..cace6f3db 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.terrain.carving; -import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CarvingEntry; import art.arcane.volmlib.util.cache.AtomicCache; import com.volmit.ModuleLog; import com.volmit.config.Range; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java index 810abe4cc..dc024227a 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingIslandSample.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.terrain.floating; -import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.modules.floating.FloatingChildBiome; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.volmlib.util.collection.KList; import com.volmit.ModuleLog; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java index 264708eeb..70e90b23e 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/FloatingWorld.java @@ -19,10 +19,10 @@ package art.arcane.iris.engine.object.terrain.floating; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CarvingEntry; import art.arcane.iris.modules.carve.CarvingSettings; -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.modules.floating.FloatingChildBiome; import art.arcane.iris.modules.floating.FloatingChildSettings; import art.arcane.iris.modules.floating.MergeFloatingChildrenSettings; import art.arcane.iris.builtin.objects.ObjectPlacement; diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java index f708edb51..e06cbb3e8 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/floating/ResolvedFloatingChild.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.object.terrain.floating; -import art.arcane.iris.builtin.carve.CarvingEntry; -import art.arcane.iris.builtin.carve.CaveProfile; -import art.arcane.iris.builtin.floating.FloatingChildBiome; +import art.arcane.iris.modules.carve.CarvingEntry; +import art.arcane.iris.modules.carve.CaveProfile; +import art.arcane.iris.modules.floating.FloatingChildBiome; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.engine.object.terrain.carving.CaveProfileSampler; import art.arcane.volmlib.util.cache.AtomicCache; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java b/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java rename to src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java index e04543669..d630acba4 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CarvingEntry.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; import com.volmit.config.Desc; import com.volmit.config.Range; @@ -33,7 +33,7 @@ import java.util.List; * of world Y, optionally split into child entries by a noise pattern. IrisApi types only; {@code CarvingResolver} picks * the entry for a position. */ -@Snippet("dimension-carving-entry") +@Snippet("iris/carve/dimension-carving-entry") @Desc("Dimension-level cave biome override with absolute world Y bounds.") public final class CarvingEntry { private static final double DEFAULT_WORLD_Y_MIN = -64; diff --git a/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java index 36941b629..c929a1204 100644 --- a/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java @@ -18,7 +18,6 @@ package art.arcane.iris.modules.carve; -import art.arcane.iris.builtin.carve.CarvingEntry; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java b/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java rename to src/main/java/art/arcane/iris/modules/carve/CaveProfile.java index 13417f346..d0b895920 100644 --- a/src/main/java/art/arcane/iris/builtin/carve/CaveProfile.java +++ b/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java @@ -16,9 +16,11 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.carve; +package art.arcane.iris.modules.carve; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.carve.CaveAnchorMode; +import art.arcane.iris.builtin.carve.CaveFieldModule; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; @@ -37,11 +39,11 @@ import java.util.Optional; /** * A 3D cave profile as packs write it for a dimension, region or biome ({@code caveProfile}) or under - * {@code snippet/cave-profile/}: the noise fields that decide where caves are, how they meet the surface, where + * {@code snippet/iris/carve/cave-profile/}: the noise fields that decide where caves are, how they meet the surface, where * cave fluid may sit and how objects find anchors in them. A level that writes none has no profile, which is the * same as one that is not {@code enabled}. IrisApi types only; the carving module builds the noise. */ -@Snippet("cave-profile") +@Snippet("iris/carve/cave-profile") @Desc("Represents a configurable 3D cave profile.") @Feature(id = "iris:carve/profile", name = "Cave profile", key = "caveProfile", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class CaveProfile implements IrisFeature { diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java b/src/main/java/art/arcane/iris/modules/deposit/DepositBiomeScope.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositBiomeScope.java index ec7e9cb86..5997e9a93 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositBiomeScope.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositBiomeScope.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java b/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java index 4b6f4e317..c28f8d4f0 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositGenerator.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; @@ -31,10 +31,10 @@ import java.util.List; /** * One kind of deposit a dimension, region or biome generates, as packs write it in the {@code "deposits"} list or under - * {@code snippet/deposit/}: how many clumps of which blocks, how large, at which heights and in which biomes. A value + * {@code snippet/iris/deposit/deposit/}: how many clumps of which blocks, how large, at which heights and in which biomes. A value * of IrisApi types only; the deposit module builds the clumps and resolves the blocks. */ -@Snippet("deposit") +@Snippet("iris/deposit/deposit") @Desc("Creates ore & other block deposits underground") public final class DepositGenerator { private static final int MAX_CLUMP_DIMENSION = 11; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java b/src/main/java/art/arcane/iris/modules/deposit/DepositHeightDistribution.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositHeightDistribution.java index 74c41f61f..4a9f2e433 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositHeightDistribution.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositHeightDistribution.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java b/src/main/java/art/arcane/iris/modules/deposit/DepositPlacementScope.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositPlacementScope.java index 5a9541033..e2303f0f6 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositPlacementScope.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositPlacementScope.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java b/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java index e080867dc..3b2bd20dc 100644 --- a/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositSettings.java @@ -18,7 +18,6 @@ package art.arcane.iris.modules.deposit; -import art.arcane.iris.builtin.deposit.DepositGenerator; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java b/src/main/java/art/arcane/iris/modules/deposit/DepositShape.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositShape.java index 72c3e3022..8ac3d3654 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositShape.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositShape.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java b/src/main/java/art/arcane/iris/modules/deposit/DepositVariant.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java rename to src/main/java/art/arcane/iris/modules/deposit/DepositVariant.java index 582301354..c7a92ee52 100644 --- a/src/main/java/art/arcane/iris/builtin/deposit/DepositVariant.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositVariant.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.deposit; +package art.arcane.iris.modules.deposit; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; @@ -31,7 +31,7 @@ import java.util.Map; * One deposit ore remap rule, an entry of {@code depositVariants}: within a vertical band, ore blocks are rewritten to * alternate blocks. A value of IrisApi types only; {@code ResolvedDepositVariant} resolves the blocks. */ -@Snippet("deposit-variant") +@Snippet("iris/deposit/deposit-variant") @Desc("Remaps ore block ids to alternate block ids within a vertical band. Ores declared at dimension, region, and biome scope can be rewritten at placement time (for example, iron_ore -> deepslate_iron_ore inside a deep carving band, or yourmod:iron -> yourmod:moon_iron inside a lunar biome).") public final class DepositVariant { @Required diff --git a/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java b/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java index 7ba4980d9..5a3e9c4c7 100644 --- a/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java @@ -18,7 +18,6 @@ package art.arcane.iris.modules.deposit; -import art.arcane.iris.builtin.deposit.DepositVariant; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingBottomPaletteMode.java b/src/main/java/art/arcane/iris/modules/floating/FloatingBottomPaletteMode.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/floating/FloatingBottomPaletteMode.java rename to src/main/java/art/arcane/iris/modules/floating/FloatingBottomPaletteMode.java index a8de3246d..7421080b8 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingBottomPaletteMode.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingBottomPaletteMode.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java b/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java rename to src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java index edc39a5f6..2970eec26 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/FloatingChildBiome.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.terrain.PaletteLayer; @@ -40,7 +40,7 @@ import java.util.OptionalInt; * is, how high it floats, how its top, underside and walls are shaped, and which objects, decorators and water it * gets. */ -@Snippet("floating-child-biome") +@Snippet("iris/floating/floating-child-biome") @Desc("Declares a floating biome layer above this biome's terrain. A 2D footprint noise decides which columns are part of the island (threshold + style control blankets, swirls, scattered blobs). The top profile is driven by the target biome's own terrain generators (so a mountains biome produces real peaks, desert produces real dunes). The bottom tail hanging below is a separately configurable noise (pick VASCULAR for drippy roots, FRACTAL_RM_SIMPLEX for crystalline spikes, PERLIN for smooth rounded bowls).") public final class FloatingChildBiome { public static final int DEFAULT_EDGE_TAPER_WIDTH = 10; diff --git a/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java index 8e6a97863..4b794a640 100644 --- a/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java @@ -18,7 +18,6 @@ package art.arcane.iris.modules.floating; -import art.arcane.iris.builtin.floating.FloatingChildBiome; import art.arcane.iris.modules.carve.CarvingSettings; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/floating/OverrideMode.java b/src/main/java/art/arcane/iris/modules/floating/OverrideMode.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/floating/OverrideMode.java rename to src/main/java/art/arcane/iris/modules/floating/OverrideMode.java index a9c77a468..b308bc1e6 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/OverrideMode.java +++ b/src/main/java/art/arcane/iris/modules/floating/OverrideMode.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/floating/TopShapeMode.java b/src/main/java/art/arcane/iris/modules/floating/TopShapeMode.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/floating/TopShapeMode.java rename to src/main/java/art/arcane/iris/modules/floating/TopShapeMode.java index 873128902..0a0be2832 100644 --- a/src/main/java/art/arcane/iris/builtin/floating/TopShapeMode.java +++ b/src/main/java/art/arcane/iris/modules/floating/TopShapeMode.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.floating; +package art.arcane.iris.modules.floating; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java b/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java similarity index 95% rename from src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java rename to src/main/java/art/arcane/iris/modules/loot/BlockDrop.java index 75151041e..d79933f74 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/BlockDrop.java +++ b/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.loot; +package art.arcane.iris.modules.loot; +import art.arcane.iris.builtin.loot.LootEntry; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; import com.volmit.config.MinItems; @@ -27,7 +28,7 @@ import com.volmit.config.Snippet; import java.util.Collections; import java.util.List; -@Snippet("block-drops") +@Snippet("iris/loot/block-drops") @Desc("Represents a block drop list") public final class BlockDrop { @Required diff --git a/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java b/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java index 659a257d6..87623b317 100644 --- a/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java +++ b/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java @@ -18,7 +18,6 @@ package art.arcane.iris.modules.loot; -import art.arcane.iris.builtin.loot.BlockDrop; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java similarity index 88% rename from src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java rename to src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java index c64f3fe53..b313539ed 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ProceduralObjectSettings.java +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java @@ -16,14 +16,14 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; -import art.arcane.iris.builtin.objects.coral.Coral; -import art.arcane.iris.builtin.objects.crystal.Crystal; -import art.arcane.iris.builtin.objects.formation.Formation; -import art.arcane.iris.builtin.objects.fungi.Fungus; -import art.arcane.iris.builtin.objects.ruin.Ruin; -import art.arcane.iris.builtin.objects.tree.Tree; +import art.arcane.iris.modules.objects.coral.Coral; +import art.arcane.iris.modules.objects.crystal.Crystal; +import art.arcane.iris.modules.objects.formation.Formation; +import art.arcane.iris.modules.objects.fungi.Fungus; +import art.arcane.iris.modules.objects.ruin.Ruin; +import art.arcane.iris.modules.objects.tree.Tree; import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; @@ -38,7 +38,7 @@ import java.util.List; * The procedural objects a region or biome declares, written as {@code "proceduralObjects": {"trees": [...], ...}}: things * Iris generates from scratch at world-gen time and places like object placements. */ -@Snippet("procedural-objects") +@Snippet("iris/objects/procedural-objects") @Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") @Feature(id = "iris:objects/procedural", name = "Procedural objects", key = "proceduralObjects", targets = {Level.REGION, Level.BIOME}) public final class ProceduralObjectSettings implements IrisFeature { diff --git a/src/main/java/art/arcane/iris/builtin/objects/coral/Coral.java b/src/main/java/art/arcane/iris/modules/objects/coral/Coral.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/objects/coral/Coral.java rename to src/main/java/art/arcane/iris/modules/objects/coral/Coral.java index 832cd8b68..31dc9f77f 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/coral/Coral.java +++ b/src/main/java/art/arcane/iris/modules/objects/coral/Coral.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.coral; +package art.arcane.iris.modules.objects.coral; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; @@ -36,7 +36,7 @@ import com.volmit.config.Required; import java.util.Optional; -@Snippet("coral") +@Snippet("iris/objects/coral") @Desc("A single procedurally generated coral reef structure. Iris bakes a pool of deterministic variants from these settings and scatters them across the seafloor at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Mirrors the procedural tree system but tuned for underwater reefs: structural blocks are waterlogged so the coral stays alive, and placement defaults to anchoring on the terrain beneath the water surface.") public final class Coral { @Desc("A human readable name used in logs and as the variant load key.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/coral/CoralBranchAzimuth.java b/src/main/java/art/arcane/iris/modules/objects/coral/CoralBranchAzimuth.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/coral/CoralBranchAzimuth.java rename to src/main/java/art/arcane/iris/modules/objects/coral/CoralBranchAzimuth.java index bd3712ab1..ec607d0d2 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/coral/CoralBranchAzimuth.java +++ b/src/main/java/art/arcane/iris/modules/objects/coral/CoralBranchAzimuth.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.coral; +package art.arcane.iris.modules.objects.coral; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/coral/CoralForm.java b/src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/coral/CoralForm.java rename to src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java index 236b3c1e0..46d645872 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/coral/CoralForm.java +++ b/src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.coral; +package art.arcane.iris.modules.objects.coral; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/crystal/Crystal.java b/src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/objects/crystal/Crystal.java rename to src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java index a68427901..f954a4e79 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/crystal/Crystal.java +++ b/src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.crystal; +package art.arcane.iris.modules.objects.crystal; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; @@ -36,7 +36,7 @@ import com.volmit.config.Required; import java.util.Optional; -@Snippet("crystal") +@Snippet("iris/objects/crystal") @Desc("A single procedurally generated crystal cluster: a budding base blob with faceted, tapered shards radiating from it (geode / amethyst-style). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Built for caves.") public final class Crystal { @Desc("A human readable name used in logs and as the variant load key.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalDistribution.java b/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalDistribution.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalDistribution.java rename to src/main/java/art/arcane/iris/modules/objects/crystal/CrystalDistribution.java index d6882038a..e4dbc5517 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalDistribution.java +++ b/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalDistribution.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.crystal; +package art.arcane.iris.modules.objects.crystal; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalSurface.java b/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalSurface.java rename to src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java index 19aa568ac..66d456e8d 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/crystal/CrystalSurface.java +++ b/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.crystal; +package art.arcane.iris.modules.objects.crystal; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/formation/Formation.java b/src/main/java/art/arcane/iris/modules/objects/formation/Formation.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/objects/formation/Formation.java rename to src/main/java/art/arcane/iris/modules/objects/formation/Formation.java index 2fac99587..eeb8b93db 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/formation/Formation.java +++ b/src/main/java/art/arcane/iris/modules/objects/formation/Formation.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.formation; +package art.arcane.iris.modules.objects.formation; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; @@ -36,7 +36,7 @@ import com.volmit.config.Required; import java.util.Optional; -@Snippet("formation") +@Snippet("iris/objects/formation") @Desc("A single procedurally generated natural formation, including rock landmarks and magical glacial silhouettes. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") public final class Formation { @Desc("A human readable name used in logs and as the variant load key.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/formation/FormationForm.java b/src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/formation/FormationForm.java rename to src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java index d6a830643..6ffbefc54 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/formation/FormationForm.java +++ b/src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.formation; +package art.arcane.iris.modules.objects.formation; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/formation/FormationProfile.java b/src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/formation/FormationProfile.java rename to src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java index 11d7b2f6b..c63462b8f 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/formation/FormationProfile.java +++ b/src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.formation; +package art.arcane.iris.modules.objects.formation; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/fungi/Fungus.java b/src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/objects/fungi/Fungus.java rename to src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java index 69f19fcaa..8098f9d59 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/fungi/Fungus.java +++ b/src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.fungi; +package art.arcane.iris.modules.objects.fungi; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; @@ -36,7 +36,7 @@ import com.volmit.config.Required; import java.util.Optional; -@Snippet("fungus") +@Snippet("iris/objects/fungus") @Desc("A single procedurally generated fungus (giant mushroom or shelf fungus). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. The fungus is built as a stem column with a cap dome grown on top, mirroring the trunk-and-canopy model used by procedural trees.") public final class Fungus { @Desc("A human readable name used in logs and as the variant load key.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/fungi/FungusCapShape.java b/src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/fungi/FungusCapShape.java rename to src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java index 6184c4afc..b57ec317e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/fungi/FungusCapShape.java +++ b/src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.fungi; +package art.arcane.iris.modules.objects.fungi; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/ruin/Ruin.java b/src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/objects/ruin/Ruin.java rename to src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java index 2774af004..3de150eef 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ruin/Ruin.java +++ b/src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.ruin; +package art.arcane.iris.modules.objects.ruin; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; @@ -39,7 +39,7 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -@Snippet("ruin") +@Snippet("iris/objects/ruin") @Desc("A single procedurally generated ruin: a crumbling man-made structure (pillar, wall, arch, foundation slab, or rubble pile). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Weathering swaps blocks for mossy or cracked variants by noise, erosion deletes blocks so the shape reads as collapsed, and a buried fraction sinks the ruin into the terrain.") public final class Ruin { @Desc("A human readable name used in logs and as the variant load key (procedural/#).") diff --git a/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecorator.java b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecorator.java rename to src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java index c09789ea2..5c77731b2 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecorator.java +++ b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.ruin; +package art.arcane.iris.modules.objects.ruin; import com.volmit.block.PaletteSpec; import com.volmit.config.Desc; @@ -29,7 +29,7 @@ import com.volmit.config.Required; import java.util.Optional; -@Snippet("ruin-decorator") +@Snippet("iris/objects/ruin-decorator") @Desc("An accent block applied to a generated ruin after it is built and eroded, such as moss carpets on broken tops, vines on the faces, or rubble scattered around the base.") public final class RuinDecorator { @Desc("Where on the ruin this accent is placed. TOP sits on the highest block of each column, SURFACE clings to air-facing vertical faces, BASE_SCATTER rings the ground footprint around the base.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecoratorTarget.java b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecoratorTarget.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecoratorTarget.java rename to src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecoratorTarget.java index 2b0b7e21e..9f8021004 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinDecoratorTarget.java +++ b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecoratorTarget.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.ruin; +package art.arcane.iris.modules.objects.ruin; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinForm.java b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/ruin/RuinForm.java rename to src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java index 02c8a8b60..9b469e02f 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ruin/RuinForm.java +++ b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.ruin; +package art.arcane.iris.modules.objects.ruin; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java b/src/main/java/art/arcane/iris/modules/objects/tree/Tree.java similarity index 99% rename from src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java rename to src/main/java/art/arcane/iris/modules/objects/tree/Tree.java index 49ff9b31b..49d18a983 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/Tree.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/Tree.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.carve.CarvingMode; @@ -39,7 +39,7 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -@Snippet("procedural-tree") +@Snippet("iris/objects/procedural-tree") @Desc("A single procedurally generated tree. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") public final class Tree { @Desc("A human readable name used in logs and as the variant load key.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeAzimuthMode.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeAzimuthMode.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java index f9373f666..92ffc4a19 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeAzimuthMode.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranchProbability.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranchProbability.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java index c44d3fa34..d0b680898 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranchProbability.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranches.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java similarity index 98% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranches.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java index 2aea203d8..62ff4bf6b 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeBranches.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; import com.volmit.config.Snippet; @@ -25,7 +25,7 @@ import com.volmit.config.MinNumber; import java.util.Optional; -@Snippet("tree-branches") +@Snippet("iris/objects/tree-branches") @Desc("A branch system that throws limbs out of the trunk and places a leaf ball at each tip. When present, branches drive the canopy and only the topmost crown disc of the profile is still placed.") public final class TreeBranches { @Desc("How branch spawn chance varies over trunk height.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeCanopy.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeCanopy.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java index ca748c351..2d8fc1e7e 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeCanopy.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; import com.volmit.config.Snippet; @@ -28,7 +28,7 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -@Snippet("tree-canopy") +@Snippet("iris/objects/tree-canopy") @Desc("The leaf crown of a procedural tree. Built from stacked dome-shaped discs (driven by the profile or by explicit layers) and optionally a branch system.") public final class TreeCanopy { @MinNumber(0) diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecorator.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecorator.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java index 78700bb5a..926a23ad6 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecorator.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.block.PaletteSpec; import com.volmit.config.Desc; @@ -29,7 +29,7 @@ import com.volmit.config.Required; import java.util.Optional; -@Snippet("tree-decorator") +@Snippet("iris/objects/tree-decorator") @Desc("An accent block applied to a generated tree such as fruit on branch tips, vines on the trunk, snow on the crown, or a glowing underside.") public final class TreeDecorator { @Desc("Where this decorator is placed on the tree.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecoratorTarget.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecoratorTarget.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java index 598ce05c2..87137f3ec 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeDecoratorTarget.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeFunction.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeFunction.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java index 3f4cc7c9c..7dd34331a 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeFunction.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLayer.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java similarity index 94% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeLayer.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java index 1f5181cae..0a6e03fdc 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLayer.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java @@ -16,13 +16,13 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; import com.volmit.config.Snippet; import com.volmit.config.MinNumber; -@Snippet("tree-layer") +@Snippet("iris/objects/tree-layer") @Desc("An explicit canopy disc at a given vertical offset and radius. Define a list of these to bypass the profile and sculpt the crown by hand.") public final class TreeLayer { @Desc("The vertical offset of this disc, measured in blocks above the trunk base.") diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLeafMode.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeLeafMode.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java index 7ac85244f..40bfebcc8 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeLeafMode.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeProfile.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeProfile.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java index 14f9b2af5..d079823ff 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeProfile.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeRootStyle.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeRootStyle.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeRootStyle.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeRootStyle.java index 4ef5457fe..ff9afcae9 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeRootStyle.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeRootStyle.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSecondaryLeaf.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java similarity index 94% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeSecondaryLeaf.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java index 54f96c881..a11d7f0f0 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSecondaryLeaf.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; import com.volmit.config.Snippet; @@ -25,7 +25,7 @@ import com.volmit.config.Ref; import com.volmit.config.Reference; import com.volmit.config.Required; -@Snippet("tree-secondary-leaf") +@Snippet("iris/objects/tree-secondary-leaf") @Desc("A weighted accent leaf or foliage block scattered through the canopy (blossoms, shroomlight, berries).") public final class TreeSecondaryLeaf { @Required diff --git a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSubBranches.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/tree/TreeSubBranches.java rename to src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java index efd42f501..f9471a229 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/tree/TreeSubBranches.java +++ b/src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java @@ -16,14 +16,14 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects.tree; +package art.arcane.iris.modules.objects.tree; import com.volmit.config.Desc; import com.volmit.config.Snippet; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; -@Snippet("tree-sub-branches") +@Snippet("iris/objects/tree-sub-branches") @Desc("One recursive level of sub-branches sprouting from each primary branch tip.") public final class TreeSubBranches { @MinNumber(1) From c9df155ee4ebc9d072cb88d266d8891f29788454 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 02:26:04 +0100 Subject: [PATCH 112/139] Move tree growth settings into the jar Iris no longer reads TreeGrowthSettings (ObjectPlacements.treeGrowth is gone), so it and its TreeMode move to art.arcane.iris.modules.objects beside TreeGrowing, the only reader. --- .../arcane/iris/engine/mantle/components/ObjectModule.java | 2 +- .../art/arcane/iris/engine/mantle/components/TreeGrowing.java | 4 ++-- .../iris/{builtin => modules}/objects/TreeGrowthSettings.java | 2 +- .../arcane/iris/{builtin => modules}/objects/TreeMode.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/TreeGrowthSettings.java (97%) rename src/main/java/art/arcane/iris/{builtin => modules}/objects/TreeMode.java (96%) diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index d24a97442..d86dfe37e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -23,7 +23,7 @@ import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.modules.objects.ProceduralObjectSettings; 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.modules.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; import com.volmit.IrisModule; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 888e75e1e..3eccf6fb6 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -22,8 +22,8 @@ import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.modules.objects.ProceduralObjectSettings; -import art.arcane.iris.builtin.objects.TreeGrowthSettings; -import art.arcane.iris.builtin.objects.TreeMode; +import art.arcane.iris.modules.objects.TreeGrowthSettings; +import art.arcane.iris.modules.objects.TreeMode; import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.loot.BlockBiomes; import art.arcane.iris.modules.objects.Declaration; diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java b/src/main/java/art/arcane/iris/modules/objects/TreeGrowthSettings.java similarity index 97% rename from src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java rename to src/main/java/art/arcane/iris/modules/objects/TreeGrowthSettings.java index b78ef1507..0f58c7a26 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeGrowthSettings.java +++ b/src/main/java/art/arcane/iris/modules/objects/TreeGrowthSettings.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; import com.volmit.config.Level; import com.volmit.IrisFeature; diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeMode.java b/src/main/java/art/arcane/iris/modules/objects/TreeMode.java similarity index 96% rename from src/main/java/art/arcane/iris/builtin/objects/TreeMode.java rename to src/main/java/art/arcane/iris/modules/objects/TreeMode.java index a0c643406..390ac5909 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeMode.java +++ b/src/main/java/art/arcane/iris/modules/objects/TreeMode.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.builtin.objects; +package art.arcane.iris.modules.objects; import com.volmit.config.Desc; From 98c3c96881e111d6e352a5c266ae1819cbb58939 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 03:29:50 +0100 Subject: [PATCH 113/139] Drop DecoratorLoad and LayerLoad They sat in the exposed package only so Iris could colour the decorator and layer map modes, which are cut. --- .../iris/builtin/decorant/DecoratorLoad.java | 52 ------------------- .../iris/builtin/terrain/LayerLoad.java | 33 ------------ 2 files changed, 85 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java delete mode 100644 src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java b/src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java deleted file mode 100644 index a73ef0c18..000000000 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecoratorLoad.java +++ /dev/null @@ -1,52 +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.builtin.decorant; - -/** How loaded with decorating a biome is, which studio's decorator load view colours it by. */ -public final class DecoratorLoad { - private static final int COLUMNS_PER_CHUNK = 256; - - private DecoratorLoad() { - } - - /** The sum of the decorators' chances times their stack heights, at least one block each; 0 for a biome without decorators. */ - public static double of(DecorantSettings settings) { - if (settings == null) { - return 0D; - } - - double load = 0D; - for (Decorator decorator : settings.decorators()) { - load += Math.max(decorator.stackMax(), 1) * decorator.chance(); - } - return load; - } - - /** The sum of the decorators' chances over a chunk's columns, which is how strongly the view colours the biome. */ - public static double colour(DecorantSettings settings) { - if (settings == null) { - return 0D; - } - - double load = 0D; - for (Decorator decorator : settings.decorators()) { - load += decorator.chance() * Math.min(1, decorator.stackMax()) * COLUMNS_PER_CHUNK; - } - return load; - } -} diff --git a/src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java b/src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java deleted file mode 100644 index 8cf6d635a..000000000 --- a/src/main/java/art/arcane/iris/builtin/terrain/LayerLoad.java +++ /dev/null @@ -1,33 +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.builtin.terrain; - -import java.util.List; - -/** The layers of a biome's surface, which studio's layer view counts. */ -public final class LayerLoad { - private static final LayersSettings DEFAULT_LAYERS = new LayersSettings(); - - private LayerLoad() { - } - - /** The layers of the biome's surface, top first; a biome that declares no layers has the one layer of grass the settings default to. */ - public static List layersOf(LayersSettings declared) { - return (declared == null ? DEFAULT_LAYERS : declared).layers(); - } -} From 83bc859b31f26fb91ebc000e161e064d5e583cbf Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 04:02:52 +0100 Subject: [PATCH 114/139] Hand Iris the placement, its record, the shuffle seed and the floor ObjectRun gives the placement's name and JSON to the run, iris:objects declares the placement type with its JSON names, and placements are recorded as typed PlacementRecords instead of key@id texts (Iris keeps the text form, so StructurePlacementMarker moves to Iris). iris:loot gives the seed a container is shuffled with and iris:terrain says it protects the floor. The five Iris-only entity knobs are fields of the EntitySpec, so IrisEntityExtras is gone. --- .../iris/builtin/objects/ObjectPlacement.java | 28 ++++++ .../iris/builtin/objects/ObjectRun.java | 3 +- .../iris/builtin/spawn/IrisEntityExtras.java | 46 --------- .../iris/builtin/structure/StructureHost.java | 3 +- .../structure/StructurePlacementMarker.java | 95 ------------------- .../iris/engine/actuator/TerrainModule.java | 7 ++ .../arcane/iris/engine/loot/LootGiving.java | 7 ++ .../iris/engine/loot/PlacedObjectLoot.java | 35 +++---- .../mantle/components/ChunkObjectPlacing.java | 5 +- .../mantle/components/FloatingPlacer.java | 7 +- .../mantle/components/ObjectModule.java | 2 + .../engine/mantle/components/TreeGrowing.java | 5 +- .../iris/engine/spawn/EntityResolution.java | 16 ++-- .../modules/objects/ForwardingTerrain.java | 5 +- .../iris/modules/objects/PlacementTags.java | 6 +- .../modules/objects/TerrainTransaction.java | 15 +-- .../iris/modules/placement/StageTerrain.java | 14 +-- 17 files changed, 103 insertions(+), 196 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java delete mode 100644 src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index db704f5fe..9c6f0db63 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -52,9 +52,14 @@ import com.volmit.noise.StyledRange; import com.volmit.object.GeneratedObject; import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; /** * One object placement of a biome or region, an entry of its {@code objects}: which objects, how often, and how they sit @@ -437,6 +442,29 @@ public final class ObjectPlacement implements PlacementSource { return json; } + /** + * The names a placement's own options are written under: every field Gson reads, under its {@code @SerializedName} and + * alternates. Settings other modules declare on a placement may not take these keys + * ({@link com.volmit.FeatureRegistry#registerPlacementType}). + */ + public static Set jsonFields() { + Set names = new TreeSet<>(); + for (Field field : ObjectPlacement.class.getDeclaredFields()) { + int modifiers = field.getModifiers(); + if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || field.isSynthetic()) { + continue; + } + SerializedName serialized = field.getAnnotation(SerializedName.class); + if (serialized == null) { + names.add(field.getName()); + continue; + } + names.add(serialized.value()); + names.addAll(Arrays.asList(serialized.alternate())); + } + return names; + } + /** * What Iris made of this placement the last time it asked, kept here so it asks once. Only Iris sets or reads it, * and it is its own type. diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java index 1ee0350bd..9b30d09df 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectRun.java @@ -110,7 +110,8 @@ public final class ObjectRun { object = objects.smartBored(object); } PlacementRequest request = new PlacementRequest(object.geometry(), new BlockPosition(x, requestedY, z)); - return new PlacementRun(request, area(), terrain, this, placementSeed(worldSeed)); + return new PlacementRun(request, object.name(), Optional.ofNullable(settings.json()), area(), terrain, this, + placementSeed(worldSeed)); } public PlaceableObject object() { diff --git a/src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java b/src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java deleted file mode 100644 index 5919e1475..000000000 --- a/src/main/java/art/arcane/iris/builtin/spawn/IrisEntityExtras.java +++ /dev/null @@ -1,46 +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.builtin.spawn; - -import java.util.Objects; -import java.util.Optional; - -/** - * Iris extension of an {@link com.volmit.entity.EntitySpec}, read by Iris's Bukkit host with - * {@code spec.extension(IrisEntityExtras.class)}: what Iris packs set on an entity that only Bukkit has a name for or - * only Iris does. Other hosts ignore it. - * - * @param reason Bukkit's spawn reason by name, such as {@code COMMAND}; empty for a natural spawn - * @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near - * @param pandaMainGene for pandas the main gene by Bukkit's name; empty to leave it to the platform - * @param pandaHiddenGene for pandas the hidden gene by Bukkit's name; empty to leave it to the platform - * @param applySettingsToProvidedMob whether the rest of the spec also applies to a mob of a content provider, which is - * otherwise left as the provider set it up - */ -public record IrisEntityExtras(Optional reason, boolean riseOutOfGround, Optional pandaMainGene, - Optional pandaHiddenGene, boolean applySettingsToProvidedMob) { - /** What an entity without the extension gets: a natural spawn, standing, with the platform's genes. */ - public static final IrisEntityExtras NONE = new IrisEntityExtras(Optional.empty(), false, Optional.empty(), Optional.empty(), false); - - public IrisEntityExtras { - Objects.requireNonNull(reason, "reason"); - Objects.requireNonNull(pandaMainGene, "pandaMainGene"); - Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene"); - } -} diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java index 14dabfe37..5703e7117 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java @@ -18,6 +18,7 @@ package art.arcane.iris.builtin.structure; import com.volmit.generation.InvocationContext; +import com.volmit.resource.ResourceId; import java.util.List; import java.util.Optional; @@ -36,5 +37,5 @@ public interface StructureHost { int reach(); /** The loot tables the structure gives its pieces' containers; empty when the pack has no such structure. */ - Optional> lootTables(String structureKey); + Optional> lootTables(ResourceId structure); } diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java deleted file mode 100644 index 97bd7ef67..000000000 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementMarker.java +++ /dev/null @@ -1,95 +0,0 @@ -package art.arcane.iris.builtin.structure; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Objects; - -public final class StructurePlacementMarker { - private static final String FAMILY_PREFIX = "@iris-structure:"; - private static final String VERSION_PREFIX = FAMILY_PREFIX + "v1:"; - - private StructurePlacementMarker() { - } - - public static String encodeStructure(String objectKey, int placementId, String structureKey) { - String normalizedObjectKey = requireKey(objectKey, "objectKey"); - String normalizedStructureKey = requireKey(structureKey, "structureKey"); - return VERSION_PREFIX - + encodeKey(normalizedObjectKey) - + ":" + placementId - + ":" + encodeKey(normalizedStructureKey); - } - - public static Decoded decode(String marker) { - if (marker == null || marker.isBlank()) { - return null; - } - if (marker.startsWith(FAMILY_PREFIX)) { - return decodeStructure(marker); - } - return decodeLegacy(marker); - } - - private static Decoded decodeStructure(String marker) { - if (!marker.startsWith(VERSION_PREFIX)) { - return null; - } - String[] fields = marker.split(":", -1); - if (fields.length != 5 || !fields[0].equals("@iris-structure") || !fields[1].equals("v1")) { - return null; - } - try { - String objectKey = decodeCanonicalKey(fields[2]); - int placementId = Integer.parseInt(fields[3]); - String structureKey = decodeCanonicalKey(fields[4]); - if (objectKey.isBlank() || structureKey.isBlank()) { - return null; - } - return new Decoded(objectKey, placementId, structureKey); - } catch (IllegalArgumentException exception) { - return null; - } - } - - private static Decoded decodeLegacy(String marker) { - int separator = marker.indexOf('@'); - if (separator <= 0 || separator != marker.lastIndexOf('@') || separator == marker.length() - 1) { - return null; - } - String objectKey = marker.substring(0, separator); - if (objectKey.isEmpty() || objectKey.equals("null")) { - return null; - } - try { - return new Decoded(objectKey, Integer.parseInt(marker.substring(separator + 1)), null); - } catch (NumberFormatException exception) { - return null; - } - } - - private static String requireKey(String key, String name) { - String required = Objects.requireNonNull(key, name); - if (required.isBlank()) { - throw new IllegalArgumentException(name + " must not be blank"); - } - return required; - } - - private static String encodeKey(String key) { - return Base64.getUrlEncoder().withoutPadding().encodeToString(key.getBytes(StandardCharsets.UTF_8)); - } - - private static String decodeCanonicalKey(String key) { - String decoded = new String(Base64.getUrlDecoder().decode(key), StandardCharsets.UTF_8); - if (!encodeKey(decoded).equals(key)) { - throw new IllegalArgumentException("Non-canonical marker key"); - } - return decoded; - } - - public record Decoded(String objectKey, int placementId, String structureKey) { - public boolean structureAware() { - return structureKey != null; - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 8302ca016..43565565f 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -36,6 +36,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; import com.volmit.ModuleSetup; +import com.volmit.service.ProtectedFloor; import com.volmit.stage.ChunkStageContext; import com.volmit.world.PackWorld; @@ -63,9 +64,15 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { WallSettings.class, LockLayersSettings.class, LockLayersMaxSettings.class, RockPaletteSettings.class, FluidPaletteSettings.class, OreSettings.class, HideOresSettings.class, BedrockSettings.class, ExplodeBiomePalettesSettings.class, ExplodeBiomePaletteSizeSettings.class); + registry.registerService(ProtectedFloor.class, TerrainModule::protectsFloor); registry.registerLifecycle(this); } + /** The bedrock row belongs to the terrain while the dimension has bedrock, as it does unless the pack says otherwise. */ + private static boolean protectsFloor(PackWorld world) { + return world.settings().declared(BedrockSettings.class).dimension().map(BedrockSettings::bedrock).orElse(true); + } + @Override public void warmUp(PackWorld world) { TerrainPalettes.of(world).warm(); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index e33a47d74..940a0e871 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -31,6 +31,7 @@ import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.OptionalLong; /** * How {@code iris:loot} fills containers: the tables of the object placed around a container, then those of the @@ -78,6 +79,12 @@ public final class LootGiving implements Loot { .draw(tableId.path(), table, lootSeed(world), site.position().x(), worldY, site.position().z()); } + @Override + public OptionalLong shuffleSeed(PackWorld world, Site site) { + int worldY = site.position().y() + world.minWorldY(); + return OptionalLong.of(LootResolver.containerSeed(lootSeed(world), site.position().x(), worldY, site.position().z())); + } + private static PlacementLoot placementLoot(PackWorld world) { return new PlacementLoot(world.resources(), () -> world.running().orElseThrow().platformLootTables(), lootSeed(world), world.log()); } diff --git a/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java b/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java index f73dadc74..baba31c0f 100644 --- a/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java +++ b/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java @@ -23,10 +23,11 @@ import art.arcane.iris.builtin.loot.ObjectVanillaLoot; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.builtin.structure.StructureHost; -import art.arcane.iris.builtin.structure.StructurePlacementMarker; import com.volmit.config.Level; import com.volmit.config.SettingsStack; +import com.volmit.placement.PlacementRecord; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; @@ -68,39 +69,39 @@ final class PlacedObjectLoot { /** The loot of the object placed at the block; empty when no object placement covers the block. Y is above the dimension's bottom. */ static Optional at(PackWorld world, int x, int y, int z) { RunningWorld running = world.running().orElseThrow(); - Optional marker = running.placementAt(x, y, z).map(StructurePlacementMarker::decode); - if (marker.isEmpty() || marker.get().objectKey().startsWith(PROCEDURAL_PREFIX)) { + Optional recorded = running.placementAt(x, y, z); + if (recorded.isEmpty() || recorded.get().object().path().startsWith(PROCEDURAL_PREFIX)) { return Optional.empty(); } - String objectKey = marker.get().objectKey(); - Optional placement = marker.get().structureAware() - ? structurePlacement(world, marker.get().structureKey(), objectKey) - : columnPlacement(running.settings().at(ObjectSettings.class, x, z), objectKey); + ResourceId object = recorded.get().object(); + Optional placement = recorded.get().structure().isPresent() + ? structurePlacement(world, recorded.get().structure().get(), object) + : columnPlacement(world.resources(), running.settings().at(ObjectSettings.class, x, z), object); return placement.map(found -> new ObjectLoots(found.loot(), found.vanillaLoot(), found.overrideGlobalLoot())); } /** A structure piece's object gives every table its structure names, each once. */ - private static Optional structurePlacement(PackWorld world, String structureKey, String objectKey) { - Optional> tables = world.extension(StructureHost.class).orElseThrow().lootTables(structureKey); - PackResources resources = world.resources(); - if (tables.isEmpty() || resources.objects().object(resources.idOf(objectKey)).isEmpty()) { + private static Optional structurePlacement(PackWorld world, ResourceId structure, ResourceId object) { + Optional> tables = world.extension(StructureHost.class).orElseThrow().lootTables(structure); + if (tables.isEmpty() || world.resources().objects().object(object).isEmpty()) { return Optional.empty(); } List loot = new ArrayList<>(); for (String table : tables.get()) { loot.add(new ObjectLoot(table, STRUCTURE_TABLE_WEIGHT)); } - return Optional.of(ObjectPlacement.builder().place(List.of(objectKey)).loot(loot).build()); + return Optional.of(ObjectPlacement.builder().place(List.of(object.path())).loot(loot).build()); } - private static Optional columnPlacement(SettingsStack declared, String objectKey) { - Optional fromRegion = declared.level(Level.REGION).flatMap(settings -> placing(settings, objectKey)); - return fromRegion.isPresent() ? fromRegion : declared.level(Level.BIOME).flatMap(settings -> placing(settings, objectKey)); + private static Optional columnPlacement(PackResources resources, SettingsStack declared, + ResourceId object) { + Optional fromRegion = declared.level(Level.REGION).flatMap(settings -> placing(resources, settings, object)); + return fromRegion.isPresent() ? fromRegion : declared.level(Level.BIOME).flatMap(settings -> placing(resources, settings, object)); } - private static Optional placing(ObjectSettings settings, String objectKey) { + private static Optional placing(PackResources resources, ObjectSettings settings, ResourceId object) { return settings.objects().stream() - .filter(placement -> placement.place().contains(objectKey)) + .filter(placement -> placement.place().stream().anyMatch(key -> resources.idOf(key).equals(object))) .findFirst(); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index c573acc2c..85505f258 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -47,6 +47,7 @@ import com.volmit.config.SettingsStack; import com.volmit.object.PlaceableObject; import com.volmit.resource.ResourceId; import com.volmit.stage.MantleStageContext; +import com.volmit.placement.PlacementRecord; import com.volmit.world.TerrainSampler; import java.util.List; @@ -570,7 +571,7 @@ final class ChunkObjectPlacing { return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure); } - private String placementMarker(PlaceableObject object, int id, String context) { + private PlacementRecord placementMarker(PlaceableObject object, int id, String context) { String key = object == null ? null : object.name(); if (key == null || key.isEmpty() || key.equals("null")) { String fingerprint = context + "|" + (object == null ? "" : object.getClass().getSimpleName()); @@ -578,7 +579,7 @@ final class ChunkObjectPlacing { + "This would previously produce 'Couldn't find Object: null' warnings on chunk reload."); return null; } - return key + "@" + id; + return PlacementRecord.of(this.context.world().resources().idOf(key), id); } private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java index 6cbf96ca8..1a2f61d87 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingPlacer.java @@ -36,6 +36,7 @@ import com.volmit.object.BlockEntityData; import com.volmit.object.ObjectBlock; import com.volmit.object.PlaceableObject; import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; import com.volmit.placement.PlacementTerrain; import com.volmit.stage.MantleStageContext; import com.volmit.world.PackWorld; @@ -161,10 +162,10 @@ final class FloatingPlacer { if (!run.placeIn(world, terrain).isPlaced()) { return false; } - String placementName = object.name() + "@" + id; + PlacementRecord placement = PlacementRecord.of(world.resources().idOf(object.name()), id); for (BlockPosition position : run.objectBlocks()) { if (placesBlock(terrain.get(position.x(), position.y(), position.z()))) { - terrain.recordPlacement(position.x(), position.y(), position.z(), placementName); + terrain.recordPlacement(position.x(), position.y(), position.z(), placement); } } return true; @@ -211,7 +212,7 @@ final class FloatingPlacer { } @Override - public void recordPlacement(int x, int y, int z, String placement) { + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { if (anchor.writes(x, y, z)) { delegate().recordPlacement(x, y, z, placement); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index d86dfe37e..9b11db0da 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; +import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; @@ -65,6 +66,7 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { registry.registerSettings(ObjectSettings.class, ProceduralObjectSettings.class, TreeGrowthSettings.class, RequireSurfaceSupportSettings.class, SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, UpperObjectsForceSettings.class); + registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); registry.registerLifecycle(this); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 3eccf6fb6..9b737349b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -38,6 +38,7 @@ import com.volmit.object.BlockEntityData; import com.volmit.object.PlaceableObject; import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; import com.volmit.placement.PlacementTerrain; import com.volmit.placement.StructureVolumes; import com.volmit.resource.ResourceId; @@ -242,11 +243,11 @@ public final class TreeGrowing implements SaplingGrowth { } @Override - public void recordPlacement(int x, int y, int z, String placement) { + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { } @Override - public Optional placementAt(int x, int y, int z) { + public Optional placementAt(int x, int y, int z) { return Optional.empty(); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index 04c77d077..078842843 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -21,7 +21,6 @@ package art.arcane.iris.engine.spawn; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.spawn.AmbientEffect; import art.arcane.iris.builtin.spawn.EntityDefinition; -import art.arcane.iris.builtin.spawn.IrisEntityExtras; import art.arcane.iris.builtin.spawn.SpawnCommand; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.engine.loot.LootItems; @@ -88,7 +87,7 @@ final class EntityResolution { return typeOf(entity).map(type -> new EntitySpec(type, appearanceOf(entity), behaviourOf(entity), equipment, attributes, new EntitySpec.Company(passengers, leashHolder), new EntitySpec.Drops(lootTables, lootShuffleSeed), - new EntitySpec.Arrival(spawnEffectOf(entity), commandsOf(entity)), List.of(extrasOf(entity)))); + arrivalOf(entity), entity.applySettingsToCustomMobAnyways(), List.of())); } /** The provider's mob when the pack names one, otherwise the entity type. */ @@ -106,7 +105,13 @@ final class EntityResolution { } private static EntitySpec.Appearance appearanceOf(EntityDefinition entity) { - return new EntitySpec.Appearance(textOf(entity.customName()), entity.customNameVisible(), entity.glowing(), entity.baby()); + return new EntitySpec.Appearance(textOf(entity.customName()), entity.customNameVisible(), entity.glowing(), entity.baby(), + textOf(entity.pandaMainGene()), textOf(entity.pandaHiddenGene())); + } + + private EntitySpec.Arrival arrivalOf(EntityDefinition entity) { + return new EntitySpec.Arrival(spawnEffectOf(entity), commandsOf(entity), textOf(entity.reason()), + entity.spawnEffectRiseOutOfGround()); } private static EntitySpec.Behaviour behaviourOf(EntityDefinition entity) { @@ -114,11 +119,6 @@ final class EntityResolution { entity.pickupItems(), entity.removable(), entity.keepEntity()); } - private static IrisEntityExtras extrasOf(EntityDefinition entity) { - return new IrisEntityExtras(textOf(entity.reason()), entity.spawnEffectRiseOutOfGround(), textOf(entity.pandaMainGene()), - textOf(entity.pandaHiddenGene()), entity.applySettingsToCustomMobAnyways()); - } - private Optional equip(LootEntry piece, RNG rng) { if (piece == null || !LootResolver.oneIn(rng, piece.rarity())) { return Optional.empty(); diff --git a/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java b/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java index d849582bf..b3b5866ab 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java +++ b/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java @@ -21,6 +21,7 @@ package art.arcane.iris.modules.objects; import com.volmit.block.BlockState; import com.volmit.object.BlockEntityData; import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; import com.volmit.placement.PlacementTerrain; import com.volmit.placement.StructureVolumes; @@ -85,12 +86,12 @@ public abstract class ForwardingTerrain implements PlacementTerrain { } @Override - public void recordPlacement(int x, int y, int z, String placement) { + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { delegate.recordPlacement(x, y, z, placement); } @Override - public Optional placementAt(int x, int y, int z) { + public Optional placementAt(int x, int y, int z) { return delegate.placementAt(x, y, z); } diff --git a/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java b/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java index f2f095030..71ab580e1 100644 --- a/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java +++ b/src/main/java/art/arcane/iris/modules/objects/PlacementTags.java @@ -18,12 +18,14 @@ package art.arcane.iris.modules.objects; +import com.volmit.placement.PlacementRecord; + /** * What a placement writes into the mantle besides the blocks, beside each block of the object. * - * @param marker the placement marker to write beside every block the object places, or null for none + * @param marker the placement to record beside every block the object places, or null for none * @param treeMaterial whether the block is also written as the tree material the mantle keeps for felling and growth * @param buriedTreasure whether storage chests among the blocks are marked as buried treasure */ -public record PlacementTags(String marker, boolean treeMaterial, boolean buriedTreasure) { +public record PlacementTags(PlacementRecord marker, boolean treeMaterial, boolean buriedTreasure) { } diff --git a/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java b/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java index fbe9bb8c9..932cabe6d 100644 --- a/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java +++ b/src/main/java/art/arcane/iris/modules/objects/TerrainTransaction.java @@ -22,6 +22,7 @@ import com.volmit.block.BlockState; import com.volmit.geometry.BlockPosition; import com.volmit.object.BlockEntityData; import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; import com.volmit.placement.PlacementTerrain; import java.util.ArrayList; @@ -97,16 +98,16 @@ public abstract class TerrainTransaction extends ForwardingTerrain { } @Override - public void recordPlacement(int x, int y, int z, String placement) { - writes.add(new PlacementRecord(new BlockPosition(x, y, z), placement)); + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + writes.add(new PlacementWrite(new BlockPosition(x, y, z), placement)); } @Override - public Optional placementAt(int x, int y, int z) { + public Optional placementAt(int x, int y, int z) { BlockPosition position = new BlockPosition(x, y, z); for (int index = writes.size() - 1; index >= 0; index--) { - if (writes.get(index) instanceof PlacementRecord record && record.position().equals(position)) { - return Optional.of(record.placement()); + if (writes.get(index) instanceof PlacementWrite write && write.position().equals(position)) { + return Optional.of(write.placement()); } } return delegate().placementAt(x, y, z); @@ -123,7 +124,7 @@ public abstract class TerrainTransaction extends ForwardingTerrain { blockWrites++; } - private sealed interface Write permits BlockWrite, PlacementRecord, MarkerWrite { + private sealed interface Write permits BlockWrite, PlacementWrite, MarkerWrite { BlockPosition position(); void applyTo(PlacementTerrain terrain); @@ -140,7 +141,7 @@ public abstract class TerrainTransaction extends ForwardingTerrain { } } - private record PlacementRecord(BlockPosition position, String placement) implements Write { + private record PlacementWrite(BlockPosition position, PlacementRecord placement) implements Write { @Override public void applyTo(PlacementTerrain terrain) { terrain.recordPlacement(position.x(), position.y(), position.z(), placement); diff --git a/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java b/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java index 55130be38..5fce7ac39 100644 --- a/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java +++ b/src/main/java/art/arcane/iris/modules/placement/StageTerrain.java @@ -18,9 +18,9 @@ package art.arcane.iris.modules.placement; -import art.arcane.iris.builtin.structure.StructurePlacementMarker; import art.arcane.iris.modules.blocks.SmartBoreDebugSettings; import com.volmit.placement.PlacementContext; +import com.volmit.placement.PlacementRecord; import com.volmit.placement.PlacementTerrain; import com.volmit.placement.StructureVolumes; import com.volmit.resource.ResourceId; @@ -115,15 +115,9 @@ public final class StageTerrain { /** The pack object placed at the block; empty when none was, or when a procedural object was. */ public Optional objectAt(int x, int y, int z) { - Optional recorded = terrain.placementAt(x, y, z); - if (recorded.isEmpty()) { - return Optional.empty(); - } - StructurePlacementMarker.Decoded marker = StructurePlacementMarker.decode(recorded.get()); - if (marker == null || marker.objectKey().startsWith(PROCEDURAL_PREFIX)) { - return Optional.empty(); - } - return Optional.of(context.world().resources().idOf(marker.objectKey())); + return terrain.placementAt(x, y, z) + .map(PlacementRecord::object) + .filter(object -> !object.path().startsWith(PROCEDURAL_PREFIX)); } private TerrainSampler sampler() { From e0dda1699cd3552dcccd1c5d2c05b836ea64a2d7 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 04:09:40 +0100 Subject: [PATCH 115/139] Move the vocabulary only Iris core uses back into Iris core 37 types of the object, value, image, world and runtime packages (the image map enums and exceptions, the registry list annotations, the engine data, the world boundary and environment, the custom biome enums, IrisRange) are read by Iris core alone. They keep their packages. The 11 that the module's structure model or ObjectRotation also reads stay. --- .../image/IrisImageMapSourceMetadata.java | 18 -- .../IrisImageMapValidationException.java | 35 ---- .../engine/object/annotations/DependsOn.java | 31 --- .../object/annotations/RegistryListBiome.java | 37 ---- .../annotations/RegistryListBlockType.java | 33 ---- .../annotations/RegistryListEnchantment.java | 14 -- .../annotations/RegistryListEntityType.java | 33 ---- .../object/annotations/RegistryListFont.java | 33 ---- .../annotations/RegistryListItemType.java | 33 ---- .../annotations/RegistryListPotionEffect.java | 14 -- .../RegistryListSpecialEntity.java | 33 ---- .../annotations/RegistryMapBlockState.java | 12 -- .../spawn/IrisEngineSpawnerCooldown.java | 36 ---- .../entity/spawn/IrisSpawnerCooldowns.java | 32 --- .../object/image/IrisImageColorMode.java | 9 - .../object/image/IrisImageMapAlpha.java | 11 -- .../object/image/IrisImageMapApplication.java | 13 -- .../engine/object/image/IrisImageMapMask.java | 33 ---- .../image/IrisImageMapMaskOperation.java | 12 -- .../object/image/IrisImageMapOrigin.java | 23 --- .../object/image/IrisImageMapOutOfBounds.java | 12 -- .../object/image/IrisImageMapRotation.java | 11 -- .../object/image/IrisImageMapSampling.java | 10 - .../engine/object/image/IrisImageMapType.java | 13 -- .../image/IrisImageMapUnknownColor.java | 10 - .../engine/object/runtime/IrisEngineData.java | 53 ----- .../object/runtime/IrisEngineStatistics.java | 67 ------- .../iris/engine/object/value/IrisRange.java | 59 ------ .../engine/object/world/IrisEnvironment.java | 36 ---- .../object/world/IrisWorldBoundary.java | 91 --------- .../object/world/IrisWorldBoundaryCenter.java | 29 --- .../object/world/biome/InferredType.java | 36 ---- .../biome/custom/IrisBiomeCustomCategory.java | 75 ------- .../custom/IrisBiomeCustomPrecipType.java | 33 ---- .../custom/IrisBiomeCustomSpawnType.java | 48 ----- .../biome/custom/IrisVanillaBiomeTags.java | 185 ------------------ .../IrisDimensionContractException.java | 25 --- 37 files changed, 1288 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java delete mode 100644 src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/value/IrisRange.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java diff --git a/src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java deleted file mode 100644 index 71a9bfce4..000000000 --- a/src/main/java/art/arcane/iris/engine/image/IrisImageMapSourceMetadata.java +++ /dev/null @@ -1,18 +0,0 @@ -package art.arcane.iris.engine.image; - -import art.arcane.iris.engine.object.image.IrisImageColorMode; - -public record IrisImageMapSourceMetadata( - String format, - IrisImageColorMode colorMode, - int width, - int height, - int colorComponents, - int channels, - int bitDepth, - boolean alpha, - double minimumAlpha, - double maximumAlpha, - String decodedContentHash -) { -} diff --git a/src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java b/src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java deleted file mode 100644 index 9c267b4a9..000000000 --- a/src/main/java/art/arcane/iris/engine/image/IrisImageMapValidationException.java +++ /dev/null @@ -1,35 +0,0 @@ -package art.arcane.iris.engine.image; - -import java.util.List; - -public final class IrisImageMapValidationException extends IllegalArgumentException { - private final List diagnostics; - - public IrisImageMapValidationException(String diagnostic) { - this(List.of(diagnostic)); - } - - public IrisImageMapValidationException(List diagnostics) { - super(message(diagnostics)); - if (diagnostics == null || diagnostics.isEmpty()) { - throw new IllegalArgumentException("Image-map validation requires at least one diagnostic"); - } - this.diagnostics = List.copyOf(diagnostics); - } - - public IrisImageMapValidationException(String diagnostic, Throwable cause) { - super(diagnostic, cause); - this.diagnostics = List.of(diagnostic); - } - - public List getDiagnostics() { - return diagnostics; - } - - private static String message(List diagnostics) { - if (diagnostics == null || diagnostics.isEmpty()) { - return "Image-map validation failed"; - } - return String.join("; ", diagnostics); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java b/src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java deleted file mode 100644 index 05c175a76..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/DependsOn.java +++ /dev/null @@ -1,31 +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.annotations; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Retention(RUNTIME) -@Target({FIELD}) -public @interface DependsOn { - String[] value(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java deleted file mode 100644 index 538c1b367..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBiome.java +++ /dev/null @@ -1,37 +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.object.annotations; - -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; - -/** - * Marks a String field (or a list of Strings) as a live biome-registry key, so schema completion offers every - * vanilla, datapack, and mod biome instead of nothing. - */ -@Retention(RUNTIME) -@Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListBiome { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java deleted file mode 100644 index 9c698782d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListBlockType.java +++ /dev/null @@ -1,33 +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.annotations; - -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 RegistryListBlockType { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java deleted file mode 100644 index 918fe7343..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEnchantment.java +++ /dev/null @@ -1,14 +0,0 @@ -package art.arcane.iris.engine.object.annotations; - -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 RegistryListEnchantment { -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java deleted file mode 100644 index 74473f2c5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListEntityType.java +++ /dev/null @@ -1,33 +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.object.annotations; - -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 RegistryListEntityType { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java deleted file mode 100644 index 83a8dc660..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListFont.java +++ /dev/null @@ -1,33 +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.annotations; - -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 RegistryListFont { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java deleted file mode 100644 index b1ff189dd..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListItemType.java +++ /dev/null @@ -1,33 +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.annotations; - -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 RegistryListItemType { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java deleted file mode 100644 index 9b8493c8f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListPotionEffect.java +++ /dev/null @@ -1,14 +0,0 @@ -package art.arcane.iris.engine.object.annotations; - -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 RegistryListPotionEffect { -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java deleted file mode 100644 index 528c33c47..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryListSpecialEntity.java +++ /dev/null @@ -1,33 +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.annotations; - -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 RegistryListSpecialEntity { - -} diff --git a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java b/src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java deleted file mode 100644 index c313daf93..000000000 --- a/src/main/java/art/arcane/iris/engine/object/annotations/RegistryMapBlockState.java +++ /dev/null @@ -1,12 +0,0 @@ -package art.arcane.iris.engine.object.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.FIELD) -public @interface RegistryMapBlockState { - String value(); -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java deleted file mode 100644 index 0a1db5c1b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisEngineSpawnerCooldown.java +++ /dev/null @@ -1,36 +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.entity.spawn; - -import art.arcane.volmlib.util.math.M; -import lombok.Data; - -@Data -public class IrisEngineSpawnerCooldown { - private long lastSpawn = 0; - private String spawner; - - public void spawn() { - lastSpawn = M.ms(); - } - - public boolean canSpawn(long intervalMilliseconds) { - return M.ms() - lastSpawn > intervalMilliseconds; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java b/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java deleted file mode 100644 index 1f0965cec..000000000 --- a/src/main/java/art/arcane/iris/engine/object/entity/spawn/IrisSpawnerCooldowns.java +++ /dev/null @@ -1,32 +0,0 @@ -package art.arcane.iris.engine.object.entity.spawn; - -import art.arcane.volmlib.util.collection.KMap; -import lombok.EqualsAndHashCode; -import lombok.NonNull; - -import java.util.function.ToLongFunction; - -@EqualsAndHashCode -public class IrisSpawnerCooldowns { - private final KMap cooldowns = new KMap<>(); - - public IrisEngineSpawnerCooldown getCooldown(@NonNull String loadKey) { - return cooldowns.computeIfAbsent(loadKey, k -> { - IrisEngineSpawnerCooldown cd = new IrisEngineSpawnerCooldown(); - cd.setSpawner(loadKey); - return cd; - }); - } - - /** Forgets the cooldowns that ran out and those of spawners {@code intervalMilliseconds} does not know (a negative interval). */ - public void cleanup(ToLongFunction intervalMilliseconds) { - cooldowns.values().removeIf(cd -> { - long interval = intervalMilliseconds.applyAsLong(cd.getSpawner()); - return interval < 0 || cd.canSpawn(interval); - }); - } - - public boolean isEmpty() { - return cooldowns.isEmpty(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java deleted file mode 100644 index 0aecfc259..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageColorMode.java +++ /dev/null @@ -1,9 +0,0 @@ -package art.arcane.iris.engine.object.image; - -public enum IrisImageColorMode { - GRAYSCALE, - RGB, - RGBA, - INDEXED, - UNSUPPORTED -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java deleted file mode 100644 index 338e2cd71..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapAlpha.java +++ /dev/null @@ -1,11 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("How alpha participates in decoded data") -public enum IrisImageMapAlpha { - IGNORE, - MASK, - TRANSPARENT_IS_FALLBACK, - ERROR -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java deleted file mode 100644 index d7ad2e1f6..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("The generation input controlled by an image map") -public enum IrisImageMapApplication { - TERRAIN_HEIGHT, - BIOME, - REGION, - SURFACE_BLOCK, - MASK, - CUSTOM -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java deleted file mode 100644 index 43ca5de04..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMask.java +++ /dev/null @@ -1,33 +0,0 @@ -package art.arcane.iris.engine.object.image; - -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.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("A composable reference to a named MASK image map") -@Data -public class IrisImageMapMask { - @Desc("The key of a named imageMaps entry whose application is MASK") - private String map = ""; - - @Desc("How this mask combines with masks before it") - private IrisImageMapMaskOperation operation = IrisImageMapMaskOperation.MULTIPLY; - - @Desc("Invert this mask before combining it") - private boolean inverted = false; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Values below this threshold become zero") - private double threshold = 0D; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Soft transition width above threshold; zero is a hard edge") - private double falloff = 0D; -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java deleted file mode 100644 index aa1708e83..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapMaskOperation.java +++ /dev/null @@ -1,12 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("How a referenced mask combines with masks before it") -public enum IrisImageMapMaskOperation { - MULTIPLY, - MINIMUM, - MAXIMUM, - ADD, - SUBTRACT -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java deleted file mode 100644 index fc2ee68a8..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOrigin.java +++ /dev/null @@ -1,23 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("A two-dimensional image-map coordinate") -@Data -public class IrisImageMapOrigin { - @Desc("X coordinate in world blocks for origin, or source pixels for sourceOrigin") - private double x = 0D; - - @Desc("Z coordinate in world blocks for origin, or source image Y pixels for sourceOrigin") - private double z = 0D; - - public IrisImageMapOrigin(double x, double z) { - this.x = x; - this.z = z; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java deleted file mode 100644 index a8bd749ae..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapOutOfBounds.java +++ /dev/null @@ -1,12 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("How coordinates outside an image are resolved") -public enum IrisImageMapOutOfBounds { - FALLBACK, - CLAMP, - REPEAT, - MIRROR, - ERROR -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java deleted file mode 100644 index 300c7c203..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapRotation.java +++ /dev/null @@ -1,11 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Clockwise image-map rotation around sourceOrigin") -public enum IrisImageMapRotation { - DEG_0, - DEG_90, - DEG_180, - DEG_270 -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java deleted file mode 100644 index f215ab5f4..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapSampling.java +++ /dev/null @@ -1,10 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("The filter used between source pixels") -public enum IrisImageMapSampling { - NEAREST, - BILINEAR, - BICUBIC -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java deleted file mode 100644 index 64ad766f9..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapType.java +++ /dev/null @@ -1,13 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("How Iris decodes each source pixel") -public enum IrisImageMapType { - GRAYSCALE_HEIGHT, - RGB_HEIGHT, - COLOR_MAP, - BINARY_MASK, - GRAYSCALE_MASK, - ALPHA_MASK -} diff --git a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java b/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java deleted file mode 100644 index 8d7e160b5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/image/IrisImageMapUnknownColor.java +++ /dev/null @@ -1,10 +0,0 @@ -package art.arcane.iris.engine.object.image; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("How a color absent from a color-map legend is handled") -public enum IrisImageMapUnknownColor { - ERROR, - FALLBACK, - IGNORE -} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java deleted file mode 100644 index 2db085788..000000000 --- a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineData.java +++ /dev/null @@ -1,53 +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.entity.spawn.IrisSpawnerCooldowns; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.volmlib.util.collection.KMap; -import lombok.Data; -import lombok.EqualsAndHashCode; - -import java.util.function.ToLongFunction; - -@Data -@EqualsAndHashCode(callSuper = true) -public class IrisEngineData extends IrisSpawnerCooldowns { - private IrisEngineStatistics statistics = new IrisEngineStatistics(); - private KMap chunks = new KMap<>(); - private Long seed = null; - - public void removeChunk(int x, int z) { - chunks.remove(CacheKey.key(x, z)); - } - - public IrisSpawnerCooldowns getChunk(int x, int z) { - return chunks.computeIfAbsent(CacheKey.key(x, z), k -> new IrisSpawnerCooldowns()); - } - - @Override - public void cleanup(ToLongFunction intervalMilliseconds) { - super.cleanup(intervalMilliseconds); - - chunks.values().removeIf(chunk -> { - chunk.cleanup(intervalMilliseconds); - return chunk.isEmpty(); - }); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java b/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.java deleted file mode 100644 index ae392297d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/runtime/IrisEngineStatistics.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 lombok.Data; - -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; - -@Data -public class IrisEngineStatistics { - private static final AtomicIntegerFieldUpdater TOTAL_HOTLOADS = - AtomicIntegerFieldUpdater.newUpdater(IrisEngineStatistics.class, "totalHotloads"); - private static final AtomicIntegerFieldUpdater CHUNKS_GENERATED = - AtomicIntegerFieldUpdater.newUpdater(IrisEngineStatistics.class, "chunksGenerated"); - - private volatile int totalHotloads = 0; - private volatile int chunksGenerated = 0; - private volatile int IrisToUpgradedVersion = 0; - private volatile int IrisCreationVersion = 0; - private volatile int MinecraftVersion = 0; - - public void generatedChunk() { - CHUNKS_GENERATED.incrementAndGet(this); - } - - public void setUpgradedVersion(int i) { - IrisToUpgradedVersion = i; - } - public int getUpgradedVersion() { - return IrisToUpgradedVersion; - } - public void setVersion(int i) { - IrisCreationVersion = i; - } - - public int getVersion() { - return IrisCreationVersion; - } - - public void setMCVersion(int i) { - MinecraftVersion = i; - } - - public int getMCVersion() { - return MinecraftVersion; - } - - public void hotloaded() { - TOTAL_HOTLOADS.incrementAndGet(this); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/value/IrisRange.java b/src/main/java/art/arcane/iris/engine/object/value/IrisRange.java deleted file mode 100644 index 9b2a2921e..000000000 --- a/src/main/java/art/arcane/iris/engine/object/value/IrisRange.java +++ /dev/null @@ -1,59 +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.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("range") -@Accessors(chain = true) -@NoArgsConstructor -@AllArgsConstructor -@Desc("Represents a range") -@Data -public class IrisRange { - @Desc("The minimum value") - private double min = 16; - - @Desc("The maximum value") - private double max = 32; - - public double get(RNG rng) { - if (min == max) { - return min; - } - - return rng.d(min, max); - } - - public boolean contains(int v) { - return v >= min && v <= max; - } - - public IrisRange merge(IrisRange other) { - min = Math.min(min, other.min); - max = Math.max(max, other.max); - return this; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java b/src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java deleted file mode 100644 index 3ec4976cd..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/IrisEnvironment.java +++ /dev/null @@ -1,36 +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.object.world; - -import art.arcane.iris.engine.object.annotations.Desc; - -@Desc("Represents a world environment") -public enum IrisEnvironment { - @Desc("The overworld environment") - NORMAL, - - @Desc("The nether environment") - NETHER, - - @Desc("The end environment") - THE_END, - - @Desc("A custom environment") - CUSTOM -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java b/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java deleted file mode 100644 index d63855e08..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundary.java +++ /dev/null @@ -1,91 +0,0 @@ -package art.arcane.iris.engine.object.world; - -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.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -import java.util.Objects; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("The native Minecraft world border applied to worlds using this dimension") -@Data -public class IrisWorldBoundary { - public static final double DEFAULT_DAMAGE_AMOUNT = 0.2D; - public static final double DEFAULT_DAMAGE_BUFFER = 5D; - public static final double MAXIMUM_CENTER = 29_999_984D; - public static final double MAXIMUM_SIZE = 59_999_968D; - - @Desc("The center of the boundary") - private IrisWorldBoundaryCenter center = new IrisWorldBoundaryCenter(); - - @MinNumber(1) - @MaxNumber(59_999_968) - @Desc("The full border diameter in blocks, matching Minecraft world-border terminology") - private double size = 16_384D; - - @MinNumber(0) - @MaxNumber(Integer.MAX_VALUE) - @Desc("Distance from the border at which the client warning begins") - private int warningDistance = 16; - - @MinNumber(0) - @Desc("Safe distance outside the border before damage begins") - private double damageBuffer = DEFAULT_DAMAGE_BUFFER; - - @MinNumber(0) - @Desc("Damage per block beyond damageBuffer") - private double damageAmount = DEFAULT_DAMAGE_AMOUNT; - - public static IrisWorldBoundary snapshot(IrisWorldBoundary configured) { - IrisWorldBoundary source = Objects.requireNonNull(configured, "Configured worldBoundary"); - source.validate(); - return new IrisWorldBoundary() - .setCenter(new IrisWorldBoundaryCenter(source.getCenter().getX(), source.getCenter().getZ())) - .setSize(source.getSize()) - .setWarningDistance(source.getWarningDistance()) - .setDamageBuffer(source.getDamageBuffer()) - .setDamageAmount(source.getDamageAmount()); - } - - public void validate() { - if (center == null) { - throw new IllegalArgumentException("worldBoundary.center is required"); - } - if (!Double.isFinite(center.getX()) || Math.abs(center.getX()) > MAXIMUM_CENTER - || !Double.isFinite(center.getZ()) || Math.abs(center.getZ()) > MAXIMUM_CENTER) { - throw new IllegalArgumentException("worldBoundary.center must be finite and within +/-" + MAXIMUM_CENTER); - } - if (!Double.isFinite(size) || size < 1D || size > MAXIMUM_SIZE) { - throw new IllegalArgumentException("worldBoundary.size must be between 1 and " + MAXIMUM_SIZE); - } - if (warningDistance < 0) { - throw new IllegalArgumentException("worldBoundary.warningDistance cannot be negative"); - } - if (!Double.isFinite(damageBuffer) || damageBuffer < 0D) { - throw new IllegalArgumentException("worldBoundary.damageBuffer must be finite and non-negative"); - } - if (!Double.isFinite(damageAmount) || damageAmount < 0D) { - throw new IllegalArgumentException("worldBoundary.damageAmount must be finite and non-negative"); - } - } - - public double minimumX() { - return center.getX() - size / 2D; - } - - public double maximumX() { - return center.getX() + size / 2D; - } - - public double minimumZ() { - return center.getZ() - size / 2D; - } - - public double maximumZ() { - return center.getZ() + size / 2D; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java b/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java deleted file mode 100644 index a860a437d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/IrisWorldBoundaryCenter.java +++ /dev/null @@ -1,29 +0,0 @@ -package art.arcane.iris.engine.object.world; - -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.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - -@Accessors(chain = true) -@NoArgsConstructor -@Desc("The world-border center in block coordinates") -@Data -public class IrisWorldBoundaryCenter { - @MinNumber(-29_999_984) - @MaxNumber(29_999_984) - @Desc("The world-border center X coordinate") - private double x = 0D; - - @MinNumber(-29_999_984) - @MaxNumber(29_999_984) - @Desc("The world-border center Z coordinate") - private double z = 0D; - - public IrisWorldBoundaryCenter(double x, double z) { - this.x = x; - this.z = z; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java b/src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java deleted file mode 100644 index 8256e91e4..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/InferredType.java +++ /dev/null @@ -1,36 +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.annotations.Desc; - -@Desc("Represents a biome type") -public enum InferredType { - @Desc("Represents any shore biome type") - SHORE, - - @Desc("Represents any land biome type") - LAND, - - @Desc("Represents any sea biome type") - SEA, - - @Desc("Represents any cave biome type") - CAVE -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java deleted file mode 100644 index a9727d366..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomCategory.java +++ /dev/null @@ -1,75 +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.engine.object.annotations.Desc; - -@Desc("The custom biome category. Vanilla asks for this, basically what represents your biome closest?") -public enum IrisBiomeCustomCategory { - @Desc("Tags the generated datapack biome as vanilla category 'beach' (shoreline biomes).") - beach, - - @Desc("Tags the generated datapack biome as vanilla category 'desert' (hot, dry sand biomes).") - desert, - - @Desc("Tags the generated datapack biome as vanilla category 'extreme_hills' (mountain biomes).") - extreme_hills, - - @Desc("Tags the generated datapack biome as vanilla category 'forest' (tree-dense temperate biomes).") - forest, - - @Desc("Tags the generated datapack biome as vanilla category 'icy' (snow and ice biomes).") - icy, - - @Desc("Tags the generated datapack biome as vanilla category 'jungle'.") - jungle, - - @Desc("Tags the generated datapack biome as vanilla category 'mesa' (badlands).") - mesa, - - @Desc("Tags the generated datapack biome as vanilla category 'mushroom' (mushroom fields).") - mushroom, - - @Desc("Tags the generated datapack biome as vanilla category 'nether'.") - nether, - - @Desc("Tags the generated datapack biome as vanilla category 'none' (no classification).") - none, - - @Desc("Tags the generated datapack biome as vanilla category 'ocean'.") - ocean, - - @Desc("Tags the generated datapack biome as vanilla category 'plains'. This is the default when category is omitted.") - plains, - - @Desc("Tags the generated datapack biome as vanilla category 'river'.") - river, - - @Desc("Tags the generated datapack biome as vanilla category 'savanna'.") - savanna, - - @Desc("Tags the generated datapack biome as vanilla category 'swamp'.") - swamp, - - @Desc("Tags the generated datapack biome as vanilla category 'taiga'.") - taiga, - - @Desc("Tags the generated datapack biome as vanilla category 'the_end'.") - the_end -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java deleted file mode 100644 index d54a7e1fe..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomPrecipType.java +++ /dev/null @@ -1,33 +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.engine.object.annotations.Desc; - -@Desc("Snow, rain, or nothing") -public enum IrisBiomeCustomPrecipType { - @Desc("No downfall") - none, - - @Desc("Rain downfall") - rain, - - @Desc("Snow downfall") - snow -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java deleted file mode 100644 index afeb577ea..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisBiomeCustomSpawnType.java +++ /dev/null @@ -1,48 +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.engine.object.annotations.Desc; - -@Desc("The mob spawn group") -public enum IrisBiomeCustomSpawnType { - @Desc("Typical monsters that spawn at night, like zombies and skeletons") - MONSTER, - - @Desc("Typical creatures like sheep, pigs, cows") - CREATURE, - - @Desc("Eg bats") - AMBIENT, - - @Desc("Axolotls") - AXOLOTLS, - - @Desc("Odd spawn group but ok") - UNDERGROUND_WATER_CREATURE, - - @Desc("Water mobs like squid, dolphins") - WATER_CREATURE, - - @Desc("Fish") - WATER_AMBIENT, - - @Desc("Unknown") - MISC -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java b/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java deleted file mode 100644 index 40eb0ea02..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/biome/custom/IrisVanillaBiomeTags.java +++ /dev/null @@ -1,185 +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.biome.custom; - -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - * Direct vanilla biome tag membership, generated from the MC 26.2 built-in datapack - * (data/minecraft/tags/worldgen/biome). Used to give Iris custom biomes the tag membership of the vanilla - * biome they derive from, so tag selectors written by vanilla and by mods (#minecraft:is_overworld and - * friends) resolve against Iris terrain. - * - *

Only DIRECT membership is listed. Vanilla's derived tags reference other tags rather than repeating - * biomes (#minecraft:is_ocean includes #minecraft:is_deep_ocean, water_on_map_outlines includes - * #minecraft:is_river, and so on), so adding a custom biome to the direct tags carries it into the derived - * tags for free. - * - *

The has_structure/* tags are deliberately absent. Iris resolves native structure placement through the - * biome's structure derivative, never through the custom biome, so injecting custom biomes there would place - * a structure twice. - * - *

{@code stronghold_biased_to} is absent for the same reason, even though it is not a has_structure tag. - * It is a structure-placement input: {@code worldgen/structure_set/strongholds.json} reads it as - * {@code preferred_biomes} when it rings strongholds around spawn. Inheriting it would enter every Iris biome - * derived from a tagged vanilla biome into that ring - which is the entire overworld surface of a typical pack - - * and let vanilla place strongholds where the pack's own structure configuration did not ask for them. - * - *

An unknown key (a mod biome, a datapack biome, or a vanilla biome added after 26.2) contributes nothing; - * the pack author's explicit tags still apply. - */ -public final class IrisVanillaBiomeTags { - private static final String TAG_NAMESPACE = "minecraft:"; - private static final Map> DIRECT_TAGS = new HashMap<>(96); - - private IrisVanillaBiomeTags() { - } - - /** - * Tags the given vanilla biome key belongs to directly. Never null; empty for unknown keys. Keys are - * returned fully namespaced and lowercase. - */ - public static List tagsFor(String biomeKey) { - if (biomeKey == null || biomeKey.isBlank()) { - return List.of(); - } - String normalized = biomeKey.trim().toLowerCase(Locale.ROOT); - if (normalized.indexOf(':') < 0) { - normalized = TAG_NAMESPACE + normalized; - } - List tags = DIRECT_TAGS.get(normalized); - return tags == null ? List.of() : tags; - } - - static int knownBiomeCount() { - return DIRECT_TAGS.size(); - } - - private static void put(String biomeKey, String... tagPaths) { - String[] namespaced = new String[tagPaths.length]; - for (int i = 0; i < tagPaths.length; i++) { - namespaced[i] = TAG_NAMESPACE + tagPaths[i]; - } - DIRECT_TAGS.put(biomeKey, List.of(namespaced)); - } - - static { - put("minecraft:badlands", "is_badlands", "is_overworld"); - put("minecraft:bamboo_jungle", "is_jungle", "is_overworld"); - put("minecraft:basalt_deltas", "is_nether"); - put("minecraft:beach", "is_beach", "is_overworld"); - put("minecraft:birch_forest", "is_forest", "is_overworld"); - put("minecraft:cherry_grove", "is_mountain", "is_overworld"); - put("minecraft:cold_ocean", "is_ocean", "is_overworld", "spawns_cold_variant_farm_animals"); - put("minecraft:crimson_forest", "is_nether"); - put("minecraft:dark_forest", "is_forest", "is_overworld"); - put("minecraft:deep_cold_ocean", "is_deep_ocean", "is_overworld", "spawns_cold_variant_farm_animals"); - put("minecraft:deep_dark", - "is_overworld", "mineshaft_blocking", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs"); - put("minecraft:deep_frozen_ocean", - "is_deep_ocean", "is_overworld", "polar_bears_spawn_on_alternate_blocks", "spawns_cold_variant_farm_animals", - "spawns_cold_variant_frogs"); - put("minecraft:deep_lukewarm_ocean", "is_deep_ocean", "is_overworld", "spawns_warm_variant_farm_animals"); - put("minecraft:deep_ocean", "is_deep_ocean", "is_overworld"); - put("minecraft:desert", - "is_overworld", "spawns_gold_rabbits", "spawns_warm_variant_farm_animals", "spawns_warm_variant_frogs"); - put("minecraft:dripstone_caves", "is_overworld"); - put("minecraft:end_barrens", "is_end"); - put("minecraft:end_highlands", "is_end"); - put("minecraft:end_midlands", "is_end"); - put("minecraft:eroded_badlands", "is_badlands", "is_overworld"); - put("minecraft:flower_forest", "is_forest", "is_overworld"); - put("minecraft:forest", "is_forest", "is_overworld"); - put("minecraft:frozen_ocean", - "is_ocean", "is_overworld", "polar_bears_spawn_on_alternate_blocks", "spawns_cold_variant_farm_animals", - "spawns_cold_variant_frogs", "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:frozen_peaks", - "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:frozen_river", - "is_overworld", "is_river", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:grove", - "is_forest", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:ice_spikes", - "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", "spawns_snow_foxes", - "spawns_white_rabbits"); - put("minecraft:jagged_peaks", - "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:jungle", "is_jungle", "is_overworld"); - put("minecraft:lukewarm_ocean", "is_ocean", "is_overworld", "spawns_warm_variant_farm_animals"); - put("minecraft:lush_caves", "allows_tropical_fish_spawns_at_any_height", "is_overworld"); - put("minecraft:mangrove_swamp", - "allows_surface_slime_spawns", "is_overworld", "spawns_warm_variant_farm_animals", - "spawns_warm_variant_frogs", "water_on_map_outlines"); - put("minecraft:meadow", "is_mountain", "is_overworld"); - put("minecraft:mushroom_fields", "is_overworld", "without_zombie_sieges"); - put("minecraft:nether_wastes", "is_nether"); - put("minecraft:ocean", "is_ocean", "is_overworld"); - put("minecraft:old_growth_birch_forest", "is_forest", "is_overworld"); - put("minecraft:old_growth_pine_taiga", - "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals"); - put("minecraft:old_growth_spruce_taiga", - "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals"); - put("minecraft:pale_garden", "is_forest", "is_overworld"); - put("minecraft:plains", "is_overworld"); - put("minecraft:river", "is_overworld", "is_river"); - put("minecraft:savanna", "is_overworld", "is_savanna"); - put("minecraft:savanna_plateau", "is_overworld", "is_savanna"); - put("minecraft:small_end_islands", "is_end"); - put("minecraft:snowy_beach", - "is_beach", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:snowy_plains", - "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", "spawns_snow_foxes", - "spawns_white_rabbits"); - put("minecraft:snowy_slopes", - "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:snowy_taiga", - "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals", "spawns_cold_variant_frogs", - "spawns_snow_foxes", "spawns_white_rabbits"); - put("minecraft:soul_sand_valley", "is_nether"); - put("minecraft:sparse_jungle", "is_jungle", "is_overworld"); - put("minecraft:stony_peaks", "is_mountain", "is_overworld", "spawns_cold_variant_farm_animals"); - put("minecraft:stony_shore", "is_overworld"); - put("minecraft:sulfur_caves", "is_overworld"); - put("minecraft:sunflower_plains", "is_overworld"); - put("minecraft:swamp", "allows_surface_slime_spawns", "is_overworld", "water_on_map_outlines"); - put("minecraft:taiga", "is_overworld", "is_taiga", "spawns_cold_variant_farm_animals"); - put("minecraft:the_end", "is_end"); - put("minecraft:the_void", "without_wandering_trader_spawns"); - put("minecraft:warm_ocean", - "is_ocean", "is_overworld", "produces_corals_from_bonemeal", "spawns_coral_variant_zombie_nautilus", - "spawns_warm_variant_farm_animals", "spawns_warm_variant_frogs"); - put("minecraft:warped_forest", "is_nether"); - put("minecraft:windswept_forest", - "is_hill", "is_overworld", "spawns_cold_variant_farm_animals"); - put("minecraft:windswept_gravelly_hills", - "is_hill", "is_overworld", "spawns_cold_variant_farm_animals"); - put("minecraft:windswept_hills", "is_hill", "is_overworld", "spawns_cold_variant_farm_animals"); - put("minecraft:windswept_savanna", "is_overworld", "is_savanna"); - put("minecraft:wooded_badlands", "is_badlands", "is_overworld"); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java b/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java deleted file mode 100644 index d23bd3d54..000000000 --- a/src/main/java/art/arcane/iris/engine/object/world/dimension/IrisDimensionContractException.java +++ /dev/null @@ -1,25 +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; - -public final class IrisDimensionContractException extends IllegalStateException { - public IrisDimensionContractException(String message) { - super(message); - } -} From 3ac971c0d92f1c4efc1fa365e90e62041b27230e Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 04:16:10 +0100 Subject: [PATCH 116/139] Name the pack table an item came from by its id --- .../arcane/iris/engine/loot/LootGiving.java | 2 +- .../arcane/iris/engine/loot/LootItems.java | 26 +++++++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java index 940a0e871..32c715e73 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootGiving.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootGiving.java @@ -76,7 +76,7 @@ public final class LootGiving implements Loot { } int worldY = site.position().y() + world.minWorldY(); return new LootItems(world.resources().items(), site.debug(), world.log()) - .draw(tableId.path(), table, lootSeed(world), site.position().x(), worldY, site.position().z()); + .draw(tableId, table, lootSeed(world), site.position().x(), worldY, site.position().z()); } @Override diff --git a/src/main/java/art/arcane/iris/engine/loot/LootItems.java b/src/main/java/art/arcane/iris/engine/loot/LootItems.java index 815c5280c..c83373b2d 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootItems.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootItems.java @@ -70,6 +70,15 @@ public final class LootItems { * asks for or runs out of tries. */ public List draw(String tableKey, LootTable table, long lootSeed, int x, int y, int z) { + return draw(tableKey, Optional.empty(), table, lootSeed, x, y, z); + } + + /** As {@link #draw(String, LootTable, long, int, int, int)} for the pack table {@code tableId}, which the items name as their source. */ + public List draw(ResourceId tableId, LootTable table, long lootSeed, int x, int y, int z) { + return draw(tableId.path(), Optional.of(tableId), table, lootSeed, x, y, z); + } + + private List draw(String tableKey, Optional tableId, LootTable table, long lootSeed, int x, int y, int z) { List drops = new ArrayList<>(); List entries = table.loot(); if (entries.isEmpty() || table.maxTries() <= 0) { @@ -86,7 +95,7 @@ public final class LootItems { if (entry == null || entry.slotTypes() != LootSlot.STORAGE) { continue; } - ItemDrop drop = drawEntry(entry, table, identity, rng, lootSeed, index, x, y, z); + ItemDrop drop = drawEntry(entry, table, tableId, identity, rng, lootSeed, index, x, y, z); if (drop != null) { drops.add(drop); } @@ -96,7 +105,7 @@ public final class LootItems { /** The item {@code entry} gives when nothing else decides whether it does, such as a block's drop or a mob's equipment; null for no item. */ public ItemDrop give(LootEntry entry, RNG rng) { - return resolve(entry, rng, null); + return resolve(entry, rng, null, Optional.empty()); } /** The attribute modifiers that pass their chances, with their amounts drawn, as for an item or an entity. */ @@ -117,15 +126,16 @@ public final class LootItems { return attributes; } - private ItemDrop drawEntry(LootEntry entry, LootTable table, String identity, RNG rng, long lootSeed, int index, int x, int y, int z) { + private ItemDrop drawEntry(LootEntry entry, LootTable table, Optional tableId, String identity, RNG rng, long lootSeed, + int index, int x, int y, int z) { long combinedRarity = LootResolver.combinedRarity(entry.rarity(), table.rarity()); if (!LootTables.spatialOneIn(lootSeed, identity, index, x, y, z, combinedRarity)) { return null; } - return resolve(entry, rng, table); + return resolve(entry, rng, table, tableId); } - private ItemDrop resolve(LootEntry entry, RNG rng, LootTable table) { + private ItemDrop resolve(LootEntry entry, RNG rng, LootTable table, Optional tableId) { Optional item = PlatformKeys.item(entry.type(), log); if (item.isEmpty() || item.get().equals(AIR)) { return null; @@ -143,7 +153,7 @@ public final class LootItems { : OptionalDouble.empty(); return new ItemDrop(item.get(), amount, lookOf(entry), enchantments, attributes, new ItemDrop.Wear(entry.unbreakable(), damage), new ItemDrop.PlatformExtras(entry.itemFlags(), Objects.requireNonNullElse(entry.customNbt(), Map.of())), - debug ? Optional.of(sourceOf(entry, table)) : Optional.empty()); + debug ? Optional.of(sourceOf(entry, table, tableId)) : Optional.empty()); } private ItemDrop.Look lookOf(LootEntry entry) { @@ -166,10 +176,10 @@ public final class LootItems { return enchantments; } - private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table) { + private static ItemDrop.Source sourceOf(LootEntry entry, LootTable table, Optional tableId) { if (table == null) { return new ItemDrop.Source(Optional.empty(), 0, entry.rarity()); } - return new ItemDrop.Source(Optional.ofNullable(table.name()), table.rarity(), entry.rarity()); + return new ItemDrop.Source(tableId, table.rarity(), entry.rarity()); } } From 9852f730a70cc50173f48350a236de7cb20d2377 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 5 Nov 2026 21:02:16 +0100 Subject: [PATCH 117/139] Read seeded noise styles flat in blocks Palette layers, the decorator chance gate and carving child biomes divide by their zoom or shrink factor only for a style without a seed; a seeded style is read in plain blocks, so its own zoom is its only scale and it lines up with every other reader of the same seed. Ported from v3e a1bd24186. IrisApi 2914ed1, Iris 3b9012535. --- .../iris/engine/decorator/ResolvedDecorator.java | 15 +++++++++++---- .../terrain/carving/ResolvedCarvingEntry.java | 7 +++++-- .../arcane/iris/modules/terrain/BiomeLayers.java | 4 ++-- .../arcane/iris/modules/terrain/LayerBlocks.java | 4 ++-- .../iris/modules/terrain/ResolvedLayer.java | 5 +++++ 5 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java index b9e19e593..1d8b330c3 100644 --- a/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java +++ b/src/main/java/art/arcane/iris/engine/decorator/ResolvedDecorator.java @@ -186,8 +186,16 @@ final class ResolvedDecorator { if (blocks.isEmpty()) { return false; } - double zoom = settings.style().zoom(); - return chanceNoise().sample(x / zoom, z / zoom) <= settings.chance(); + return chanceNoisePlacesAt(x, z); + } + + /** + * Whether the style noise stays under the chance at the column. A style without a seed divides by its zoom here on top + * of its own scale; a seeded one is read in plain blocks. + */ + private boolean chanceNoisePlacesAt(double x, double z) { + double blocksPerSample = settings.style().isSeeded() ? 1 : settings.style().zoom(); + return chanceNoise().sample(x / blocksPerSample, z / blocksPerSample) <= settings.chance(); } /** The block of the palette at the position, for decorations that fill a column block by block; null when the palette has no block. */ @@ -210,8 +218,7 @@ final class ResolvedDecorator { return blockAt(x, y, z); } - double zoom = settings.style().zoom(); - if (!(chanceNoise().sample(x / zoom, z / zoom) <= settings.chance())) { + if (!chanceNoisePlacesAt(x, z)) { return null; } diff --git a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java index cace6f3db..d47f11e93 100644 --- a/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java +++ b/src/main/java/art/arcane/iris/engine/object/terrain/carving/ResolvedCarvingEntry.java @@ -94,8 +94,11 @@ public final class ResolvedCarvingEntry { long idHash = settings.id().trim().hashCode(); long generatorSeed = seed ^ (idHash << 32) ^ CHILD_GENERATOR_SALT; return childGenerators.computeIfAbsent(generatorSeed, key -> { - double scale = Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor()); - return resources.noise().sampler(settings.childStyle(), key + CHILD_GENERATOR_SIGNATURE).scaled(scale); + NoiseSampler children = resources.noise().sampler(settings.childStyle(), key + CHILD_GENERATOR_SIGNATURE); + if (settings.childStyle().isSeeded()) { + return children; + } + return children.scaled(Math.max(MIN_CHILD_SCALE, settings.childShrinkFactor())); }); } } diff --git a/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java index 71906e315..949f103a5 100644 --- a/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java +++ b/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java @@ -246,9 +246,9 @@ public final class BiomeLayers { /** Adds the layer's block {@code j} blocks down; a layer that fails to pick adds nothing. */ private void addBlock(KList blocks, ResolvedLayer layer, int index, int j, double wx, double wz, RNG random) { - double zoom = layer.zoom(); + double blocksPerSample = layer.blocksPerSample(); try { - blocks.add(layer.get(random, index + j, (wx + j) / zoom, j, (wz - j) / zoom)); + blocks.add(layer.get(random, index + j, (wx + j) / blocksPerSample, j, (wz - j) / blocksPerSample)); } catch (Throwable e) { log.error("A biome layer failed to pick a block", e); } diff --git a/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java b/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java index 0887c3ac3..3f61e66ca 100644 --- a/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java +++ b/src/main/java/art/arcane/iris/modules/terrain/LayerBlocks.java @@ -71,8 +71,8 @@ public final class LayerBlocks { if (size <= 1) { return size - 1; } - double zoom = layer.zoom(); - double noise = layerPicks.noise(parent, signature).sample(x / zoom, y / zoom, z / zoom); + NoiseSampler sampler = layerPicks.noise(parent, signature); + double noise = layer.style().isSeeded() ? sampler.sample(x, z) : sampler.sample(x / layer.zoom(), y / layer.zoom(), z / layer.zoom()); int index = (int) Math.round(noise * (size - 1)); return index < 0 || index >= size ? 0 : index; } diff --git a/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java b/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java index f484309c4..669cf51d6 100644 --- a/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java +++ b/src/main/java/art/arcane/iris/modules/terrain/ResolvedLayer.java @@ -71,6 +71,11 @@ public final class ResolvedLayer { return settings.zoom(); } + /** How many blocks one step of the layer's block noise spans: its zoom, or 1 for a seeded style, which is read flat. */ + public double blocksPerSample() { + return settings.style().isSeeded() ? 1 : settings.zoom(); + } + public SlopeClip slopeCondition() { return settings.slopeCondition(); } From d65da9862499f5b802fea259365e0802b5335316 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 5 Nov 2026 21:14:53 +0100 Subject: [PATCH 118/139] Space surface objects apart and vary their chance with noise Ported from v3e (4be4f9774, 92a1fa645). An object placement can set a separation in blocks: each chunk rolls one candidate spot, and it stands only when no lower ranked candidate of a placement with the same objects lies closer. Spots and ranks come from the world seed, the chunk and the objects, so spacing holds across chunk, biome and region borders in any generation order. A chanceStyle multiplies the chance by noise. --- .../arcane/iris/builtin/IrisSeedPurposes.java | 2 + .../iris/builtin/objects/ObjectPlacement.java | 23 ++- .../mantle/components/ChunkObjectPlacing.java | 86 +++++++---- .../mantle/components/ObjectPlacing.java | 26 +++- .../modules/objects/ObjectSeparation.java | 140 ++++++++++++++++++ 5 files changed, 244 insertions(+), 33 deletions(-) create mode 100644 src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java index c292be806..11ec40496 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java @@ -38,6 +38,8 @@ public final class IrisSeedPurposes { public static final ResourceId MANTLE = purpose("mantle"); /** The noise that warps the columns of object placements with a surface warp. */ public static final ResourceId OBJECT_WARP = purpose("object-warp"); + /** The candidate spots, ranks and chance noise of separated object placements. */ + public static final ResourceId OBJECT_SEPARATION = purpose("object-separation"); public static final ResourceId POST = purpose("post"); public static final ResourceId TERRAIN = purpose("terrain"); diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index 9c6f0db63..715751a4b 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -98,8 +98,13 @@ public final class ObjectPlacement implements PlacementSource { @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; + @Desc("If set, chance is multiplied by this noise (0 to 1) at the chunk, so objects gather in some areas and thin out in others.") + private NoiseStyle chanceStyle = null; + @MinNumber(0) + @Desc("Keeps objects of this placement at least this many blocks apart, also across chunks and biomes that place the same objects. Each chunk then places at most one. 0 turns it off. Surface placements only.") + private int separation = 0; @MinNumber(1) - @Desc("If the chance check passes, place this many in a single chunk") + @Desc("If the chance check passes, place this many in a single chunk. Ignored when separation is set.") 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 StyledRange densityStyle = null; @@ -199,6 +204,8 @@ public final class ObjectPlacement implements PlacementSource { slopeCondition = source.slopeCondition; rotateTowardsSlope = source.rotateTowardsSlope; chance = source.chance; + chanceStyle = source.chanceStyle; + separation = source.separation; density = source.density; densityStyle = source.densityStyle; stiltSettings = source.stiltSettings; @@ -284,6 +291,20 @@ public final class ObjectPlacement implements PlacementSource { return chance; } + /** The noise, from 0 to 1, that {@link #chance()} is multiplied by at each chunk; empty when the chance is the same everywhere. */ + public Optional chanceStyle() { + return Optional.ofNullable(chanceStyle); + } + + /** The least distance in blocks between two objects of placements with the same objects; 0 when they are not kept apart. */ + public int separation() { + return separation; + } + + public boolean isSeparated() { + return separation > 0; + } + /** The count of placements when the chance check passes, unless {@link #densityStyle()} picks it. */ public int density() { return density; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 85505f258..809f5273a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -35,6 +35,7 @@ import art.arcane.iris.modules.objects.CavePlacement; import art.arcane.iris.modules.objects.TerrainTransaction; import art.arcane.iris.modules.objects.EffectiveSettings; import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ObjectSeparation; import art.arcane.iris.modules.objects.PlacementChanges; import art.arcane.iris.modules.objects.PlacementTags; import art.arcane.iris.modules.objects.ProceduralPlacement; @@ -73,6 +74,7 @@ final class ChunkObjectPlacing { private static final String REGEN_THREAD_PREFIX = "Iris-Regen-"; private final ObjectPool objects; + private final ObjectSeparation separation; private final ModuleLog log; private final MantleStageContext context; private final ObjectChunk chunk; @@ -91,6 +93,7 @@ final class ChunkObjectPlacing { ChunkObjectPlacing(ObjectPool objects, EffectiveSettings settings, ModuleLog log, MantleStageContext context) { this.objects = objects; + this.separation = ObjectSeparation.of(context.world()); this.log = log; this.context = context; this.chunk = new ObjectChunk(context, settings, log); @@ -241,13 +244,17 @@ final class ChunkObjectPlacing { private void placeSurfaceScope(Tally tally, String scope, List placements, String ownerName) { for (ObjectPlacement placement : placements) { tally.checked(scope); - boolean passes = rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER)); - traceChance(scope, passes, placement); - if (!passes) { - continue; - } - tally.triggered(scope); try { + if (placement.isSeparated()) { + placeSeparatedObject(tally, placement, scope); + continue; + } + boolean passes = rng.chance(separation.chanceAt(placement, centerX, centerZ) + rng.d(-CHANCE_JITTER, CHANCE_JITTER)); + traceChance(scope, passes, placement); + if (!passes) { + continue; + } + tally.triggered(scope); placeObject(tally, placement, scope); } catch (Throwable failure) { tally.errors++; @@ -256,6 +263,25 @@ final class ChunkObjectPlacing { } } + /** Places the one object the chunk's candidate stands for, when no closer candidate of a lower rank outranks it. */ + private void placeSeparatedObject(Tally tally, ObjectPlacement placement, String scope) { + Optional kept = separation.keptCandidate(chunkX, chunkZ, placement, context.settings()); + traceChance(scope, kept.isPresent(), placement); + if (kept.isEmpty()) { + return; + } + tally.triggered(scope); + ObjectSeparation.Candidate candidate = kept.get(); + tally.attempts++; + Optional picked = objects.pickScaled(placement, candidate.rng()); + if (picked.isEmpty()) { + tally.nullObjects++; + traceNullObject(scope, 0, 1, placement); + return; + } + placeOnSurfaceAt(tally, placement, scope, picked.get(), candidate.x(), candidate.z(), candidate.rng(), 0, 1); + } + private void placeCaveScope(Tally tally, String scope, List placements, CaveProfile profile, ResourceId expectedCaveBiome, String ownerName, CaveAnchors anchors) { for (ObjectPlacement placement : placements) { @@ -297,31 +323,35 @@ final class ChunkObjectPlacing { traceNullObject(scope, i, density, placement); continue; } - PlaceableObject object = picked.get(); int x = rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS); int z = rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS); - PlacementChanges changes = effective.forSurface(placement, object); - boolean treePlacement = isTreePlacement(object, placement); - int id = rng.i(0, Integer.MAX_VALUE); - String goldenTag = golden ? scope + "/" + object.name() : null; - if (golden) { - log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() - + " densityIndex=" + i + " xx=" + x + " zz=" + z + " mode=" + placement.mode()); - } - try { - PlacementTags tags = tags(object, id, "surface", treePlacement, placement); - int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, goldenTag); - if (result >= 0) { - tally.placed++; - } else { - tally.rejected++; - } - traceObjectResult(scope, object, result, x, z, i, density); - } catch (Throwable failure) { - tally.errors++; - log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() - + " densityIndex=" + i + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); + placeOnSurfaceAt(tally, placement, scope, picked.get(), x, z, rng, i, density); + } + } + + private void placeOnSurfaceAt(Tally tally, ObjectPlacement placement, String scope, PlaceableObject object, int x, int z, + RNG placingRng, int densityIndex, int density) { + PlacementChanges changes = effective.forSurface(placement, object); + boolean treePlacement = isTreePlacement(object, placement); + int id = placingRng.i(0, Integer.MAX_VALUE); + String goldenTag = golden ? scope + "/" + object.name() : null; + if (golden) { + log.debug("Goldendebug object attempt: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " densityIndex=" + densityIndex + " xx=" + x + " zz=" + z + " mode=" + placement.mode()); + } + try { + PlacementTags tags = tags(object, id, "surface", treePlacement, placement); + int result = chunk.placeOnSurface(object, x, z, placement, changes, tags, goldenTag); + if (result >= 0) { + tally.placed++; + } else { + tally.rejected++; } + traceObjectResult(scope, object, result, x, z, densityIndex, density); + } catch (Throwable failure) { + tally.errors++; + log.error("Regen object placement exception: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " object=" + object.name() + + " densityIndex=" + densityIndex + " density=" + density + " error=" + failure.getClass().getSimpleName() + ":" + failure.getMessage(), failure); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 3be711ca4..7cf5256a9 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -22,8 +22,10 @@ import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.modules.objects.EffectiveSettings; import art.arcane.iris.modules.objects.ObjectPool; +import art.arcane.iris.modules.objects.ObjectSeparation; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings; import com.volmit.config.Level; import com.volmit.config.SettingsStack; import com.volmit.object.PlaceableObject; @@ -47,12 +49,14 @@ public final class ObjectPlacing { private final PackWorld world; private final ObjectPool objects; + private final ObjectSeparation separation; private final EffectiveSettings settings = new EffectiveSettings(); private final ModuleLog log; private ObjectPlacing(PackWorld world) { this.world = world; this.objects = ObjectPool.of(world); + this.separation = ObjectSeparation.of(world); this.log = world.log(); } @@ -71,22 +75,36 @@ public final class ObjectPlacing { RNG rng = objects.chunkRandom(chunkX, chunkZ); int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; - SettingsStack declared = world.running().orElseThrow().settings().at(ObjectSettings.class, centerX, centerZ); + FeatureSettings worldSettings = world.running().orElseThrow().settings(); + SettingsStack declared = worldSettings.at(ObjectSettings.class, centerX, centerZ); Set keys = new HashSet<>(); for (Level level : GUESSED_LEVELS) { - declared.level(level).ifPresent(settings -> guessFrom(settings, rng, chunkX, chunkZ, keys)); + declared.level(level).ifPresent(settings -> guessFrom(settings, worldSettings, rng, chunkX, chunkZ, keys)); } return keys; } - private void guessFrom(ObjectSettings settings, RNG rng, int chunkX, int chunkZ, Set keys) { + private void guessFrom(ObjectSettings settings, FeatureSettings worldSettings, RNG rng, int chunkX, int chunkZ, Set keys) { + int centerX = (chunkX << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; + int centerZ = (chunkZ << CHUNK_SHIFT) + CHUNK_CENTER_OFFSET_BLOCKS; for (ObjectPlacement placement : settings.objects()) { - if (placement.carvingSupport().supportsSurface() && rng.chance(placement.chance() + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { + if (!placement.carvingSupport().supportsSurface()) { + continue; + } + if (placement.isSeparated()) { + guessSeparatedKey(chunkX, chunkZ, placement, worldSettings).ifPresent(keys::add); + } else if (rng.chance(separation.chanceAt(placement, centerX, centerZ) + rng.d(-CHANCE_JITTER, CHANCE_JITTER))) { keys.addAll(guessPlacedKeys(rng, chunkX, chunkZ, placement)); } } } + private Optional guessSeparatedKey(int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings worldSettings) { + return separation.keptCandidate(chunkX, chunkZ, placement, worldSettings) + .flatMap(candidate -> objects.pickScaled(placement, candidate.rng())) + .map(PlaceableObject::name); + } + private Set guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) { Set keys = new HashSet<>(); for (int i = 0; i < objects.density(placement, rng, x, z); i++) { diff --git a/src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java b/src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java new file mode 100644 index 000000000..b3c130ea0 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectSeparation.java @@ -0,0 +1,140 @@ +package art.arcane.iris.modules.objects; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The chance and spacing of surface object placements in a world. + * + *

A separated placement rolls one candidate spot per chunk. The candidate stands only when no candidate of a lower rank, + * from a placement with the same objects, lies closer than the separation. Spots and ranks come from the world seed, the + * chunk and the objects alone, so every chunk agrees on them across chunk, biome and region borders, and objects never + * stand closer than the separation, whatever order chunks generate in. + */ +public final class ObjectSeparation { + private static final int CHUNK_WIDTH_BLOCKS = 16; + private static final int CHUNK_SHIFT = 4; + /** Placements read a chunk's settings at local 8, 8, as Iris always did. */ + private static final int SETTINGS_COLUMN_OFFSET_BLOCKS = 8; + /** A chunk places the biome's objects before the region's, so the biome's placement speaks for the chunk. */ + private static final List PLACING_LEVELS = List.of(Level.BIOME, Level.REGION); + + private final PackWorld world; + private final long seed; + private final Map chanceNoises = new ConcurrentHashMap<>(); + + private ObjectSeparation(PackWorld world) { + this.world = world; + this.seed = world.seed(IrisSeedPurposes.OBJECT_SEPARATION); + } + + /** The separation of {@code world}. */ + public static ObjectSeparation of(PackWorld world) { + return world.state(ObjectSeparation.class, ObjectSeparation::new); + } + + /** The chance to place at the block column: the placement's chance, multiplied by its chance noise when it has one. */ + public double chanceAt(ObjectPlacement placement, double x, double z) { + Optional style = placement.chanceStyle(); + if (style.isEmpty()) { + return placement.chance(); + } + double noise = chanceNoises.computeIfAbsent(style.get(), declared -> world.resources().noise().sampler(declared, seed)).sample(x, z); + return placement.chance() * Math.max(0D, Math.min(1D, noise)); + } + + /** + * The candidate the chunk places for the separated placement; empty when it rolled none or a lower ranked one is too + * close. {@code settings} tells which placements the neighbouring chunks declare. + */ + public Optional keptCandidate(int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings settings) { + Optional own = candidateOf(chunkX, chunkZ, placement); + if (own.isEmpty() || isOutranked(own.get(), chunkX, chunkZ, placement, settings)) { + return Optional.empty(); + } + return own; + } + + private boolean isOutranked(Candidate own, int chunkX, int chunkZ, ObjectPlacement placement, FeatureSettings settings) { + int reach = placement.separation(); + for (int x = Math.floorDiv(own.x() - reach, CHUNK_WIDTH_BLOCKS); x <= Math.floorDiv(own.x() + reach, CHUNK_WIDTH_BLOCKS); x++) { + for (int z = Math.floorDiv(own.z() - reach, CHUNK_WIDTH_BLOCKS); z <= Math.floorDiv(own.z() + reach, CHUNK_WIDTH_BLOCKS); z++) { + if (x == chunkX && z == chunkZ) { + continue; + } + int rivalX = x; + int rivalZ = z; + Optional rival = placementOfSameObjectsAt(rivalX, rivalZ, placement.place(), settings) + .flatMap(other -> candidateOf(rivalX, rivalZ, other)); + if (rival.isPresent() && rival.get().rank() < own.rank() && rival.get().isCloserThan(own, reach)) { + return true; + } + } + } + return false; + } + + private static Optional placementOfSameObjectsAt(int chunkX, int chunkZ, List objects, FeatureSettings settings) { + int x = (chunkX << CHUNK_SHIFT) + SETTINGS_COLUMN_OFFSET_BLOCKS; + int z = (chunkZ << CHUNK_SHIFT) + SETTINGS_COLUMN_OFFSET_BLOCKS; + SettingsStack declared = settings.at(ObjectSettings.class, x, z); + for (Level level : PLACING_LEVELS) { + Optional placing = declared.level(level).flatMap(placements -> separatedPlacing(placements, objects)); + if (placing.isPresent()) { + return placing; + } + } + return Optional.empty(); + } + + private static Optional separatedPlacing(ObjectSettings settings, List objects) { + return settings.objects().stream() + .filter(placement -> placement.isSeparated() && placement.carvingSupport().supportsSurface() && placement.place().equals(objects)) + .findFirst(); + } + + private Optional candidateOf(int chunkX, int chunkZ, ObjectPlacement placement) { + RNG rng = new RNG(chunkSeed(chunkX, chunkZ, placement.place().hashCode())); + int x = (chunkX << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS); + int z = (chunkZ << CHUNK_SHIFT) + rng.nextInt(CHUNK_WIDTH_BLOCKS); + if (!rng.chance(chanceAt(placement, x, z))) { + return Optional.empty(); + } + return Optional.of(new Candidate(x, z, rng.nextLong(), rng)); + } + + // Each input is mixed in after the previous one: XORing scaled coordinates gave chunk x,z and -x,-z the same seed + // whenever both were odd. + private long chunkSeed(int chunkX, int chunkZ, int objectsHash) { + return splitMix(splitMix(splitMix(seed + objectsHash) + chunkX) + chunkZ); + } + + private static long splitMix(long value) { + long mixed = value + 0x9E3779B97F4A7C15L; + mixed = (mixed ^ (mixed >>> 30)) * 0xBF58476D1CE4E5B9L; + mixed = (mixed ^ (mixed >>> 27)) * 0x94D049BB133111EBL; + return mixed ^ (mixed >>> 31); + } + + /** Where a chunk would place, in block coordinates, with the random that picks and places the object there. */ + public record Candidate(int x, int z, long rank, RNG rng) { + boolean isCloserThan(Candidate other, int blocks) { + long dx = x - other.x; + long dz = z - other.z; + return dx * dx + dz * dz < (long) blocks * blocks; + } + } +} From 501862b9ea98469a15c39f74b44fd451fa1062bb Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 5 Nov 2026 21:28:12 +0100 Subject: [PATCH 119/139] Keep leaves from cutting logs Ported from v3e (3ba277aa4). Overlapping objects wrote over each other block by block, so one tree's leaves could cut another tree's trunk and leave the top floating. Leaves now keep a log already placed there, as in vanilla trees. --- .../engine/object/placement/BlocksModule.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index 6594a008b..c1707ab17 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -52,7 +52,7 @@ import java.util.Set; * Module {@code iris:blocks}: writes the object's blocks where the placement puts them, then its markers. * Each block is turned with the object, edited, warped, painted onto its column when the mode paints, * waterlogged in water and attached to the faces vines can hang from. Air is not written, except by - * structure pieces, and neither is a vine into a solid block or a melded block into open space. + * structure pieces, and neither is a vine into a solid block, leaves onto a log or a melded block into open space. */ public final class BlocksModule implements IrisModule { private static final Set AIR_MATERIALS = Set.of("minecraft:air", "minecraft:cave_air"); @@ -156,13 +156,23 @@ public final class BlocksModule implements IrisModule { if (world.has(data, BlockTrait.CUSTOM)) { return true; } - boolean vineIntoSolid = world.has(data, BlockTrait.VINE) && world.isSolid(x, y, z); - return shouldPlaceObjectBlock(structurePiece, AIR_MATERIALS.contains(data.material().toString()), vineIntoSolid); + return shouldPlaceObjectBlock(structurePiece, AIR_MATERIALS.contains(data.material().toString()), keepsExisting(world, data, x, y, z)); } - /** Air is written only by structure pieces, and a vine never replaces a solid block. */ - static boolean shouldPlaceObjectBlock(boolean structurePiece, boolean air, boolean vineIntoSolid) { - return !vineIntoSolid && (structurePiece || !air); + /** + * A vine never replaces a solid block, and leaves never cut a log another object already placed, as in vanilla + * trees: the log above the cut would float. + */ + private static boolean keepsExisting(PlacementWorld world, BlockState data, int x, int y, int z) { + if (world.has(data, BlockTrait.VINE)) { + return world.isSolid(x, y, z); + } + return world.has(data, BlockTrait.LEAVES) && world.has(world.get(x, y, z), BlockTrait.LOG); + } + + /** Air is written only by structure pieces, and nothing is written where the existing block is kept. */ + static boolean shouldPlaceObjectBlock(boolean structurePiece, boolean air, boolean keepsExisting) { + return !keepsExisting && (structurePiece || !air); } /** Whether a waterloggable block lands in water a waterloggable or underwater placement keeps. */ From d2ce5f4a05950ee14f8186280617a726391a43b2 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 5 Nov 2026 23:00:20 +0100 Subject: [PATCH 120/139] Port v3e's parts-based procedural objects The 37 part classes from v3e (dev) now live in engine/procedural, outside the host's own type package, so the built-ins jar may register them as a resource kind. ProceduralObjectCatalog reads iris:objects/procedural definitions from the pack's procedural/ folder and bakes their variants per world (or detached, for reach); ObjectPool places procedural/ and procedural/# keys like any object and warms them, and ObjectChunk keeps their baked leaves. ProceduralValue reads its forms (number, range, keyframes, curve shape) through IrisApi's @JsonForms codec instead of Gson. Trees: procedural/trees/ counts as a tree folder and TreeGrowing reports every variant it places as a tree. The v4-era kinds (tree, ruin, formation, coral, fungi, crystal), ProceduralPlacement, ProceduralObjectSettings and PlacementSource are removed; ObjectPlacement is the one placement. --- README.md | 5 +- builtin-modules.txt | 2 +- .../iris/builtin/objects/ObjectPlacement.java | 10 +- .../iris/builtin/objects/PlacementSource.java | 42 -- .../mantle/components/CaveSettings.java | 6 +- .../mantle/components/ChunkObjectPlacing.java | 149 +---- .../components/EffectivePlacements.java | 10 +- .../components/FloatingObjectPlacing.java | 5 +- .../engine/mantle/components/ObjectChunk.java | 33 +- .../mantle/components/ObjectModule.java | 13 +- .../mantle/components/ObjectPlacing.java | 4 +- .../mantle/components/ObjectWarmUp.java | 15 - .../mantle/components/PlacementReach.java | 38 +- .../engine/mantle/components/TreeGrowing.java | 41 +- .../procedural/IrisProceduralBlocks.java | 134 ----- .../procedural/ResolvedProceduralObjects.java | 76 --- .../ResolvedProceduralPlacement.java | 181 ------- .../object/procedural/coral/CoralCanvas.java | 64 --- .../procedural/coral/CoralGenerator.java | 263 --------- .../procedural/coral/ResolvedCoral.java | 43 -- .../crystal/CrystalBaseBuilder.java | 49 -- .../procedural/crystal/CrystalCanvas.java | 52 -- .../procedural/crystal/CrystalGenerator.java | 112 ---- .../procedural/crystal/CrystalGeometry.java | 85 --- .../crystal/CrystalShardBuilder.java | 125 ----- .../procedural/crystal/ResolvedCrystal.java | 43 -- .../formation/FormationBlockResolver.java | 67 --- .../procedural/formation/FormationCanvas.java | 61 --- .../formation/FormationGenerator.java | 75 --- .../formation/FormationProfiles.java | 58 -- .../formation/FormationShapeBuilder.java | 429 --------------- .../formation/ResolvedFormation.java | 48 -- .../procedural/fungi/FungusCapBuilder.java | 119 ---- .../procedural/fungi/FungusGenerator.java | 104 ---- .../procedural/fungi/FungusShelfBuilder.java | 81 --- .../procedural/fungi/FungusStemBuilder.java | 95 ---- .../procedural/fungi/ResolvedFungus.java | 76 --- .../object/procedural/ruin/ResolvedRuin.java | 43 -- .../procedural/ruin/RuinBlockCanvas.java | 107 ---- .../procedural/ruin/RuinDecoratorApplier.java | 122 ----- .../object/procedural/ruin/RuinGenerator.java | 200 ------- .../object/procedural/ruin/RuinShapes.java | 146 ----- .../tree/ProceduralTreeGenerator.java | 127 ----- .../object/procedural/tree/ResolvedTree.java | 96 ---- .../procedural/tree/TreeBlockCanvas.java | 102 ---- .../procedural/tree/TreeBlockResolver.java | 165 ------ .../procedural/tree/TreeCanopyBuilder.java | 352 ------------ .../procedural/tree/TreeDecoratorApplier.java | 280 ---------- .../object/procedural/tree/TreeFunctions.java | 197 ------- .../procedural/tree/TreePlausibility.java | 109 ---- .../object/procedural/tree/TreeProfiles.java | 80 --- .../procedural/tree/TreeRootBuilder.java | 154 ------ .../object/procedural/tree/TreeSupport.java | 90 --- .../procedural/tree/TreeTrunkBuilder.java | 202 ------- .../iris/engine/procedural/BakeProfile.java | 85 +++ .../procedural/IrisProceduralBlocks.java | 100 ++++ .../procedural/ProceduralObjectCatalog.java | 142 +++++ .../procedural/ProceduralShape.java | 2 +- .../engine/procedural/ProceduralVariants.java | 152 ++++++ .../engine/procedural/part/BlobShape.java | 160 ++++++ .../engine/procedural/part/BlockChoice.java | 45 ++ .../procedural/part/BranchAzimuth.java} | 25 +- .../procedural/part/ClusterLayout.java} | 21 +- .../procedural/part/DecorationSpot.java} | 25 +- .../engine/procedural/part/Decorator.java | 271 ++++++++++ .../engine/procedural/part/LeafDecay.java | 132 +++++ .../procedural/part/MaterialPainter.java | 135 +++++ .../engine/procedural/part/MaterialRule.java | 85 +++ .../engine/procedural/part/ObjectBaker.java | 120 ++++ .../iris/engine/procedural/part/PartBlob.java | 108 ++++ .../engine/procedural/part/PartBranches.java | 107 ++++ .../engine/procedural/part/PartCanvas.java | 140 +++++ .../engine/procedural/part/PartCluster.java | 60 ++ .../iris/engine/procedural/part/PartFill.java | 41 ++ .../engine/procedural/part/PartGrower.java | 201 +++++++ .../procedural/part/PartMode.java} | 18 +- .../engine/procedural/part/PartNoise.java | 98 ++++ .../engine/procedural/part/PartOffset.java | 41 ++ .../engine/procedural/part/PartOutline.java | 134 +++++ .../part/PartPattern.java} | 13 +- .../engine/procedural/part/PartSection.java | 32 ++ .../engine/procedural/part/PartShape.java | 48 ++ .../iris/engine/procedural/part/PartSpot.java | 36 ++ .../iris/engine/procedural/part/PartStem.java | 170 ++++++ .../engine/procedural/part/PartTrace.java | 39 ++ .../procedural/part/ProceduralDecoration.java | 96 ++++ .../procedural/part/ProceduralMaterial.java | 63 +++ .../procedural/part/ProceduralObject.java | 98 ++++ .../procedural/part/ProceduralPart.java | 127 +++++ .../procedural/part/ProceduralSpan.java | 55 ++ .../procedural/part/ProceduralValue.java | 299 ++++++++++ .../part/ResolvedProceduralObject.java | 56 ++ .../part/RuleFace.java} | 18 +- .../iris/engine/procedural/part/Sections.java | 37 ++ .../engine/procedural/part/StemShape.java | 243 +++++++++ .../iris/engine/procedural/part/Vectors.java | 96 ++++ .../modules/objects/EffectiveSettings.java | 36 +- .../iris/modules/objects/ObjectBuilder.java | 6 + .../iris/modules/objects/ObjectPool.java | 21 +- .../objects/ProceduralObjectSettings.java | 99 ---- .../modules/objects/ProceduralPlacement.java | 97 ---- .../iris/modules/objects/coral/Coral.java | 344 ------------ .../iris/modules/objects/coral/CoralForm.java | 39 -- .../iris/modules/objects/crystal/Crystal.java | 314 ----------- .../objects/crystal/CrystalSurface.java | 33 -- .../modules/objects/formation/Formation.java | 447 --------------- .../objects/formation/FormationForm.java | 45 -- .../objects/formation/FormationProfile.java | 35 -- .../iris/modules/objects/fungi/Fungus.java | 355 ------------ .../modules/objects/fungi/FungusCapShape.java | 35 -- .../iris/modules/objects/ruin/Ruin.java | 286 ---------- .../modules/objects/ruin/RuinDecorator.java | 78 --- .../iris/modules/objects/ruin/RuinForm.java | 35 -- .../iris/modules/objects/tree/Tree.java | 511 ------------------ .../modules/objects/tree/TreeAzimuthMode.java | 45 -- .../objects/tree/TreeBranchProbability.java | 47 -- .../modules/objects/tree/TreeBranches.java | 237 -------- .../iris/modules/objects/tree/TreeCanopy.java | 102 ---- .../modules/objects/tree/TreeDecorator.java | 85 --- .../objects/tree/TreeDecoratorTarget.java | 45 -- .../modules/objects/tree/TreeFunction.java | 47 -- .../iris/modules/objects/tree/TreeLayer.java | 45 -- .../modules/objects/tree/TreeLeafMode.java | 43 -- .../modules/objects/tree/TreeProfile.java | 53 -- .../objects/tree/TreeSecondaryLeaf.java | 50 -- .../modules/objects/tree/TreeSubBranches.java | 93 ---- 126 files changed, 4031 insertions(+), 9036 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java delete mode 100644 src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java rename src/main/java/art/arcane/iris/engine/{object => }/procedural/ProceduralShape.java (95%) create mode 100644 src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java rename src/main/java/art/arcane/iris/{modules/objects/coral/CoralBranchAzimuth.java => engine/procedural/part/BranchAzimuth.java} (57%) rename src/main/java/art/arcane/iris/{modules/objects/tree/TreeRootStyle.java => engine/procedural/part/ClusterLayout.java} (62%) rename src/main/java/art/arcane/iris/{modules/objects/ruin/RuinDecoratorTarget.java => engine/procedural/part/DecorationSpot.java} (56%) create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java rename src/main/java/art/arcane/iris/{modules/objects/crystal/CrystalDistribution.java => engine/procedural/part/PartMode.java} (59%) create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java rename src/main/java/art/arcane/iris/engine/{object/procedural/crystal/CrystalRole.java => procedural/part/PartPattern.java} (70%) create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java rename src/main/java/art/arcane/iris/engine/{object/procedural/fungi/FungusCellRole.java => procedural/part/RuleFace.java} (69%) create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/Sections.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java create mode 100644 src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/coral/Coral.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/formation/Formation.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/Tree.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java diff --git a/README.md b/README.md index 63a08a3c2..8d9f8b9ba 100644 --- a/README.md +++ b/README.md @@ -67,8 +67,9 @@ placement itself, read by the module decoder like any settings class, and the on stages into the chunk's mantle (on the surface, in a cave inside the cave's bounds, or hung from the terrain above), reading the carved space the cave carver planned, and the loot an object placed at a block defines; the layout, the settings of a column and the upper dimension's objects come from IrisApi (`TerrainSampler`, `FeatureSettings`, `UpperDimension`). `ObjectPlacing` and its helpers (`ChunkObjectPlacing`, -`CaveAnchors`, `PlacementReach`) decide what to place and where. The procedural generators (`engine/object/procedural`) stay -compiled in, behind `ProceduralPlacement`, until they build `GeneratedObject`s instead of Iris objects. +`CaveAnchors`, `PlacementReach`) decide what to place and where. Procedural objects (`engine/procedural`, resource kind +`iris:objects/procedural`, folder `procedural`) are definitions of parts that bake into variants; a placement names them as +`procedural/`, or `procedural/#` for one variant, like any object. `iris:loot` owns the loot table resource kind (`LootResources`, folder `loot`), checks the tables and the references to them (`LootValidator`), and provides `Loot` (`LootGiving`: which tables a container draws from and the `ItemDrop`s a table gives) and `BlockDrops` (`BlockDropping`). `iris:spawn` owns spawners, entities and markers (`SpawnResources`, diff --git a/builtin-modules.txt b/builtin-modules.txt index 9d5af6cac..2be9067bf 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -88,7 +88,7 @@ include art/arcane/iris/engine/mantle/components/ObjectLocating*.class include art/arcane/iris/engine/mantle/components/TreeGrowing*.class include art/arcane/iris/engine/mantle/components/ObjectChunk*.class include art/arcane/iris/engine/mantle/components/GoldenDebugTerrain*.class -include art/arcane/iris/engine/object/procedural/** +include art/arcane/iris/engine/procedural/** module art.arcane.iris.engine.modifier.FloatingModule include art/arcane/iris/engine/modifier/FloatingIslands*.class include art/arcane/iris/engine/object/terrain/floating/** diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index 715751a4b..bd2588322 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -70,7 +70,7 @@ import java.util.TreeSet; @Snippet("iris/objects/object-placer") @Desc("Represents an iris object placer. It places objects.") @JsonAdapter(ObjectPlacement.KeepingItsJson.class) -public final class ObjectPlacement implements PlacementSource { +public final class ObjectPlacement { private static final int DEFAULT_SURFACE_SUPPORT_BUFFER = 2; private static final int DEFAULT_SURFACE_SUPPORT_DEPTH = 2; @@ -273,7 +273,6 @@ public final class ObjectPlacement implements PlacementSource { return snow; } - @Override public boolean isDolphinTarget() { return isDolphinTarget; } @@ -286,7 +285,6 @@ public final class ObjectPlacement implements PlacementSource { return rotateTowardsSlope; } - @Override public double chance() { return chance; } @@ -342,17 +340,14 @@ public final class ObjectPlacement implements PlacementSource { return boreExtendMinY; } - @Override public boolean underwater() { return underwater; } - @Override public CarvingMode carvingSupport() { return carvingSupport; } - @Override public int surfaceSupportBuffer() { return surfaceSupportBuffer; } @@ -361,12 +356,10 @@ public final class ObjectPlacement implements PlacementSource { return surfaceSupportDepth; } - @Override public boolean requireSurfaceSupport() { return requireSurfaceSupport; } - @Override public CaveAnchorMode caveAnchorMode() { return caveAnchorMode; } @@ -408,7 +401,6 @@ public final class ObjectPlacement implements PlacementSource { return warp; } - @Override public ObjectPlaceMode mode() { return mode; } diff --git a/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java b/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java deleted file mode 100644 index 96a33efd0..000000000 --- a/src/main/java/art/arcane/iris/builtin/objects/PlacementSource.java +++ /dev/null @@ -1,42 +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.builtin.objects; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.carve.CaveAnchorMode; - -/** What a placement is read from: an object placement of a biome or region, or a procedural object. */ -public interface PlacementSource { - double chance(); - - ObjectPlaceMode mode(); - - CarvingMode carvingSupport(); - - CaveAnchorMode caveAnchorMode(); - - boolean underwater(); - - boolean requireSurfaceSupport(); - - int surfaceSupportBuffer(); - - boolean isDolphinTarget(); -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java index 9a9de5bb7..a62b89d82 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveSettings.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.modules.carve.CaveProfile; -import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.builtin.objects.ObjectPlacement; /** What a cave object placement takes from the cave profile that applies to it. */ final class CaveSettings { @@ -51,7 +51,7 @@ final class CaveSettings { } /** How the placement looks for its anchor in caves: its own mode, else the profile's, else the floor; turned upside down, the ceiling. */ - CaveAnchors.Search searchFor(PlacementSource placement, CaveProfile profile) { + CaveAnchors.Search searchFor(ObjectPlacement placement, CaveProfile profile) { CaveAnchorMode mode = anchorMode(placement, profile); if (placement.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { mode = CaveAnchorMode.CEILING; @@ -59,7 +59,7 @@ final class CaveSettings { return new CaveAnchors.Search(mode, scanStep(profile), minDepthBelowSurface(profile), searchAttempts(profile)); } - private static CaveAnchorMode anchorMode(PlacementSource placement, CaveProfile profile) { + private static CaveAnchorMode anchorMode(ObjectPlacement placement, CaveProfile profile) { CaveAnchorMode placementMode = placement.caveAnchorMode(); if (placementMode != null && !placementMode.equals(CaveAnchorMode.PROFILE_DEFAULT)) { return placementMode; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index 809f5273a..fae8e63b0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -24,21 +24,17 @@ import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.objects.PlacementSource; -import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.modules.objects.CavePlacement; import art.arcane.iris.modules.objects.TerrainTransaction; -import art.arcane.iris.modules.objects.EffectiveSettings; import art.arcane.iris.modules.objects.ObjectPool; import art.arcane.iris.modules.objects.ObjectSeparation; import art.arcane.iris.modules.objects.PlacementChanges; import art.arcane.iris.modules.objects.PlacementTags; -import art.arcane.iris.modules.objects.ProceduralPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.IrisFeature; import com.volmit.ModuleLog; @@ -56,8 +52,8 @@ import java.util.Optional; import java.util.OptionalInt; /** - * Places what the objects of one chunk's region and biomes say: the objects of its surface, caves and the terrain stacked above, - * and its procedural objects, in that order, all drawing from the one random of the chunk. + * Places what the objects of one chunk's region and biomes say: the objects of its surface, caves and the terrain stacked + * above, in that order, all drawing from the one random of the chunk. */ final class ChunkObjectPlacing { /** Objects read their chunk's settings at local 8, 8 as Iris always did, not at the API's centre column (local 7, 7): moving it would move objects. */ @@ -91,12 +87,12 @@ final class ChunkObjectPlacing { private final int worldHeight; private final int caveLavaHeight; - ChunkObjectPlacing(ObjectPool objects, EffectiveSettings settings, ModuleLog log, MantleStageContext context) { + ChunkObjectPlacing(ObjectPool objects, ModuleLog log, MantleStageContext context) { this.objects = objects; this.separation = ObjectSeparation.of(context.world()); this.log = log; this.context = context; - this.chunk = new ObjectChunk(context, settings, log); + this.chunk = new ObjectChunk(context, log); this.terrain = context.terrain(); this.chunkX = context.chunkX(); this.chunkZ = context.chunkZ(); @@ -121,7 +117,6 @@ final class ChunkObjectPlacing { logLayerStart(column); } Tally tally = placeObjects(column); - placeProceduralObjects(column); if (upperObjectsEnabled()) { placeUpperObjects(column); } @@ -136,8 +131,7 @@ final class ChunkObjectPlacing { ResourceId surface = terrain.surfaceBiome(centerX, centerZ); int surfaceY = terrain.surfaceHeight(centerX, centerZ); ResourceId cave = resolveCaveObjectBiome(surfaceY, surface); - return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), proceduralOf(cave, region, surface), - profilesOf(cave, region, surface)); + return new Column(region, surface, cave, surfaceY, objectsOf(cave, region, surface), profilesOf(cave, region, surface)); } private ResourceId resolveCaveObjectBiome(int surfaceY, ResourceId surfaceBiome) { @@ -169,12 +163,6 @@ final class ChunkObjectPlacing { levelValue(declared, Level.REGION)); } - private ColumnProcedural proceduralOf(ResourceId cave, ResourceId region, ResourceId surface) { - SettingsStack declared = context.settings().at(ProceduralObjectSettings.class, centerX, centerZ); - return new ColumnProcedural(levelValue(declared, Level.BIOME), - caveSettings(cave, surface, declared, ProceduralObjectSettings.class), levelValue(declared, Level.REGION)); - } - private ColumnProfiles profilesOf(ResourceId cave, ResourceId region, ResourceId surface) { SettingsStack declared = context.settings().at(CaveProfile.class, centerX, centerZ); return new ColumnProfiles(levelValue(declared, Level.BIOME), caveSettings(cave, surface, declared, CaveProfile.class), @@ -415,115 +403,6 @@ final class ChunkObjectPlacing { return contained.commit() == TerrainTransaction.Commit.REJECTED ? "CONTAINMENT" : "NO_WRITES"; } - private void placeProceduralObjects(Column column) { - List surface = proceduralPlacements(column.procedural().surface()); - List region = proceduralPlacements(column.procedural().region()); - CaveProfile surfaceProfile = caves.resolve(column.profiles().surface(), column.profiles().region()); - CaveProfile regionProfile = caves.resolve(column.profiles().region(), column.profiles().cave()); - placeProceduralFrom(surface, column.surface().toString(), surfaceProfile, column.surface()); - placeProceduralFrom(region, column.region().toString(), regionProfile, null); - if (!column.cave().equals(column.surface())) { - CaveProfile caveProfile = caves.resolve(column.profiles().cave(), column.profiles().region()); - placeProceduralFrom(proceduralPlacements(column.procedural().cave()), column.cave().toString(), caveProfile, column.cave()); - } - } - - private List proceduralPlacements(ProceduralObjectSettings settings) { - return settings == null ? List.of() : ResolvedProceduralObjects.of(context.world(), settings); - } - - private void placeProceduralFrom(List placements, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome) { - if (placements.isEmpty()) { - return; - } - int blockX = context.originX(); - int blockZ = context.originZ(); - CaveAnchors anchors = newAnchors(); - for (ProceduralPlacement placement : placements) { - boolean chancePassed = passesProceduralChance(rng, placement.chance()); - if (golden) { - log.debug("Goldendebug procedural chance: chunk=" + chunkX + "," + chunkZ + " scope=" + scope + " placement=" + placement.name() + " passed=" + chancePassed); - } - if (!chancePassed) { - continue; - } - placeProcedural(placement, scope, caveProfile, expectedCaveBiome, anchors, blockX, blockZ); - } - } - - private void placeProcedural(ProceduralPlacement placement, String scope, CaveProfile caveProfile, ResourceId expectedCaveBiome, - CaveAnchors anchors, int blockX, int blockZ) { - boolean carving = placement.carvingSupport() == CarvingMode.CARVING_ONLY; - CaveAnchors.Search search = caves.searchFor(placement, caveProfile); - int density = Math.max(1, placement.density()); - for (int i = 0; i < density; i++) { - Optional picked = placement.variant(rng); - if (picked.isEmpty()) { - if (golden) { - log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + i + " variant=null"); - } - continue; - } - PlaceableObject variant = picked.get(); - CaveAnchors.Anchor anchor = carving ? anchors.find(rng, blockX, blockZ, search, expectedCaveBiome, placement.underwater()) : null; - if (carving && anchor == null) { - if (golden) { - log.debug("Goldendebug procedural cave anchor rejected: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() - + " minDepthBelowSurface=" + search.minDepthBelowSurface()); - } - continue; - } - int x = anchor == null ? rng.i(blockX, blockX + CHUNK_WIDTH_BLOCKS) : anchor.x(); - int z = anchor == null ? rng.i(blockZ, blockZ + CHUNK_WIDTH_BLOCKS) : anchor.z(); - int id = rng.i(0, Integer.MAX_VALUE); - if (golden) { - logProceduralPick(placement, variant, i, x, z, carving); - } - try { - placeProceduralVariant(placement, variant, scope, caveProfile, search, anchor, x, z, id); - } catch (Throwable failure) { - log.error("Failed to place procedural object '" + placement.name() + "' in " + scope, failure); - } - } - } - - private void placeProceduralVariant(ProceduralPlacement placement, PlaceableObject variant, String scope, CaveProfile caveProfile, - CaveAnchors.Search search, CaveAnchors.Anchor anchor, int x, int z, int id) { - String goldenTag = golden ? scope + "/" + placement.name() : null; - PlacementTags tags = tags(variant, id, "procedural", placement.tree(), false); - int resultY; - String commit = "n/a"; - if (anchor != null) { - PlacementChanges changes = effective.forCave(placement, variant, caveProfile); - CavePlacement contained = chunk.placeInCave(variant, x, anchor.y(), z, placement, changes, search.minDepthBelowSurface(), tags, goldenTag); - resultY = contained.resultY(); - commit = contained.commit().toString(); - } else { - resultY = chunk.placeOnSurface(variant, x, z, placement, PlacementChanges.NONE, tags, goldenTag); - } - if (golden) { - log.debug("Goldendebug procedural result: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() - + " variant=" + variant.name() + " xx=" + x + " zz=" + z + " resultY=" + resultY + " commit=" + commit); - } - } - - private void logProceduralPick(ProceduralPlacement placement, PlaceableObject variant, int index, int x, int z, boolean carving) { - List pool = placement.variants(); - log.debug("Goldendebug procedural pick: chunk=" + chunkX + "," + chunkZ + " placement=" + placement.name() + " densityIndex=" + index - + " variant=" + variant.name() + " variantIndex=" + pool.indexOf(variant) + "/" + pool.size() + " xx=" + x + " zz=" + z - + " mode=" + placement.mode() + " carving=" + carving); - } - - static boolean passesProceduralChance(RNG rng, double chance) { - if (chance <= 0.0) { - return false; - } - if (chance >= 1.0) { - return true; - } - return rng.chance(Math.max(0.0, Math.min(1.0, chance + rng.d(-CHANCE_JITTER, CHANCE_JITTER)))); - } - private void placeUpperObjects(Column column) { SettingsStack upper = terrain.upperDimension() .map(dimension -> dimension.settings().at(ObjectSettings.class, centerX, centerZ)) @@ -593,11 +472,8 @@ final class ChunkObjectPlacing { } } - private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, PlacementSource placement) { - return tags(object, id, context, treePlacement, placement.isDolphinTarget() && placement.underwater()); - } - - private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, boolean buriedTreasure) { + private PlacementTags tags(PlaceableObject object, int id, String context, boolean treePlacement, ObjectPlacement placement) { + boolean buriedTreasure = placement.isDolphinTarget() && placement.underwater(); return new PlacementTags(placementMarker(object, id, context), treePlacement, buriedTreasure); } @@ -612,8 +488,12 @@ final class ChunkObjectPlacing { return PlacementRecord.of(this.context.world().resources().idOf(key), id); } + /** Objects in {@code trees/} are trees, procedural ones in {@code procedural/trees/} too, and so is anything a placement grows from saplings. */ private static boolean isTreePlacement(PlaceableObject object, ObjectPlacement placement) { String key = object == null ? null : object.name(); + if (key != null && ProceduralObjectCatalog.isProceduralKey(key)) { + key = key.substring(ProceduralObjectCatalog.KEY_PREFIX.length()); + } return (key != null && key.startsWith(TREE_FOLDER)) || (placement != null && !placement.trees().isEmpty()); } @@ -674,15 +554,12 @@ final class ChunkObjectPlacing { } private record Column(ResourceId region, ResourceId surface, ResourceId cave, int surfaceY, ColumnObjects objects, - ColumnProcedural procedural, ColumnProfiles profiles) { + ColumnProfiles profiles) { } private record ColumnObjects(ObjectSettings surface, ObjectSettings cave, ObjectSettings region) { } - private record ColumnProcedural(ProceduralObjectSettings surface, ProceduralObjectSettings cave, ProceduralObjectSettings region) { - } - private record ColumnProfiles(CaveProfile surface, CaveProfile cave, CaveProfile region) { } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java index e3b62a18d..a192f25cd 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/EffectivePlacements.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.modules.carve.CaveProfile; -import art.arcane.iris.builtin.objects.PlacementSource; +import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.modules.objects.PlacementChanges; import com.volmit.object.PlaceableObject; @@ -41,12 +41,12 @@ final class EffectivePlacements { } /** The changes to make to {@code placement} to place {@code object} on the surface. */ - PlacementChanges forSurface(PlacementSource placement, PlaceableObject object) { + PlacementChanges forSurface(ObjectPlacement placement, PlaceableObject object) { return withDimensionSurfaceSupport(placement, withImportedMode(placement, object, PlacementChanges.NONE)); } /** The changes to make to {@code placement} to place {@code object} in a cave with the cave profile {@code caveProfile}. */ - PlacementChanges forCave(PlacementSource placement, PlaceableObject object, CaveProfile caveProfile) { + PlacementChanges forCave(ObjectPlacement placement, PlaceableObject object, CaveProfile caveProfile) { PlacementChanges changes = forSurface(placement, object); ObjectPlaceMode mode = changes.mode() != null ? changes.mode() : placement.mode(); if (mode != ObjectPlaceMode.CENTER_HEIGHT || caveProfile == null) { @@ -62,7 +62,7 @@ final class EffectivePlacements { } /** Imported objects are placed with the fast minimal stilt unless their mode finds its own height. */ - private static PlacementChanges withImportedMode(PlacementSource placement, PlaceableObject object, PlacementChanges changes) { + private static PlacementChanges withImportedMode(ObjectPlacement placement, PlaceableObject object, PlacementChanges changes) { String key = object.name(); if (key == null || key.isBlank() || !isImported(key)) { return changes; @@ -79,7 +79,7 @@ final class EffectivePlacements { } /** The dimension widens the buffer of a placement, never narrows it, and its support requirement applies on top of the placement's own: both have to want it. */ - private PlacementChanges withDimensionSurfaceSupport(PlacementSource placement, PlacementChanges changes) { + private PlacementChanges withDimensionSurfaceSupport(ObjectPlacement placement, PlacementChanges changes) { boolean require = placement.requireSurfaceSupport() && dimensionRequiresSurfaceSupport; int buffer = Math.max(placement.surfaceSupportBuffer(), dimensionSurfaceSupportBuffer); if (require == placement.requireSurfaceSupport() && buffer == placement.surfaceSupportBuffer()) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 81bc3aacc..0d7964d2e 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -24,6 +24,7 @@ import art.arcane.iris.modules.floating.FloatingChildSettings; import art.arcane.iris.modules.floating.IslandFootprint; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.modules.objects.ObjectPool; import art.arcane.iris.modules.objects.ObjectSize; import com.volmit.object.PlaceableObject; @@ -426,6 +427,7 @@ public final class FloatingObjectPlacing { /** The reach of floating children's objects, each object sized once. */ private static final class Reach { private final PackResources resources; + private final ProceduralObjectCatalog procedural; private final Map biomeObjects; private final ModuleLog log; private final Map> sizes = new HashMap<>(); @@ -433,6 +435,7 @@ public final class FloatingObjectPlacing { private Reach(PackResources resources, Map biomeObjects, ModuleLog log) { this.resources = resources; + this.procedural = ProceduralObjectCatalog.detached(resources, log); this.biomeObjects = biomeObjects; this.log = log; } @@ -479,7 +482,7 @@ public final class FloatingObjectPlacing { private int objectReach(String objectKey, ObjectPlacement placement) { try { - Optional size = sizes.computeIfAbsent(objectKey, key -> PlacementReach.sizeOf(resources, key)); + Optional size = sizes.computeIfAbsent(objectKey, key -> PlacementReach.sizeOf(resources, procedural, key)); if (size.isEmpty()) { return 0; } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java index 2ed257e1a..deac96b27 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java @@ -23,15 +23,14 @@ import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; -import art.arcane.iris.builtin.objects.PlacementSource; import art.arcane.iris.modules.objects.CarvedSpace; import art.arcane.iris.modules.objects.CavePlacement; import art.arcane.iris.modules.objects.CaveTransaction; import art.arcane.iris.modules.objects.EffectiveSettings; import art.arcane.iris.modules.objects.ForwardingTerrain; import art.arcane.iris.modules.objects.PlacementChanges; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.modules.objects.PlacementTags; -import art.arcane.iris.modules.objects.ProceduralPlacement; import art.arcane.iris.modules.objects.TerrainTransaction; import com.volmit.ModuleLog; import com.volmit.block.BlockRegistry; @@ -55,17 +54,15 @@ final class ObjectChunk { private final PackWorld world; private final PlacementTerrain terrain; private final CarvedSpace carved; - private final EffectiveSettings settings; private final BlockRegistry blocks; private final ModuleLog log; private final int worldHeight; - ObjectChunk(MantleStageContext context, EffectiveSettings settings, ModuleLog log) { + ObjectChunk(MantleStageContext context, ModuleLog log) { this.world = context.world(); this.terrain = context.placementTerrain(); this.worldHeight = context.terrain().bounds().maxY(); this.carved = new CarvedSpace(context.extension(MatterMantle.class).orElseThrow(), worldHeight); - this.settings = settings; this.blocks = world.resources().blocks(); this.log = log; } @@ -86,10 +83,10 @@ final class ObjectChunk { * @param goldenTag logs the placement's questions under this tag, or null to leave them * @return the height the object was placed at, negative when the placement rejected it */ - int placeOnSurface(PlaceableObject object, int x, int z, PlacementSource placement, PlacementChanges changes, + int placeOnSurface(PlaceableObject object, int x, int z, ObjectPlacement placement, PlacementChanges changes, PlacementTags tags, String goldenTag) { - PlacementTerrain placer = proceduralTerrain(terrain, placement, goldenTag); - return place(ObjectRun.of(object, settings.of(placement, changes), x, SAMPLED_HEIGHT, z), placer, tags); + PlacementTerrain placer = proceduralTerrain(terrain, object, goldenTag); + return place(ObjectRun.of(object, EffectiveSettings.withChanges(placement, changes), x, SAMPLED_HEIGHT, z), placer, tags); } /** @@ -98,10 +95,10 @@ final class ObjectChunk { * * @param goldenTag logs the placement's questions under this tag, or null to leave them */ - CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, PlacementSource placement, PlacementChanges changes, + CavePlacement placeInCave(PlaceableObject object, int x, int anchorY, int z, ObjectPlacement placement, PlacementChanges changes, int minDepthBelowSurface, PlacementTags tags, String goldenTag) { - ObjectPlacement effective = settings.of(placement, changes); - CaveTransaction transaction = new CaveTransaction(proceduralTerrain(terrain, placement, goldenTag), worldHeight, anchorY, + ObjectPlacement effective = EffectiveSettings.withChanges(placement, changes); + CaveTransaction transaction = new CaveTransaction(proceduralTerrain(terrain, object, goldenTag), worldHeight, anchorY, minDepthBelowSurface); int placeY = anchorY; if (effective.mode().placeMode().has(PlaceTrait.UPSIDE_DOWN)) { @@ -131,15 +128,15 @@ final class ObjectChunk { } /** - * A procedural object's terrain: its leaves decay when it is meant to look real, and the golden-debug switch logs - * its questions. Object placements use the chunk's terrain as it is. + * A procedural variant's terrain: it keeps the leaf states the variant baked, persistent or decaying, and the + * golden-debug switch logs its questions. Pack objects use the chunk's terrain as it is. */ - private PlacementTerrain proceduralTerrain(PlacementTerrain base, PlacementSource placement, String goldenTag) { - if (!(placement instanceof ProceduralPlacement procedural)) { + private PlacementTerrain proceduralTerrain(PlacementTerrain base, PlaceableObject object, String goldenTag) { + if (!ProceduralObjectCatalog.isProceduralKey(object.name())) { return base; } - PlacementTerrain decaying = procedural.plausible() ? new DecayingTerrain(base) : base; - return goldenTag == null ? decaying : new GoldenDebugTerrain(decaying, goldenTag, log); + PlacementTerrain keepingBakedLeaves = new DecayingTerrain(base); + return goldenTag == null ? keepingBakedLeaves : new GoldenDebugTerrain(keepingBakedLeaves, goldenTag, log); } /** Writes the tags beside each of the object's own blocks. */ @@ -157,7 +154,7 @@ final class ObjectChunk { } } - /** A terrain whose leaves decay, for procedural objects meant to look like the real thing. */ + /** A terrain that leaves non-persistent leaves as they are, so they decay like the real thing. */ private static final class DecayingTerrain extends ForwardingTerrain { private DecayingTerrain(PlacementTerrain delegate) { super(delegate); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 9b11db0da..ba70f3bc5 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -21,7 +21,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.modules.objects.ProceduralObjectSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.modules.objects.TreeGrowthSettings; @@ -41,8 +41,9 @@ import com.volmit.world.PackWorld; /** * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work - * done by {@link ObjectPlacing}, one per engine runtime, with the noise of its placements and the variants of its procedural - * objects built ahead of generation ({@link #warmUp}). Its reach is the pack's largest object placement. It tells + * done by {@link ObjectPlacing}, one per engine runtime, with the noise of its placements and the variants of the + * procedural objects they place ({@link ProceduralObjectCatalog}) built ahead of generation ({@link #warmUp}). Its + * reach is the pack's largest object placement. It tells * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the * object search and studio tools, and grows the trees of saplings ({@link TreeGrowing}). */ @@ -63,9 +64,9 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { var registry = setup.registry(); registry.registerService(ObjectsAt.class, new ObjectLocating()); registry.registerService(SaplingGrowth.class, new TreeGrowing()); - registry.registerSettings(ObjectSettings.class, ProceduralObjectSettings.class, TreeGrowthSettings.class, - RequireSurfaceSupportSettings.class, SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, - UpperObjectsForceSettings.class); + registry.registerSettings(ObjectSettings.class, TreeGrowthSettings.class, RequireSurfaceSupportSettings.class, + SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, UpperObjectsForceSettings.class); + registry.registerResourceKind(ProceduralObjectCatalog.DEFINITIONS); registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); registry.registerLifecycle(this); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 7cf5256a9..7a2770d64 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.modules.objects.EffectiveSettings; import art.arcane.iris.modules.objects.ObjectPool; import art.arcane.iris.modules.objects.ObjectSeparation; import art.arcane.volmlib.util.math.RNG; @@ -50,7 +49,6 @@ public final class ObjectPlacing { private final PackWorld world; private final ObjectPool objects; private final ObjectSeparation separation; - private final EffectiveSettings settings = new EffectiveSettings(); private final ModuleLog log; private ObjectPlacing(PackWorld world) { @@ -67,7 +65,7 @@ public final class ObjectPlacing { /** Places what originates in the chunk {@code context} generates. */ void place(MantleStageContext context) { - new ChunkObjectPlacing(objects, settings, log, context).place(); + new ChunkObjectPlacing(objects, log, context).place(); } /** The keys of the objects the chunk would get, as far as the chunk's surface objects go. */ diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index d7b81c6cb..f48ddb42c 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -21,11 +21,8 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.modules.objects.ProceduralObjectSettings; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; import art.arcane.iris.modules.objects.Declaration; import art.arcane.iris.modules.objects.ObjectPool; -import art.arcane.iris.modules.objects.ProceduralPlacement; import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; import com.volmit.world.PackWorld; @@ -55,18 +52,12 @@ final class ObjectWarmUp { void warm() { List> placements = byKey(Declaration.allOf(world, ObjectSettings.class)); - List> procedural = byKey(Declaration.allOf(world, ProceduralObjectSettings.class)); for (Level level : WARMED_LEVELS) { for (Declaration declaration : placements) { if (declaration.level() == level) { warmPlacements(declaration.settings().objects()); } } - for (Declaration declaration : procedural) { - if (declaration.level() == level) { - warmProcedural(declaration.settings()); - } - } } } @@ -81,10 +72,4 @@ final class ObjectWarmUp { } } } - - private void warmProcedural(ProceduralObjectSettings settings) { - for (ProceduralPlacement placement : ResolvedProceduralObjects.of(world, settings)) { - placement.variant(root.nextParallelRNG(warmed++)); - } - } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java index c9789c24b..ec695f57b 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/PlacementReach.java @@ -21,19 +21,17 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.anchor.PlaceMode; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.modules.objects.ProceduralObjectSettings; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.prepare.ObjectTranslate; import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralObjects; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.engine.procedural.ProceduralVariants; import art.arcane.iris.modules.objects.ObjectSize; -import art.arcane.iris.modules.objects.ProceduralPlacement; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; import com.volmit.geometry.BlockBox; -import com.volmit.object.PlaceableObject; import com.volmit.resource.PackResources; import java.util.HashMap; @@ -50,24 +48,23 @@ final class PlacementReach { private static final double SCALE_PADDING_FACTOR = 2D; private final PackResources resources; + private final ProceduralObjectCatalog procedural; private final ModuleLog log; private final Map> sizes = new HashMap<>(); private final Set warnedLargeObjects = new HashSet<>(); PlacementReach(PackResources resources, ModuleLog log) { this.resources = resources; + this.procedural = ProceduralObjectCatalog.detached(resources, log); this.log = log; } - /** The largest reach of any object placement or procedural object the pack's regions and biomes declare. */ + /** The largest reach of any object placement the pack's regions and biomes declare. */ int ofPack(PackSettings settings) { int radius = 0; for (Entry entry : settings.declared(ObjectSettings.class)) { radius = Math.max(radius, ofPlacements(entry.value().objects())); } - for (Entry entry : settings.declared(ProceduralObjectSettings.class)) { - radius = Math.max(radius, ofProcedural(entry.value())); - } return radius; } @@ -86,7 +83,7 @@ final class PlacementReach { private int ofObject(ObjectPlacement placement, String objectKey) { try { - Optional size = sizes.computeIfAbsent(objectKey, key -> sizeOf(resources, key)); + Optional size = sizes.computeIfAbsent(objectKey, key -> sizeOf(resources, procedural, key)); if (size.isEmpty()) { return 0; } @@ -101,8 +98,11 @@ final class PlacementReach { } } - /** The size of the pack object {@code objectKey} names; empty when the pack has none. */ - static Optional sizeOf(PackResources resources, String objectKey) { + /** The size of the object {@code objectKey} names, for a procedural pool its largest variant; empty when the pack has none. */ + static Optional sizeOf(PackResources resources, ProceduralObjectCatalog procedural, String objectKey) { + if (ProceduralObjectCatalog.isProceduralKey(objectKey)) { + return procedural.variants(objectKey).map(ProceduralVariants::largestSize); + } return resources.objects().sizeOf(resources.idOf(objectKey)).map(PlacementReach::sizeOf); } @@ -110,22 +110,6 @@ final class PlacementReach { return new ObjectSize(box.maxX() - box.minX(), box.maxY() - box.minY(), box.maxZ() - box.minZ()); } - private int ofProcedural(ProceduralObjectSettings settings) { - int radius = 0; - for (ProceduralPlacement placement : ResolvedProceduralObjects.resolve(settings, resources)) { - for (PlaceableObject variant : placement.variants()) { - radius = Math.max(radius, of(new ObjectSize(variant.width(), variant.height(), variant.depth()), placement)); - } - } - return radius; - } - - /** The reach of an object of {@code size} placed with the options a procedural object has. */ - static int of(ObjectSize size, ProceduralPlacement placement) { - return of(size, placement.mode().placeMode(), null, placement.rotation(), placement.translate(), null, - placement.vacuumSettings().orElse(null)); - } - static int of(ObjectSize size, ObjectPlacement placement) { return of(size, placement.mode().placeMode(), placement.scale().maxScale(), placement.rotation(), placement.translate(), placement.warp() == null || placement.warp().isFlat() ? 0 : placement.warp().multiplier(), diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 9b737349b..1be4a3ac0 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -21,10 +21,9 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.modules.objects.ProceduralObjectSettings; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.modules.objects.TreeGrowthSettings; import art.arcane.iris.modules.objects.TreeMode; -import art.arcane.iris.modules.objects.tree.Tree; import art.arcane.iris.engine.loot.BlockBiomes; import art.arcane.iris.modules.objects.Declaration; import art.arcane.iris.modules.objects.ObjectPool; @@ -61,6 +60,7 @@ import java.util.stream.Collectors; public final class TreeGrowing implements SaplingGrowth { private static final int SAPLING_WIDTH = 1; private static final int SAPLING_DEPTH = 1; + private static final String PROCEDURAL_TREE_FOLDER = ProceduralObjectCatalog.KEY_PREFIX + "trees/"; @Override public Optional grow(PackWorld world, Sapling sapling, Surroundings surroundings) { @@ -75,7 +75,7 @@ public final class TreeGrowing implements SaplingGrowth { return Optional.empty(); } List keys = placement.get().place(); - Optional tree = ObjectPool.of(world).object(keys.get(RNG.r.i(keys.size()))); + Optional tree = ObjectPool.of(world).object(keys.get(RNG.r.i(keys.size())), RNG.r); if (tree.isEmpty()) { return Optional.empty(); } @@ -90,14 +90,24 @@ public final class TreeGrowing implements SaplingGrowth { @Override public TreeObjects treeObjects(PackWorld world) { Set objects = new HashSet<>(); - Set procedural = new HashSet<>(); for (Declaration declaration : Declaration.allOf(world, ObjectSettings.class)) { collectPlacements(declaration.settings().objects(), objects); } - for (Declaration declaration : Declaration.allOf(world, ProceduralObjectSettings.class)) { - collectProceduralTrees(declaration.settings().trees(), procedural); + return new TreeObjects(idsOf(world, placedNames(world, objects))); + } + + /** The names objects are placed under: a procedural pool's are its variants' own. */ + private static Set placedNames(PackWorld world, Set objectKeys) { + ProceduralObjectCatalog procedural = ProceduralObjectCatalog.of(world); + Set names = new HashSet<>(); + for (String key : objectKeys) { + if (ProceduralObjectCatalog.isProceduralKey(key)) { + procedural.placeable(key).forEach(variant -> names.add(variant.name())); + } else { + names.add(key); + } } - return new TreeObjects(idsOf(world, objects), idsOf(world, procedural)); + return names; } private static Set idsOf(PackWorld world, Set keys) { @@ -134,29 +144,22 @@ public final class TreeGrowing implements SaplingGrowth { return matches; } + /** The objects of tree placements, and procedural objects in {@code procedural/trees/} wherever they are placed. */ private static void collectPlacements(List placements, Set objectKeys) { for (ObjectPlacement placement : placements) { - if (placement == null || placement.trees().isEmpty()) { + if (placement == null) { continue; } for (String objectKey : placement.place()) { - if (objectKey != null && !objectKey.isBlank()) { + if (objectKey != null && !objectKey.isBlank() && (!placement.trees().isEmpty() || isProceduralTree(objectKey))) { objectKeys.add(objectKey); } } } } - private static void collectProceduralTrees(List trees, Set objectKeys) { - for (Tree tree : trees) { - if (tree == null || tree.name() == null || tree.name().isBlank()) { - continue; - } - int variants = Math.max(1, tree.variants()); - for (int index = 0; index < variants; index++) { - objectKeys.add(Tree.variantLoadKey(tree.name(), index)); - } - } + private static boolean isProceduralTree(String objectKey) { + return objectKey.startsWith(PROCEDURAL_TREE_FOLDER); } /** diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java deleted file mode 100644 index 1901c28e5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/IrisProceduralBlocks.java +++ /dev/null @@ -1,134 +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.procedural; - -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.math.Vector3i; -import com.volmit.block.BlockState; -import com.volmit.block.PaletteSpec; -import com.volmit.object.ObjectBlock; -import com.volmit.geometry.BlockPosition; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -/** - * Shared low-level helpers for building procedural objects in memory: resolving a single block id or a noise palette - * into a block state, and assembling a raw block map into a centered object shape anchored so its y=0 layer sits one - * block above the terrain surface (same convention the tree generator uses). - */ -public final class IrisProceduralBlocks { - public static final String[] FACE_PROPERTIES = {"north", "east", "south", "west", "up", "down"}; - - private IrisProceduralBlocks() { - } - - public static int[] faceOffset(String face) { - return switch (face) { - case "north" -> new int[]{0, 0, -1}; - case "south" -> new int[]{0, 0, 1}; - case "east" -> new int[]{1, 0, 0}; - case "west" -> new int[]{-1, 0, 0}; - case "up" -> new int[]{0, 1, 0}; - default -> new int[]{0, -1, 0}; - }; - } - - public static boolean paletteSet(PaletteSpec palette) { - return palette != null && !palette.palette().isEmpty(); - } - - public static boolean paletteSet(Optional palette) { - return palette.filter(IrisProceduralBlocks::paletteSet).isPresent(); - } - - public static BlockState resolve(String block, Optional palette, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { - return resolve(block, palette.orElse(null), blocks, x, y, z, paletteRng); - } - - public static BlockState resolve(Optional block, Optional palette, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { - return resolve(block.orElse(null), palette.orElse(null), blocks, x, y, z, paletteRng); - } - - /** The block of {@code palette} at the position, picked with the seed of {@code paletteRng} as the palette's old class did; else {@code block}. */ - public static BlockState resolve(String block, PaletteSpec palette, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { - if (paletteSet(palette)) { - return blocks.pick(palette, paletteRng.getSeed(), x, y, z); - } - if (block != null && !block.isEmpty()) { - return blocks.block(block); - } - return null; - } - - public static boolean hasProperty(BlockState state, String property) { - return state.properties().containsKey(property); - } - - public static String materialKey(BlockState state) { - return state.material().toString(); - } - - public static String propertyValue(BlockState state, String property) { - return state.properties().get(property); - } - - /** The blocks centered on x and z, with their lowest layer one block above the anchor; null when there are none. */ - public static ProceduralShape assemble(Map blocks) { - if (blocks == null || blocks.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 (Vector3i v : blocks.keySet()) { - minX = Math.min(minX, v.getBlockX()); - minY = Math.min(minY, v.getBlockY()); - minZ = Math.min(minZ, v.getBlockZ()); - maxX = Math.max(maxX, v.getBlockX()); - maxY = Math.max(maxY, v.getBlockY()); - maxZ = Math.max(maxZ, v.getBlockZ()); - } - - int w = maxX - minX + 1; - int h = maxY - minY + 1; - int d = maxZ - minZ + 1; - int cx = w / 2; - int cy = h / 2; - int cz = d / 2; - - List placed = new ArrayList<>(blocks.size()); - for (Map.Entry entry : blocks.entrySet()) { - Vector3i v = entry.getKey(); - int nx = v.getBlockX() - minX - cx; - int ny = v.getBlockY() - cy + 1; - int nz = v.getBlockZ() - minZ - cz; - placed.add(new ObjectBlock(new BlockPosition(nx, ny, nz), entry.getValue())); - } - - return new ProceduralShape(w, h, d, placed); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java deleted file mode 100644 index f71fe1b9a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralObjects.java +++ /dev/null @@ -1,76 +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.procedural; - -import art.arcane.iris.modules.objects.ProceduralObjectSettings; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.iris.engine.object.procedural.coral.ResolvedCoral; -import art.arcane.iris.engine.object.procedural.crystal.ResolvedCrystal; -import art.arcane.iris.engine.object.procedural.formation.ResolvedFormation; -import art.arcane.iris.engine.object.procedural.fungi.ResolvedFungus; -import art.arcane.iris.engine.object.procedural.ruin.ResolvedRuin; -import art.arcane.iris.engine.object.procedural.tree.ResolvedTree; -import art.arcane.iris.modules.objects.ProceduralPlacement; -import com.volmit.resource.PackResources; -import com.volmit.world.PackWorld; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.BiFunction; - -/** The procedural objects a region or biome declares, each made placeable once per world, in the order the settings list them. */ -public final class ResolvedProceduralObjects { - private ResolvedProceduralObjects() { - } - - /** The placements {@code settings} declare in {@code world}, resolved the first time the world asks. */ - public static List of(PackWorld world, ProceduralObjectSettings settings) { - PackResources resources = world.resources(); - return world.state(ResolvedByDeclaration.class, ignored -> new ResolvedByDeclaration()).placements - .computeIfAbsent(settings, declared -> resolve(declared, resources)); - } - - /** The placements {@code settings} declare, resolved anew, for work outside any world such as working out the pack's reach. */ - public static List resolve(ProceduralObjectSettings settings, PackResources resources) { - List all = new ArrayList<>(); - for (Tree tree : settings.trees()) { - all.add(new ResolvedTree(tree, resources)); - } - addAll(all, settings.ruins(), resources, ResolvedRuin::new); - addAll(all, settings.formations(), resources, ResolvedFormation::new); - addAll(all, settings.coral(), resources, ResolvedCoral::new); - addAll(all, settings.fungi(), resources, ResolvedFungus::new); - addAll(all, settings.crystals(), resources, ResolvedCrystal::new); - return List.copyOf(all); - } - - private static void addAll(List all, List settings, PackResources resources, - BiFunction resolve) { - for (S entry : settings) { - all.add(resolve.apply(entry, resources)); - } - } - - /** A world's resolved placements, by the settings that declare them. */ - private static final class ResolvedByDeclaration { - private final Map> placements = new ConcurrentHashMap<>(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java b/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java deleted file mode 100644 index 1cd7fb26d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ResolvedProceduralPlacement.java +++ /dev/null @@ -1,181 +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.procedural; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.modules.objects.ProceduralPlacement; -import art.arcane.volmlib.util.cache.AtomicCache; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.object.PlaceableObject; -import com.volmit.resource.PackResources; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * A procedural object's settings made placeable: bakes a deterministic pool of variants from them, once, through the - * pack's objects ({@link ObjectBuilder}), and hands the placement options to {@code iris:objects}. - */ -public abstract class ResolvedProceduralPlacement implements ProceduralPlacement { - private static final long VARIANT_SEED_STRIDE = 7919L; - - /** The options every procedural placement shares with an object placement. */ - public record Shape(String name, double chance, int density, long seed, int variants, ObjectPlaceMode mode, - ObjectRotation rotation, ObjectLimit clamp, CarvingMode carvingSupport, boolean underwater, - ObjectTranslate translate, StiltSettings stiltSettings, VacuumSettings vacuumSettings) { - } - - private final Shape shape; - private final PackResources resources; - private final AtomicCache> variantCache = new AtomicCache<>(); - - protected ResolvedProceduralPlacement(Shape shape, PackResources resources) { - this.shape = shape; - this.resources = resources; - } - - /** The shape variant {@code index} is baked as, from its own seeded stream; null when it has no blocks. */ - protected abstract ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks); - - /** The number of variants to bake; the settings' count, at least one. */ - protected int variantCount() { - return Math.max(1, shape.variants()); - } - - @Override - public String name() { - return shape.name(); - } - - @Override - public double chance() { - return shape.chance(); - } - - @Override - public int density() { - return shape.density(); - } - - @Override - public boolean plausible() { - return false; - } - - @Override - public boolean tree() { - return false; - } - - @Override - public ObjectPlaceMode mode() { - return shape.mode(); - } - - @Override - public CarvingMode carvingSupport() { - return shape.carvingSupport(); - } - - @Override - public CaveAnchorMode caveAnchorMode() { - return CaveAnchorMode.PROFILE_DEFAULT; - } - - @Override - public boolean underwater() { - return shape.underwater(); - } - - @Override - public ObjectRotation rotation() { - return shape.rotation(); - } - - @Override - public ObjectTranslate translate() { - return shape.translate(); - } - - @Override - public Optional vacuumSettings() { - return Optional.ofNullable(shape.vacuumSettings()); - } - - @Override - public ObjectLimit clamp() { - return shape.clamp(); - } - - @Override - public Optional stiltSettings() { - return Optional.ofNullable(shape.stiltSettings()); - } - - @Override - public List variants() { - return variantCache.aquire(() -> bake(new ObjectBuilder(resources))); - } - - @Override - public Optional variant(RNG rng) { - List baked = variants(); - if (baked == null || baked.isEmpty()) { - return Optional.empty(); - } - return Optional.of(baked.get(rng.i(baked.size()))); - } - - /** Bakes every variant; the default draws variant {@code i} from {@code seed + i * stride}. */ - protected List bake(ObjectBuilder blocks) { - List baked = new ArrayList<>(); - int count = variantCount(); - - for (int i = 0; i < count; i++) { - ProceduralShape generated = generate(i, variantRng(i), blocks); - if (generated == null || generated.blocks().isEmpty()) { - continue; - } - baked.add(build(blocks, "procedural/" + shape.name() + "#" + i, generated)); - } - - return baked; - } - - protected static PlaceableObject build(ObjectBuilder blocks, String loadKey, ProceduralShape generated) { - return blocks.build(loadKey, generated.width(), generated.height(), generated.depth(), generated.blocks()); - } - - protected final RNG variantRng(int index) { - return new RNG(shape.seed() + (index * VARIANT_SEED_STRIDE)); - } - - protected final long seed() { - return shape.seed(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java deleted file mode 100644 index b0ee7a1c5..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralCanvas.java +++ /dev/null @@ -1,64 +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.procedural.coral; - -import java.util.HashMap; -import java.util.Map; - -public final class CoralCanvas { - public enum Role { - STRUCTURE, - TIP - } - - private static final long BIAS = 1L << 20; - private static final long MASK = (1L << 21) - 1L; - - private final Map cells = new HashMap<>(); - - public void set(int x, int y, int z, Role role) { - if (y < 0) { - return; - } - long key = encode(x, y, z); - Role existing = cells.get(key); - if (existing == Role.TIP && role == Role.STRUCTURE) { - return; - } - cells.put(key, role); - } - - public Map getCells() { - return cells; - } - - public static long encode(int x, int y, int z) { - long ex = (x + BIAS) & MASK; - long ey = (y + BIAS) & MASK; - long ez = (z + BIAS) & MASK; - return (ex << 42) | (ey << 21) | ez; - } - - public static int[] decode(long key) { - int ez = (int) ((key & MASK) - BIAS); - int ey = (int) (((key >> 21) & MASK) - BIAS); - int ex = (int) (((key >> 42) & MASK) - BIAS); - return new int[]{ex, ey, ez}; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java deleted file mode 100644 index ea6bce10f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/CoralGenerator.java +++ /dev/null @@ -1,263 +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.procedural.coral; - -import art.arcane.iris.modules.objects.coral.Coral; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.HashMap; -import java.util.Map; - -public final class CoralGenerator { - private static final double GOLDEN_ANGLE = 137.50776405003785; - - private CoralGenerator() { - } - - public static ProceduralShape generate(Coral coral, int variantIndex, RNG rng, ObjectBuilder blocks) { - int lo = Math.min(coral.heightMin(), coral.heightMax()); - int hi = Math.max(coral.heightMin(), coral.heightMax()); - int height = Math.max(2, rng.i(lo, hi + 1)); - long shapeSeed = rng.getSeed() + variantIndex * 31L; - - CoralCanvas canvas = new CoralCanvas(); - switch (coral.form()) { - case BRANCHING -> buildBranching(canvas, coral, height, shapeSeed, rng); - case FAN -> buildFan(canvas, coral, height, shapeSeed); - case BRAIN -> buildBrain(canvas, coral, height, shapeSeed); - case PILLAR -> buildPillar(canvas, coral, height, shapeSeed); - case TENDRIL -> buildTendril(canvas, coral, height, shapeSeed, rng); - } - - Map resolved = resolve(canvas, coral, blocks); - return IrisProceduralBlocks.assemble(resolved); - } - - private static void buildBranching(CoralCanvas canvas, Coral coral, int height, long seed, RNG rng) { - int stalkTop = Math.max(1, (int) Math.round(height * 0.5)); - for (int y = 0; y < stalkTop; y++) { - placeWavy(canvas, coral, 0, y, 0, y, seed, CoralCanvas.Role.STRUCTURE); - } - - int count = Math.max(1, coral.branchCount()); - for (int b = 0; b < count; b++) { - double az = branchAzimuth(coral, b, count, rng); - int startY = stalkTop - 1 + (int) Math.round((b % 2) * 1.0); - double[] tip = rasterizeArm(canvas, coral, 0, startY, 0, az, - coral.branchElevation(), coral.branchLength(), seed + b * 131L); - - placeTipCluster(canvas, coral, (int) Math.round(tip[0]), (int) Math.round(tip[1]), (int) Math.round(tip[2]), - coral.tipClusterRadius(), seed + b * 977L); - - if (coral.subBranches()) { - int subCount = Math.max(1, coral.subBranchCount()); - for (int s = 0; s < subCount; s++) { - double subAz = az + (s - (subCount - 1) / 2.0) * 35.0; - double subLen = coral.branchLength() * coral.subBranchScale(); - double[] subTip = rasterizeArm(canvas, coral, - (int) Math.round(tip[0]), (int) Math.round(tip[1]), (int) Math.round(tip[2]), - subAz, coral.branchElevation() + 10.0, subLen, seed + b * 131L + s * 17L + 5000L); - placeTipCluster(canvas, coral, (int) Math.round(subTip[0]), (int) Math.round(subTip[1]), (int) Math.round(subTip[2]), - Math.max(0, coral.tipClusterRadius() - 1), seed + b * 977L + s * 53L); - } - } - } - } - - private static void buildFan(CoralCanvas canvas, Coral coral, int height, long seed) { - int half = Math.max(1, coral.fanWidth()); - for (int y = 0; y < height; y++) { - double t = y / (double) Math.max(1, height - 1); - double profile = Math.sin(Math.PI * t); - int w = (int) Math.round(half * profile); - for (int dx = -w; dx <= w; dx++) { - canvas.set(dx, y, 0, CoralCanvas.Role.STRUCTURE); - } - } - for (int dx = -half; dx <= half; dx++) { - placeTip(canvas, coral, dx, height - 1, 0, seed + dx); - } - } - - private static void buildBrain(CoralCanvas canvas, Coral coral, int height, long seed) { - int r = Math.max(1, coral.brainRadius()); - int ry = Math.max(1, Math.min(r, (int) Math.round(height * 0.6))); - double rough = coral.brainRoughness(); - for (int dx = -r; dx <= r; dx++) { - for (int dz = -r; dz <= r; dz++) { - for (int dy = 0; dy <= ry * 2; dy++) { - double nx = dx / (double) r; - double ny = (dy - ry) / (double) ry; - double nz = dz / (double) r; - double d = nx * nx + ny * ny + nz * nz; - double wobble = (TreeFunctions.valueNoise3D(dx, dy, dz, seed) - 0.5) * 2.0 * rough; - if (d <= 1.0 + wobble) { - canvas.set(dx, dy, dz, CoralCanvas.Role.STRUCTURE); - } - } - } - } - } - - private static void buildPillar(CoralCanvas canvas, Coral coral, int height, long seed) { - int r = Math.max(1, coral.pillarRadius()); - for (int y = 0; y < height; y++) { - for (int dx = -r; dx <= r; dx++) { - for (int dz = -r; dz <= r; dz++) { - if (dx * dx + dz * dz <= r * r) { - canvas.set(dx, y, dz, CoralCanvas.Role.STRUCTURE); - } - } - } - } - placeTipCluster(canvas, coral, 0, height - 1, 0, coral.tipClusterRadius(), seed); - } - - private static void buildTendril(CoralCanvas canvas, Coral coral, int height, long seed, RNG rng) { - int count = Math.max(1, coral.tendrilCount()); - double radius = Math.max(0.0, coral.spread()); - for (int c = 0; c < count; c++) { - double az = Math.toRadians(c * (360.0 / count)); - double bx = Math.cos(az) * radius * 0.5; - double bz = Math.sin(az) * radius * 0.5; - int tx = (int) Math.round(bx); - int tz = (int) Math.round(bz); - int top = 0; - for (int y = 0; y < height; y++) { - placeWavy(canvas, coral, tx, y, tz, y * (c + 1), seed + c * 311L, CoralCanvas.Role.STRUCTURE); - top = y; - } - placeTip(canvas, coral, tx, top, tz, seed + c * 311L); - } - } - - private static double[] rasterizeArm(CoralCanvas canvas, Coral coral, int ox, int oy, int oz, - double azimuthDeg, double elevationDeg, double length, long seed) { - double azRad = Math.toRadians(azimuthDeg); - double elRad = Math.toRadians(elevationDeg); - double dx = length * Math.cos(elRad) * Math.sin(azRad); - double dy = length * Math.sin(elRad); - double dz = length * Math.cos(elRad) * Math.cos(azRad); - int steps = Math.max(1, (int) Math.round(Math.max(Math.abs(dy), Math.max(Math.abs(dx), Math.abs(dz))))); - - double[] tip = new double[]{ox, oy, oz}; - for (int i = 0; i <= steps; i++) { - double t = i / (double) steps; - double sway = swayOffset(coral, t * length, seed); - int x = (int) Math.round(ox + dx * t + sway); - int y = (int) Math.round(oy + dy * t); - int z = (int) Math.round(oz + dz * t - sway); - canvas.set(x, y, z, CoralCanvas.Role.STRUCTURE); - tip = new double[]{x, y, z}; - } - return tip; - } - - private static void placeWavy(CoralCanvas canvas, Coral coral, int x, int y, int z, double phase, long seed, CoralCanvas.Role role) { - double sway = swayOffset(coral, phase, seed); - int sx = (int) Math.round(sway); - int sz = (int) Math.round(swayOffset(coral, phase + 53.0, seed + 7L)); - canvas.set(x + sx, y, z + sz, role); - } - - private static double swayOffset(Coral coral, double phase, long seed) { - double amount = Math.max(0.0, Math.min(1.0, coral.sway())); - if (amount <= 0.0) { - return 0.0; - } - double n = TreeFunctions.valueNoise1D(phase * 0.35, seed) - 0.5; - return n * 2.0 * amount * (1.0 + coral.spread() * 0.25); - } - - private static void placeTipCluster(CoralCanvas canvas, Coral coral, int cx, int cy, int cz, int radius, long seed) { - if (radius <= 0) { - placeTip(canvas, coral, cx, cy, cz, seed); - return; - } - for (int dx = -radius; dx <= radius; dx++) { - for (int dy = -radius; dy <= radius; dy++) { - for (int dz = -radius; dz <= radius; dz++) { - if (dx * dx + dy * dy + dz * dz <= radius * radius) { - canvas.set(cx + dx, cy + dy, cz + dz, CoralCanvas.Role.STRUCTURE); - } - } - } - } - placeTip(canvas, coral, cx, cy + radius + 1, cz, seed); - } - - private static void placeTip(CoralCanvas canvas, Coral coral, int x, int y, int z, long seed) { - if (!hasTip(coral)) { - return; - } - if (TreeFunctions.valueNoise1D(x * 31.0 + y * 17.0 + z * 13.0, seed) <= coral.tipChance()) { - canvas.set(x, y, z, CoralCanvas.Role.TIP); - } - } - - private static boolean hasTip(Coral coral) { - return IrisProceduralBlocks.paletteSet(coral.tipPalette()) - || (coral.tipBlock() != null && !coral.tipBlock().isEmpty()); - } - - private static double branchAzimuth(Coral coral, int index, int count, RNG rng) { - return switch (coral.branchAzimuth()) { - case GOLDEN_ANGLE -> index * GOLDEN_ANGLE; - case EVEN -> index * (360.0 / count); - case RANDOM -> rng.d(0.0, 360.0); - }; - } - - private static Map resolve(CoralCanvas canvas, Coral coral, ObjectBuilder blocks) { - Map out = new HashMap<>(); - RNG paletteRng = new RNG(coral.seed()); - for (Map.Entry entry : canvas.getCells().entrySet()) { - int[] xyz = CoralCanvas.decode(entry.getKey()); - int x = xyz[0]; - int y = xyz[1]; - int z = xyz[2]; - BlockState state; - if (entry.getValue() == CoralCanvas.Role.TIP) { - state = IrisProceduralBlocks.resolve(coral.tipBlock(), coral.tipPalette(), blocks, x, y, z, paletteRng); - if (state == null) { - state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), blocks, x, y, z, paletteRng); - } - } else { - state = IrisProceduralBlocks.resolve(coral.block(), coral.blockPalette(), blocks, x, y, z, paletteRng); - } - if (state == null) { - continue; - } - if (coral.waterlogged() && IrisProceduralBlocks.hasProperty(state, "waterlogged")) { - try { - state = blocks.withProperty(state, "waterlogged", "true"); - } catch (IllegalArgumentException ignored) { - } - } - out.put(new Vector3i(x, y, z), state); - } - return out; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java b/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java deleted file mode 100644 index c256d20b4..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/coral/ResolvedCoral.java +++ /dev/null @@ -1,43 +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.procedural.coral; - -import art.arcane.iris.modules.objects.coral.Coral; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.resource.PackResources; - -/** A coral reef made placeable: its variants are baked by {@link CoralGenerator}. */ -public final class ResolvedCoral extends ResolvedProceduralPlacement { - private final Coral settings; - - public ResolvedCoral(Coral settings, PackResources resources) { - super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), - settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); - this.settings = settings; - } - - @Override - protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { - return CoralGenerator.generate(settings, index, rng, blocks); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.java deleted file mode 100644 index 93d1ca854..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalBaseBuilder.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.procedural.crystal; - -import art.arcane.iris.modules.objects.crystal.Crystal; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; - -public final class CrystalBaseBuilder { - private CrystalBaseBuilder() { - } - - public static void build(CrystalCanvas canvas, Crystal crystal, long seed) { - double radius = crystal.baseRadius(); - if (radius <= 0.0) { - canvas.set(0, 0, 0, CrystalRole.BASE); - return; - } - - double noiseStrength = crystal.baseNoise(); - int reach = (int) Math.ceil(radius + 1.0); - for (int x = -reach; x <= reach; x++) { - for (int y = -reach; y <= reach; y++) { - for (int z = -reach; z <= reach; z++) { - double distance = Math.sqrt((double) x * x + (double) y * y + (double) z * z); - double wobble = (TreeFunctions.valueNoise3D(x, y, z, seed) - 0.5) * 2.0 * noiseStrength * radius; - if (distance <= radius + wobble) { - canvas.set(x, y, z, CrystalRole.BASE); - } - } - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java deleted file mode 100644 index 072c1029f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalCanvas.java +++ /dev/null @@ -1,52 +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.procedural.crystal; - -import art.arcane.volmlib.util.math.Vector3i; - -import java.util.HashMap; -import java.util.Map; - -public final class CrystalCanvas { - private final Map cells = new HashMap<>(); - - public void set(int x, int y, int z, CrystalRole role) { - Vector3i key = new Vector3i(x, y, z); - CrystalRole existing = cells.get(key); - if (existing == null || rank(role) > rank(existing)) { - cells.put(key, role); - } - } - - public boolean has(int x, int y, int z) { - return cells.containsKey(new Vector3i(x, y, z)); - } - - public Map getCells() { - return cells; - } - - private static int rank(CrystalRole role) { - return switch (role) { - case BASE -> 0; - case SHARD -> 1; - case TIP -> 2; - }; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java deleted file mode 100644 index 341650cb3..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGenerator.java +++ /dev/null @@ -1,112 +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.procedural.crystal; - -import art.arcane.iris.modules.objects.crystal.Crystal; -import com.volmit.block.PaletteSpec; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.HashMap; -import java.util.Map; - -public final class CrystalGenerator { - private CrystalGenerator() { - } - - public static ProceduralShape generate(Crystal crystal, int variantIndex, RNG rng, ObjectBuilder blocks) { - CrystalCanvas canvas = new CrystalCanvas(); - long structureSeed = rng.getSeed(); - - CrystalBaseBuilder.build(canvas, crystal, structureSeed + 977L); - CrystalShardBuilder.build(canvas, crystal, rng); - - Map resolved = new HashMap<>(); - RNG paletteRng = new RNG(crystal.seed()); - RNG tipRng = new RNG(crystal.seed() + (variantIndex * 31337L) + 4099L); - - for (Map.Entry entry : canvas.getCells().entrySet()) { - Vector3i position = entry.getKey(); - int x = position.getBlockX(); - int y = position.getBlockY(); - int z = position.getBlockZ(); - BlockState blockData = resolveRole(crystal, entry.getValue(), blocks, x, y, z, paletteRng, tipRng); - if (blockData == null) { - continue; - } - resolved.put(position, blockData); - } - - return IrisProceduralBlocks.assemble(resolved); - } - - private static BlockState resolveRole(Crystal crystal, CrystalRole role, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng, RNG tipRng) { - return switch (role) { - case BASE -> resolveBase(crystal, blocks, x, y, z, paletteRng); - case SHARD -> resolveShard(crystal, blocks, x, y, z, paletteRng); - case TIP -> resolveTip(crystal, blocks, x, y, z, paletteRng, tipRng); - }; - } - - private static BlockState resolveBase(Crystal crystal, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { - boolean hasBase = IrisProceduralBlocks.paletteSet(crystal.basePalette()) - || (crystal.baseBlock() != null && !crystal.baseBlock().isEmpty()); - if (hasBase) { - BlockState base = IrisProceduralBlocks.resolve(crystal.baseBlock(), crystal.basePalette(), blocks, x, y, z, paletteRng); - if (base != null) { - return base; - } - } - return resolveShard(crystal, blocks, x, y, z, paletteRng); - } - - private static BlockState resolveShard(Crystal crystal, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng) { - return IrisProceduralBlocks.resolve(crystal.block(), crystal.blockPalette(), blocks, x, y, z, paletteRng); - } - - private static BlockState resolveTip(Crystal crystal, ObjectBuilder blocks, int x, int y, int z, RNG paletteRng, RNG tipRng) { - boolean hasTip = IrisProceduralBlocks.paletteSet(crystal.tipPalette()) - || (crystal.tipBlock() != null && !crystal.tipBlock().isEmpty()); - - if (hasTip) { - if (tipRng.chance(crystal.tipChance())) { - BlockState tip = IrisProceduralBlocks.resolve(crystal.tipBlock(), crystal.tipPalette(), blocks, x, y, z, paletteRng); - if (tip != null) { - return tip; - } - } - return resolveShard(crystal, blocks, x, y, z, paletteRng); - } - - if (crystal.glow() && crystal.glowBlock() != null && !crystal.glowBlock().isEmpty()) { - if (tipRng.chance(crystal.tipChance())) { - BlockState glow = IrisProceduralBlocks.resolve(crystal.glowBlock(), (PaletteSpec) null, blocks, x, y, z, paletteRng); - if (glow != null) { - return glow; - } - } - } - - return resolveShard(crystal, blocks, x, y, z, paletteRng); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.java deleted file mode 100644 index 8f21be72b..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalGeometry.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.procedural.crystal; - -import art.arcane.iris.modules.objects.crystal.CrystalSurface; - - -public final class CrystalGeometry { - private CrystalGeometry() { - } - - public static double[] surfaceNormal(CrystalSurface surface) { - return switch (surface) { - case FLOOR -> new double[]{0.0, 1.0, 0.0}; - case CEILING -> new double[]{0.0, -1.0, 0.0}; - case WALL -> { - double len = Math.sqrt(1.0 + 0.5 * 0.5); - yield new double[]{1.0 / len, 0.5 / len, 0.0}; - } - }; - } - - public static double[] orthonormalBasisU(double[] normal) { - double[] reference = Math.abs(normal[1]) > 0.99 ? new double[]{1.0, 0.0, 0.0} : new double[]{0.0, 1.0, 0.0}; - double[] u = cross(reference, normal); - normalize(u); - return u; - } - - public static double[] orthonormalBasisV(double[] normal, double[] u) { - double[] v = cross(normal, u); - normalize(v); - return v; - } - - public static double[] coneDirection(double[] normal, double[] u, double[] v, double coneAngleRadians, double azimuthRadians) { - double sin = Math.sin(coneAngleRadians); - double cos = Math.cos(coneAngleRadians); - double ca = Math.cos(azimuthRadians); - double sa = Math.sin(azimuthRadians); - double[] dir = new double[3]; - for (int i = 0; i < 3; i++) { - dir[i] = cos * normal[i] + sin * (ca * u[i] + sa * v[i]); - } - normalize(dir); - return dir; - } - - public static double[] cross(double[] a, double[] b) { - return new double[]{ - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0] - }; - } - - public static void normalize(double[] vec) { - double len = Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); - if (len < 1e-9) { - vec[0] = 0.0; - vec[1] = 1.0; - vec[2] = 0.0; - return; - } - vec[0] /= len; - vec[1] /= len; - vec[2] /= len; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java deleted file mode 100644 index 08055b8c1..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalShardBuilder.java +++ /dev/null @@ -1,125 +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.procedural.crystal; - -import art.arcane.iris.modules.objects.crystal.CrystalDistribution; -import art.arcane.iris.modules.objects.crystal.Crystal; -import art.arcane.volmlib.util.math.RNG; - -public final class CrystalShardBuilder { - private static final double GOLDEN_ANGLE = 137.50776405003785; - - private CrystalShardBuilder() { - } - - public static void build(CrystalCanvas canvas, Crystal crystal, RNG rng) { - double[] normal = CrystalGeometry.surfaceNormal(crystal.growthSurface()); - double[] u = CrystalGeometry.orthonormalBasisU(normal); - double[] v = CrystalGeometry.orthonormalBasisV(normal, u); - - int countLo = Math.min(crystal.shardCountMin(), crystal.shardCountMax()); - int countHi = Math.max(crystal.shardCountMin(), crystal.shardCountMax()); - int shardCount = Math.max(1, rng.i(countLo, countHi + 1)); - - int lengthLo = Math.min(crystal.shardLengthMin(), crystal.shardLengthMax()); - int lengthHi = Math.max(crystal.shardLengthMin(), crystal.shardLengthMax()); - - double spreadRadians = Math.toRadians(Math.max(0.0, Math.min(90.0, crystal.spreadAngle()))); - double jitterAmount = Math.max(0.0, Math.min(1.0, crystal.jitter())); - double emitRadius = Math.max(0.0, crystal.baseRadius() * 0.6); - - for (int i = 0; i < shardCount; i++) { - double azimuth = azimuth(crystal.distribution(), i, rng); - azimuth += rng.d(-Math.PI, Math.PI) * jitterAmount * 0.5; - - double cone = spreadRadians * fanFraction(shardCount, i, rng); - cone += rng.d(-spreadRadians, spreadRadians) * jitterAmount * 0.5; - cone = Math.max(0.0, Math.min(Math.PI / 2.0, cone)); - - double[] direction = CrystalGeometry.coneDirection(normal, u, v, cone, azimuth); - - double ox = normal[0] * emitRadius + u[0] * Math.cos(azimuth) * emitRadius + v[0] * Math.sin(azimuth) * emitRadius; - double oy = normal[1] * emitRadius + u[1] * Math.cos(azimuth) * emitRadius + v[1] * Math.sin(azimuth) * emitRadius; - double oz = normal[2] * emitRadius + u[2] * Math.cos(azimuth) * emitRadius + v[2] * Math.sin(azimuth) * emitRadius; - - int length = Math.max(1, rng.i(lengthLo, lengthHi + 1)); - rasterizeShard(canvas, crystal, ox, oy, oz, direction, length); - } - } - - private static void rasterizeShard(CrystalCanvas canvas, Crystal crystal, double ox, double oy, double oz, double[] direction, int length) { - double baseRadius = Math.max(0.5, crystal.shardBaseRadius()); - double taper = Math.max(0.0, Math.min(1.0, crystal.shardTaper())); - - int samples = Math.max(1, length * 3); - - for (int s = 0; s <= samples; s++) { - double t = s / (double) samples; - double cx = ox + direction[0] * length * t; - double cy = oy + direction[1] * length * t; - double cz = oz + direction[2] * length * t; - - double radius = baseRadius * (1.0 - taper * t); - if (t >= 1.0) { - radius = 0.0; - } - radius = Math.max(0.0, radius); - - int reach = (int) Math.floor(radius); - int centerX = (int) Math.round(cx); - int centerY = (int) Math.round(cy); - int centerZ = (int) Math.round(cz); - - if (reach <= 0) { - canvas.set(centerX, centerY, centerZ, CrystalRole.SHARD); - } else { - for (int dx = -reach; dx <= reach; dx++) { - for (int dy = -reach; dy <= reach; dy++) { - for (int dz = -reach; dz <= reach; dz++) { - double dist = Math.sqrt((double) dx * dx + (double) dy * dy + (double) dz * dz); - if (dist <= radius) { - canvas.set(centerX + dx, centerY + dy, centerZ + dz, CrystalRole.SHARD); - } - } - } - } - } - } - - int tipX = (int) Math.round(ox + direction[0] * length); - int tipY = (int) Math.round(oy + direction[1] * length); - int tipZ = (int) Math.round(oz + direction[2] * length); - canvas.set(tipX, tipY, tipZ, CrystalRole.TIP); - } - - private static double azimuth(CrystalDistribution distribution, int index, RNG rng) { - if (distribution == CrystalDistribution.GOLDEN_ANGLE) { - return Math.toRadians(index * GOLDEN_ANGLE); - } - return rng.d(0.0, Math.PI * 2.0); - } - - private static double fanFraction(int count, int index, RNG rng) { - if (count <= 1) { - return rng.d(0.0, 1.0); - } - double base = index / (double) (count - 1); - return Math.max(0.0, Math.min(1.0, base * 0.7 + rng.d(0.0, 0.3))); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java b/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java deleted file mode 100644 index 03f036794..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/ResolvedCrystal.java +++ /dev/null @@ -1,43 +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.procedural.crystal; - -import art.arcane.iris.modules.objects.crystal.Crystal; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.resource.PackResources; - -/** A crystal cluster made placeable: its variants are baked by {@link CrystalGenerator}. */ -public final class ResolvedCrystal extends ResolvedProceduralPlacement { - private final Crystal settings; - - public ResolvedCrystal(Crystal settings, PackResources resources) { - super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), - settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); - this.settings = settings; - } - - @Override - protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { - return CrystalGenerator.generate(settings, index, rng, blocks); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.java deleted file mode 100644 index a1111167d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationBlockResolver.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.procedural.formation; - -import com.volmit.block.PaletteSpec; -import java.util.Optional; -import art.arcane.iris.modules.objects.formation.Formation; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -public final class FormationBlockResolver { - private FormationBlockResolver() { - } - - public static BlockState resolve(Formation f, ObjectBuilder blocks, FormationCanvas.Role role, Vector3i raw) { - int x = raw.getBlockX(); - int y = raw.getBlockY(); - int z = raw.getBlockZ(); - RNG paletteRng = new RNG(f.seed()); - - if (role == FormationCanvas.Role.CAP && capDefined(f)) { - BlockState cap = IrisProceduralBlocks.resolve(f.capBlock(), f.capPalette(), blocks, x, y, z, paletteRng); - if (cap != null) { - return cap; - } - } - - if (strataDefined(f)) { - PaletteSpec strata = f.strataPalette().orElseThrow(); - int thickness = Math.max(1, f.strataThickness()); - int band = Math.floorDiv(y, thickness); - BlockState strataState = blocks.pick(strata, f.seed() + (band * 31L), x, band, z); - if (strataState != null) { - return strataState; - } - } - - return IrisProceduralBlocks.resolve(f.block(), f.blockPalette(), blocks, x, y, z, paletteRng); - } - - private static boolean capDefined(Formation f) { - return IrisProceduralBlocks.paletteSet(f.capPalette()) || f.capBlock().filter(block -> !block.isEmpty()).isPresent(); - } - - private static boolean strataDefined(Formation f) { - return IrisProceduralBlocks.paletteSet(f.strataPalette()); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java deleted file mode 100644 index bc38eee3a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationCanvas.java +++ /dev/null @@ -1,61 +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.procedural.formation; - -import art.arcane.volmlib.util.math.Vector3i; - -import java.util.HashMap; -import java.util.Map; - -public final class FormationCanvas { - public enum Role { - BODY, - CAP - } - - private final Map cells = new HashMap<>(); - - public void setBody(int x, int y, int z) { - Vector3i key = new Vector3i(x, y, z); - if (cells.get(key) == Role.CAP) { - return; - } - cells.put(key, Role.BODY); - } - - public void setCap(int x, int y, int z) { - cells.put(new Vector3i(x, y, z), Role.CAP); - } - - public void remove(int x, int y, int z) { - cells.remove(new Vector3i(x, y, z)); - } - - public boolean has(int x, int y, int z) { - return cells.containsKey(new Vector3i(x, y, z)); - } - - public Map getCells() { - return cells; - } - - public boolean isEmpty() { - return cells.isEmpty(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java deleted file mode 100644 index e20f622b9..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationGenerator.java +++ /dev/null @@ -1,75 +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.procedural.formation; - -import art.arcane.iris.modules.objects.formation.Formation; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.HashMap; -import java.util.Map; - -public final class FormationGenerator { - private FormationGenerator() { - } - - public static ProceduralShape generate(Formation f, int variantIndex, RNG rng, ObjectBuilder blocks) { - int lo = Math.min(f.heightMin(), f.heightMax()); - int hi = Math.max(f.heightMin(), f.heightMax()); - int height = Math.max(3, rng.i(lo, hi + 1)); - - int wLo = Math.min(f.baseWidthMin(), f.baseWidthMax()); - int wHi = Math.max(f.baseWidthMin(), f.baseWidthMax()); - double baseRadius = Math.max(1, rng.i(wLo, wHi + 1)); - - FormationCanvas canvas = new FormationCanvas(); - - switch (f.form()) { - case SPIRE -> FormationShapeBuilder.spire(canvas, f, height, baseRadius, rng); - case HOODOO -> FormationShapeBuilder.hoodoo(canvas, f, height, baseRadius, rng); - case ARCH -> FormationShapeBuilder.arch(canvas, f, height, baseRadius, rng); - case SEA_STACK -> FormationShapeBuilder.seaStack(canvas, f, height, baseRadius, rng); - case BOULDER -> FormationShapeBuilder.boulder(canvas, f, height, baseRadius, rng); - case BASALT_COLUMN -> FormationShapeBuilder.basaltColumns(canvas, f, height, baseRadius, rng); - case ICEBERG -> FormationShapeBuilder.iceberg(canvas, f, height, baseRadius, rng); - case FISSURE -> FormationShapeBuilder.fissure(canvas, f, height, baseRadius, rng); - case SPIRAL -> FormationShapeBuilder.spiral(canvas, f, height, baseRadius, rng); - case OVERHANG -> FormationShapeBuilder.overhang(canvas, f, height, baseRadius, rng); - } - - if (canvas.isEmpty()) { - return null; - } - - Map resolved = new HashMap<>(); - for (Map.Entry entry : canvas.getCells().entrySet()) { - BlockState bd = FormationBlockResolver.resolve(f, blocks, entry.getValue(), entry.getKey()); - if (bd == null) { - continue; - } - resolved.put(entry.getKey(), bd); - } - - return IrisProceduralBlocks.assemble(resolved); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java deleted file mode 100644 index 9bd54a7c0..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationProfiles.java +++ /dev/null @@ -1,58 +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.procedural.formation; - -import art.arcane.iris.modules.objects.formation.Formation; - - -public final class FormationProfiles { - private FormationProfiles() { - } - - public static double radiusAt(Formation f, double baseRadius, double topRadius, double t) { - double clamped = Math.max(0.0, Math.min(1.0, t)); - return switch (f.profile()) { - case CONSTANT -> baseRadius; - case LINEAR -> baseRadius + (topRadius - baseRadius) * clamped; - case TAPER -> baseRadius + (topRadius - baseRadius) * smoothstep(clamped); - case PARABOLIC -> parabolic(f, baseRadius, topRadius, clamped); - case BULGE -> baseRadius + (Math.max(baseRadius, topRadius) - baseRadius) * bell(clamped) + (topRadius - baseRadius) * clamped * 0.25; - }; - } - - private static double parabolic(Formation f, double baseRadius, double topRadius, double t) { - double waist = Math.max(0.0, Math.min(1.0, f.profileWaist())); - double floor = Math.max(0.0, Math.min(1.0, f.profileWaistFloor())); - double denom = Math.pow(Math.max(waist, 1.0 - waist), 2); - if (denom == 0) { - denom = 1; - } - double envelope = baseRadius + (topRadius - baseRadius) * t; - double pinch = floor + (1.0 - floor) * (Math.pow(t - waist, 2) / denom); - return Math.max(0.5, envelope * pinch); - } - - private static double smoothstep(double t) { - return 3.0 * t * t - 2.0 * t * t * t; - } - - private static double bell(double t) { - return Math.exp(-Math.pow(t - 0.5, 2) / (2.0 * 0.22 * 0.22)); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java deleted file mode 100644 index 109db16d0..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/FormationShapeBuilder.java +++ /dev/null @@ -1,429 +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.procedural.formation; - -import art.arcane.iris.modules.objects.formation.Formation; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.HashMap; -import java.util.Map; - -public final class FormationShapeBuilder { - private FormationShapeBuilder() { - } - - public static void spire(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - double topRadius = f.topWidth(); - column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, true); - double lean = Math.toRadians(f.lean()); - double azimuth = Math.toRadians(f.leanAzimuth()); - int previousX = 0; - int previousZ = 0; - for (int y = 0; y < height; y++) { - double shear = Math.tan(lean) * y; - int centerX = (int) Math.round(Math.cos(azimuth) * shear); - int centerZ = (int) Math.round(Math.sin(azimuth) * shear); - boolean cap = y >= height - 2; - for (int x = Math.min(previousX, centerX); x <= Math.max(previousX, centerX); x++) { - setSpireCenter(canvas, x, y, previousZ, cap); - } - for (int z = Math.min(previousZ, centerZ); z <= Math.max(previousZ, centerZ); z++) { - setSpireCenter(canvas, centerX, y, z, cap); - } - previousX = centerX; - previousZ = centerZ; - } - } - - public static void seaStack(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - double topRadius = Math.max(1.0, baseRadius * 0.55); - if (f.topWidth() > 0) { - topRadius = f.topWidth(); - } - column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, true); - } - - public static void hoodoo(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - double topRadius = f.topWidth() > 0 ? f.topWidth() : Math.max(1.0, baseRadius * 0.7); - column(canvas, f, height, baseRadius, topRadius, 0, 0, rng, false); - - int capRadius = f.hoodooCapRadius(); - if (capRadius <= 0) { - return; - } - int capHeight = Math.max(1, f.hoodooCapHeight()); - double lean = Math.toRadians(f.lean()); - double azimuth = Math.toRadians(f.leanAzimuth()); - double shear = Math.tan(lean) * height; - double topOffX = Math.cos(azimuth) * shear; - double topOffZ = Math.sin(azimuth) * shear; - double wideRadius = topRadius + capRadius; - - for (int cy = 0; cy < capHeight; cy++) { - int y = height + cy; - double shrink = capHeight <= 1 ? 0 : (cy / (double) (capHeight - 1)) * 0.5; - double r = wideRadius * (1.0 - shrink); - disc(canvas, f, (int) Math.round(topOffX), y, (int) Math.round(topOffZ), r, true, rng); - } - } - - public static void boulder(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - double rx = baseRadius; - double ry = Math.max(2.0, height * 0.5); - double rz = baseRadius * (0.8 + rng.d(0.0, 0.3)); - double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); - long noiseSeed = f.seed() + 4201L; - - int maxR = (int) Math.ceil(Math.max(rx, Math.max(ry, rz))) + 2; - for (int x = -maxR; x <= maxR; x++) { - for (int y = 0; y <= (int) Math.ceil(ry * 2) + 1; y++) { - for (int z = -maxR; z <= maxR; z++) { - double nx = x / rx; - double ny = (y - ry) / ry; - double nz = z / rz; - double d = nx * nx + ny * ny + nz * nz; - double wobble = (TreeFunctions.valueNoise3D(x, y, z, noiseSeed) - 0.5) * roughness * 0.9; - if (d + wobble <= 1.0) { - canvas.setBody(x, y, z); - } - } - } - } - } - - public static void arch(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - double span = Math.max(2.0, f.archSpan()); - double tubeRadius = Math.max(0.75, f.archThickness() * 0.5); - double asymmetry = Math.max(0.0, Math.min(1.0, f.archAsymmetry())); - double leftFootX = -span * 0.5 - tubeRadius - rng.d(0.0, span * 0.16) * asymmetry; - double rightFootX = span * 0.5 + tubeRadius + rng.d(0.0, span * 0.16) * asymmetry; - double leftFootZ = rng.d(-tubeRadius * 0.45, tubeRadius * 0.45) * asymmetry; - double rightFootZ = rng.d(-tubeRadius * 0.45, tubeRadius * 0.45) * asymmetry; - double crownZ = rng.d(-span * 0.2, span * 0.2) * asymmetry; - double crownShiftX = rng.d(-span * 0.12, span * 0.12) * asymmetry; - double depthTwist = rng.d(-span * 0.1, span * 0.1) * asymmetry; - double crownPosition = 0.5 + rng.d(-0.12, 0.12) * asymmetry; - double leftSteepness = 0.58 + rng.d(-0.16, 0.16) * asymmetry; - double rightSteepness = 0.58 + rng.d(-0.16, 0.16) * asymmetry; - double radiusWave = rng.d(-0.22, 0.22) * asymmetry; - double radiusPhase = rng.d(0.0, Math.PI * 2.0); - double crownCenterY = Math.max(tubeRadius + 2.0, height - 1.0 - tubeRadius); - double footRadius = tubeRadius + Math.min(tubeRadius * 0.45, baseRadius * 0.18); - long noiseSeed = rng.nextLong(); - int steps = Math.max(24, (int) Math.ceil((rightFootX - leftFootX + height) * 4.0)); - - ball(canvas, f, (int) Math.round(leftFootX), (int) Math.round(footRadius), - (int) Math.round(leftFootZ), footRadius, false, noiseSeed, rng); - ball(canvas, f, (int) Math.round(rightFootX), (int) Math.round(footRadius), - (int) Math.round(rightFootZ), footRadius, false, noiseSeed, rng); - - for (int step = 0; step <= steps; step++) { - double t = step / (double) steps; - double normalizedRise; - double steepness; - if (t <= crownPosition) { - normalizedRise = Math.sin((t / crownPosition) * Math.PI * 0.5); - steepness = leftSteepness; - } else { - normalizedRise = Math.sin(((1.0 - t) / (1.0 - crownPosition)) * Math.PI * 0.5); - steepness = rightSteepness; - } - double rise = Math.pow(Math.max(0.0, normalizedRise), steepness); - double x = leftFootX + (rightFootX - leftFootX) * t - + Math.sin(Math.PI * t) * crownShiftX; - double inverse = 1.0 - t; - double z = inverse * inverse * leftFootZ + 2.0 * inverse * t * crownZ + t * t * rightFootZ - + Math.sin(Math.PI * 2.0 * t) * depthTwist; - double y = tubeRadius + (crownCenterY - tubeRadius) * rise; - double radius = tubeRadius * (1.0 + radiusWave * Math.sin(Math.PI * t) - * Math.sin(Math.PI * 2.0 * t + radiusPhase)); - radius = Math.max(tubeRadius * 0.68, Math.min(tubeRadius * 1.32, radius)); - ball(canvas, f, (int) Math.round(x), (int) Math.round(y), (int) Math.round(z), - radius, false, noiseSeed, rng); - } - if (asymmetry == 0.0) { - mirrorAcrossX(canvas); - } - } - - public static void basaltColumns(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - int count = Math.max(2, f.basaltColumns()); - int colRadius = Math.max(1, f.basaltColumnRadius()); - double variance = Math.max(0.0, Math.min(1.0, f.basaltHeightVariance())); - int spread = (int) Math.ceil(baseRadius); - - for (int c = 0; c < count; c++) { - double angle = rng.d(0.0, Math.PI * 2.0); - double dist = rng.d(0.0, spread); - int ox = (int) Math.round(Math.cos(angle) * dist); - int oz = (int) Math.round(Math.sin(angle) * dist); - double hVar = 1.0 - variance + rng.d(0.0, variance * 2.0); - int colHeight = Math.max(3, (int) Math.round(height * hVar)); - - for (int y = 0; y < colHeight; y++) { - for (int x = -colRadius; x <= colRadius; x++) { - for (int z = -colRadius; z <= colRadius; z++) { - if (Math.abs(x) + Math.abs(z) > colRadius) { - continue; - } - canvas.setBody(ox + x, y, oz + z); - } - } - } - if (colRadius > 0) { - canvas.setCap(ox, colHeight - 1, oz); - } - } - } - - public static void iceberg(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - long noiseSeed = rng.nextLong(); - double bodyHeight = Math.max(2.0, height * 0.42); - double radiusX = baseRadius * rng.d(1.15, 1.5); - double radiusZ = baseRadius * rng.d(1.0, 1.35); - ellipsoid(canvas, radiusX, bodyHeight, radiusZ, bodyHeight * 0.36, noiseSeed, f.roughness()); - - int peaks = Math.max(1, f.icebergPeaks()); - double phase = rng.d(0.0, Math.PI * 2.0); - for (int i = 0; i < peaks; i++) { - double angle = phase + (Math.PI * 2.0 * i / peaks) + rng.d(-0.35, 0.35); - double distance = rng.d(0.0, baseRadius * 0.62); - int offsetX = (int) Math.round(Math.cos(angle) * distance); - int offsetZ = (int) Math.round(Math.sin(angle) * distance); - int peakHeight = Math.max(3, (int) Math.round(height * rng.d(0.58, 1.0))); - double peakRadius = Math.max(1.0, baseRadius * rng.d(0.28, 0.58)); - double leanDistance = rng.d(0.0, Math.max(1.0, baseRadius * 0.45)); - taperedPeak(canvas, f, peakHeight, peakRadius, offsetX, offsetZ, angle, leanDistance, rng); - } - } - - public static void fissure(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - int count = Math.max(2, f.fractureCount()); - double separation = Math.max(1.0, f.fractureSeparation()); - double shardRadius = Math.max(1.0, baseRadius / Math.max(1.6, count * 0.72)); - double phase = rng.d(0.0, Math.PI * 2.0); - - for (int i = 0; i < count; i++) { - double lane = i - ((count - 1) / 2.0); - double offset = lane * (shardRadius * 2.0 + separation); - int offsetX = (int) Math.round(Math.cos(phase) * offset); - int offsetZ = (int) Math.round(Math.sin(phase) * offset); - double outwardAngle = lane < 0 ? phase + Math.PI : phase; - int shardHeight = Math.max(3, (int) Math.round(height * rng.d(0.62, 1.0))); - double leanDistance = rng.d(separation * 0.4, separation + baseRadius * 0.8); - taperedPeak(canvas, f, shardHeight, shardRadius, offsetX, offsetZ, outwardAngle, leanDistance, rng); - } - } - - public static void spiral(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - int steps = Math.max(12, height * 4); - double turns = Math.max(0.25, f.spiralTurns()); - double startRadius = Math.max(1.0, f.spiralRadius()); - double startThickness = Math.max(1.0, f.spiralThickness()); - double phase = rng.d(0.0, Math.PI * 2.0); - long noiseSeed = rng.nextLong(); - - for (int step = 0; step <= steps; step++) { - double t = step / (double) steps; - double angle = phase + Math.PI * 2.0 * turns * t; - double radius = startRadius * (1.0 - 0.72 * t); - int x = (int) Math.round(Math.cos(angle) * radius); - int y = (int) Math.round(t * (height - 1)); - int z = (int) Math.round(Math.sin(angle) * radius); - double thickness = Math.max(0.75, startThickness * (1.0 - 0.48 * t)); - ball(canvas, f, x, y, z, thickness, step == steps, noiseSeed, rng); - } - - double footRadius = Math.max(1.0, Math.min(baseRadius, startThickness + 1.0)); - disc(canvas, f, (int) Math.round(Math.cos(phase) * startRadius), 0, - (int) Math.round(Math.sin(phase) * startRadius), footRadius, false, rng); - } - - public static void overhang(FormationCanvas canvas, Formation f, int height, double baseRadius, RNG rng) { - int steps = Math.max(12, height * 4); - double reach = Math.max(1.0, f.overhangReach()); - double drop = Math.max(0.0, f.overhangDrop()); - double phase = Math.toRadians(f.leanAzimuth()) + rng.d(-0.18, 0.18); - double trunkHeight = Math.max(3.0, height * 0.62); - long noiseSeed = rng.nextLong(); - - for (int step = 0; step <= steps; step++) { - double t = step / (double) steps; - double extension; - double y; - if (t <= 0.58) { - double rise = t / 0.58; - extension = reach * 0.16 * rise * rise; - y = trunkHeight * rise; - } else { - double hook = (t - 0.58) / 0.42; - extension = reach * (0.16 + 0.84 * Math.sin(hook * Math.PI * 0.5)); - y = trunkHeight + Math.sin(hook * Math.PI) * height * 0.18 - drop * hook * hook; - } - int x = (int) Math.round(Math.cos(phase) * extension); - int z = (int) Math.round(Math.sin(phase) * extension); - double thickness = Math.max(0.9, baseRadius * (1.0 - 0.64 * t)); - ball(canvas, f, x, Math.max(0, (int) Math.round(y)), z, thickness, step == steps, noiseSeed, rng); - } - } - - private static void column(FormationCanvas canvas, Formation f, int height, double baseRadius, double topRadius, int extraBaseX, int extraBaseZ, RNG rng, boolean capTop) { - double lean = Math.toRadians(f.lean()); - double azimuth = Math.toRadians(f.leanAzimuth()); - double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); - double jitter = Math.max(0.0, Math.min(1.0, f.jitter())); - long noiseSeed = f.seed() + 9001L; - - for (int y = 0; y < height; y++) { - double t = height <= 1 ? 1.0 : (y / (double) (height - 1)); - double radius = FormationProfiles.radiusAt(f, baseRadius, topRadius, t); - double shear = Math.tan(lean) * y; - int cx = extraBaseX + (int) Math.round(Math.cos(azimuth) * shear); - int cz = extraBaseZ + (int) Math.round(Math.sin(azimuth) * shear); - boolean cap = capTop && y >= height - 2; - ringDisc(canvas, f, cx, y, cz, radius, roughness, jitter, noiseSeed, cap, rng); - } - } - - private static void setSpireCenter(FormationCanvas canvas, int x, int y, int z, boolean cap) { - if (cap) { - canvas.setCap(x, y, z); - } else { - canvas.setBody(x, y, z); - } - } - - private static void ringDisc(FormationCanvas canvas, Formation f, int cx, int y, int cz, double radius, double roughness, double jitter, long noiseSeed, boolean cap, RNG rng) { - int r = (int) Math.ceil(radius) + 1; - for (int x = -r; x <= r; x++) { - for (int z = -r; z <= r; z++) { - double dist = Math.sqrt(x * x + z * z); - double perturb = (TreeFunctions.valueNoise3D(cx + x, y, cz + z, noiseSeed) - 0.5) * roughness * (radius + 1.0); - double effective = radius + perturb; - if (dist <= effective) { - if (jitter > 0 && dist > effective - 1.0 && rng.chance(jitter * 0.5)) { - continue; - } - if (cap) { - canvas.setCap(cx + x, y, cz + z); - } else { - canvas.setBody(cx + x, y, cz + z); - } - } - } - } - } - - private static void disc(FormationCanvas canvas, Formation f, int cx, int y, int cz, double radius, boolean cap, RNG rng) { - int r = (int) Math.ceil(radius) + 1; - for (int x = -r; x <= r; x++) { - for (int z = -r; z <= r; z++) { - if (Math.sqrt(x * x + z * z) <= radius) { - if (cap) { - canvas.setCap(cx + x, y, cz + z); - } else { - canvas.setBody(cx + x, y, cz + z); - } - } - } - } - } - - private static void taperedPeak(FormationCanvas canvas, Formation f, int height, double radius, - int offsetX, int offsetZ, double leanAngle, double leanDistance, RNG rng) { - long noiseSeed = rng.nextLong(); - double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); - double jitter = Math.max(0.0, Math.min(1.0, f.jitter())); - for (int y = 0; y < height; y++) { - double t = height <= 1 ? 1.0 : y / (double) (height - 1); - int x = offsetX + (int) Math.round(Math.cos(leanAngle) * leanDistance * t * t); - int z = offsetZ + (int) Math.round(Math.sin(leanAngle) * leanDistance * t * t); - double layerRadius = Math.max(0.45, radius * Math.pow(1.0 - t, 0.72)); - ringDisc(canvas, f, x, y, z, layerRadius, roughness, jitter, noiseSeed, y >= height - 2, rng); - } - } - - private static void ellipsoid(FormationCanvas canvas, double radiusX, double radiusY, double radiusZ, - double centerY, long noiseSeed, double configuredRoughness) { - double roughness = Math.max(0.0, Math.min(1.0, configuredRoughness)); - int maxX = (int) Math.ceil(radiusX) + 1; - int maxY = (int) Math.ceil(radiusY) + 1; - int maxZ = (int) Math.ceil(radiusZ) + 1; - for (int x = -maxX; x <= maxX; x++) { - for (int y = 0; y <= maxY; y++) { - for (int z = -maxZ; z <= maxZ; z++) { - double nx = x / radiusX; - double ny = (y - centerY) / radiusY; - double nz = z / radiusZ; - double distance = nx * nx + ny * ny + nz * nz; - double wobble = (TreeFunctions.valueNoise3D(x, y, z, noiseSeed) - 0.5) * roughness * 0.55; - if (distance + wobble <= 1.0) { - canvas.setBody(x, y, z); - } - } - } - } - } - - private static void ball(FormationCanvas canvas, Formation f, int centerX, int centerY, int centerZ, - double radius, boolean cap, long noiseSeed, RNG rng) { - int extent = (int) Math.ceil(radius); - double roughness = Math.max(0.0, Math.min(1.0, f.roughness())); - double jitter = Math.max(0.0, Math.min(1.0, f.jitter())); - for (int x = -extent; x <= extent; x++) { - for (int y = -extent; y <= extent; y++) { - for (int z = -extent; z <= extent; z++) { - double distance = Math.sqrt(x * x + y * y + z * z); - double perturb = (TreeFunctions.valueNoise3D(centerX + x, centerY + y, centerZ + z, noiseSeed) - 0.5) - * roughness * Math.max(1.0, radius * 0.6); - double effectiveRadius = radius + perturb; - if (distance > effectiveRadius + 0.2) { - continue; - } - if (jitter > 0.0 && distance > effectiveRadius - 0.75 && rng.chance(jitter * 0.35)) { - continue; - } - int targetY = centerY + y; - if (targetY < 0) { - continue; - } - if (cap) { - canvas.setCap(centerX + x, targetY, centerZ + z); - } else { - canvas.setBody(centerX + x, targetY, centerZ + z); - } - } - } - } - } - - private static void mirrorAcrossX(FormationCanvas canvas) { - Map cells = new HashMap<>(canvas.getCells()); - for (Map.Entry entry : cells.entrySet()) { - Vector3i position = entry.getKey(); - if (entry.getValue() == FormationCanvas.Role.CAP) { - canvas.setCap(-position.getBlockX(), position.getBlockY(), position.getBlockZ()); - } else { - canvas.setBody(-position.getBlockX(), position.getBlockY(), position.getBlockZ()); - } - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java b/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java deleted file mode 100644 index 54a7a44e3..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/formation/ResolvedFormation.java +++ /dev/null @@ -1,48 +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.procedural.formation; - -import art.arcane.iris.modules.objects.formation.Formation; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.resource.PackResources; - -/** A rock formation made placeable: its variants are baked by {@link FormationGenerator}. */ -public final class ResolvedFormation extends ResolvedProceduralPlacement { - private final Formation settings; - - public ResolvedFormation(Formation settings, PackResources resources) { - super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), - settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); - this.settings = settings; - } - - @Override - public int surfaceSupportBuffer() { - return settings.surfaceSupportBuffer(); - } - - @Override - protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { - return FormationGenerator.generate(settings, index, rng, blocks); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java deleted file mode 100644 index 418a26c3a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCapBuilder.java +++ /dev/null @@ -1,119 +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.procedural.fungi; - -import com.volmit.block.PaletteSpec; -import java.util.Optional; -import art.arcane.iris.modules.objects.fungi.FungusCapShape; -import art.arcane.iris.modules.objects.fungi.Fungus; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.volmlib.util.math.Vector3i; - -import java.util.Map; - -public final class FungusCapBuilder { - private FungusCapBuilder() { - } - - public static void build(Map roles, Fungus fungus, int baseRadius, double cx, int baseY, double cz, long seed) { - int radius = (int) Math.round(baseRadius + Math.max(0.0, fungus.capOverhang())); - int thickness = Math.max(1, Math.min(3, fungus.capThickness())); - double squish = Math.max(0.0, Math.min(1.0, fungus.capSquish())); - double droop = Math.max(0.0, fungus.capDroop()); - FungusCapShape shape = fungus.capShape() == null ? FungusCapShape.DOME : fungus.capShape(); - int icx = (int) Math.round(cx); - int icz = (int) Math.round(cz); - - boolean hasGill = blockOrPaletteSet(fungus.gillBlock(), fungus.gillPalette()); - boolean hasSpot = blockOrPaletteSet(fungus.spotBlock(), fungus.spotPalette()); - - double apexRise = apexRise(shape, radius) * (1.0 - 0.6 * squish); - double droopReach = Math.tan(Math.toRadians(droop)) * radius; - - for (int dx = -radius; dx <= radius; dx++) { - for (int dz = -radius; dz <= radius; dz++) { - double dist = Math.sqrt(dx * dx + dz * dz); - if (dist > radius + 0.5) { - continue; - } - double normalized = dist / Math.max(1.0, radius); - double surfaceTop = baseY + capSurface(shape, normalized, apexRise); - surfaceTop -= droopReach * Math.pow(normalized, 3); - - int topYi = (int) Math.round(surfaceTop); - for (int layer = 0; layer < thickness; layer++) { - int y = topYi - layer; - if (y < baseY - thickness) { - continue; - } - Vector3i pos = new Vector3i(icx + dx, y, icz + dz); - FungusCellRole role = FungusCellRole.CAP; - - boolean underside = layer == thickness - 1; - boolean topFace = layer == 0; - - if (underside && hasGill && rollNoise(icx + dx, y, icz + dz, seed + 4111L) <= fungus.gillChance()) { - role = FungusCellRole.GILL; - } else if (topFace && hasSpot && spotNoise(icx + dx, y, icz + dz, seed + 9311L) <= fungus.spotChance()) { - role = FungusCellRole.SPOT; - } - - roles.putIfAbsent(pos, role); - } - } - } - } - - private static double apexRise(FungusCapShape shape, int radius) { - return switch (shape) { - case DOME -> radius * 0.85; - case CONICAL -> radius * 1.4; - case FUNNEL -> radius * 0.5; - case FLAT -> radius * 0.35; - case FLAT_WIDE -> radius * 0.2; - }; - } - - private static double capSurface(FungusCapShape shape, double normalized, double apexRise) { - double n = Math.max(0.0, Math.min(1.0, normalized)); - return switch (shape) { - case DOME -> apexRise * Math.sqrt(Math.max(0.0, 1.0 - n * n)); - case CONICAL -> apexRise * (1.0 - n); - case FUNNEL -> apexRise * (n * n); - case FLAT -> apexRise * Math.max(0.0, 1.0 - Math.pow(n, 4)); - case FLAT_WIDE -> apexRise * Math.max(0.0, 1.0 - Math.pow(n, 6)); - }; - } - - private static double rollNoise(int x, int y, int z, long seed) { - return TreeFunctions.valueNoise3D(x, y, z, seed); - } - - private static double spotNoise(int x, int y, int z, long seed) { - return TreeFunctions.valueNoise3D(Math.floorDiv(x, 2), y, Math.floorDiv(z, 2), seed); - } - - static boolean blockOrPaletteSet(Optional block, Optional palette) { - if (IrisProceduralBlocks.paletteSet(palette)) { - return true; - } - return block.filter(name -> !name.isEmpty()).isPresent(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java deleted file mode 100644 index 43beea35e..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusGenerator.java +++ /dev/null @@ -1,104 +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.procedural.fungi; - -import art.arcane.iris.modules.objects.fungi.Fungus; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.HashMap; -import java.util.Map; - -public final class FungusGenerator { - private FungusGenerator() { - } - - public static ProceduralShape generate(Fungus fungus, int height, RNG rng, ObjectBuilder blocks) { - Map roles = new HashMap<>(); - long baseSeed = rng.getSeed(); - - if (fungus.shelf()) { - FungusShelfBuilder.build(roles, fungus, rng, baseSeed); - } else { - buildUpright(roles, fungus, height, rng, baseSeed); - } - - if (roles.isEmpty()) { - return null; - } - - RNG paletteRng = new RNG(fungus.seed()); - Map resolved = new HashMap<>(); - for (Map.Entry entry : roles.entrySet()) { - Vector3i pos = entry.getKey(); - BlockState bd = resolveRole(fungus, entry.getValue(), blocks, pos, paletteRng); - if (bd == null) { - continue; - } - resolved.put(pos, bd); - } - - return IrisProceduralBlocks.assemble(resolved); - } - - private static void buildUpright(Map roles, Fungus fungus, int height, RNG rng, long baseSeed) { - int stemHeight = Math.max(1, height); - Map stemCells = new HashMap<>(); - double[] top = FungusStemBuilder.build(stemCells, fungus, stemHeight, baseSeed); - for (Vector3i v : stemCells.keySet()) { - roles.put(v, FungusCellRole.STEM); - } - - int radius = pickRadius(fungus, rng); - double cx = top[0]; - double cz = top[2]; - int capBaseY = (int) Math.round(top[1]); - FungusCapBuilder.build(roles, fungus, radius, cx, capBaseY, cz, baseSeed + 5557L); - } - - private static int pickRadius(Fungus fungus, RNG rng) { - int lo = Math.min(fungus.capRadiusMin(), fungus.capRadiusMax()); - int hi = Math.max(fungus.capRadiusMin(), fungus.capRadiusMax()); - lo = Math.max(1, lo); - hi = Math.max(lo, hi); - return rng.i(lo, hi + 1); - } - - private static BlockState resolveRole(Fungus fungus, FungusCellRole role, ObjectBuilder blocks, Vector3i pos, RNG paletteRng) { - int x = pos.getBlockX(); - int y = pos.getBlockY(); - int z = pos.getBlockZ(); - return switch (role) { - case STEM -> IrisProceduralBlocks.resolve(fungus.stem(), fungus.stemPalette(), blocks, x, y, z, paletteRng); - case CAP -> IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), blocks, x, y, z, paletteRng); - case GILL -> { - BlockState gill = IrisProceduralBlocks.resolve(fungus.gillBlock(), fungus.gillPalette(), blocks, x, y, z, paletteRng); - yield gill != null ? gill : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), blocks, x, y, z, paletteRng); - } - case SPOT -> { - BlockState spot = IrisProceduralBlocks.resolve(fungus.spotBlock(), fungus.spotPalette(), blocks, x, y, z, paletteRng); - yield spot != null ? spot : IrisProceduralBlocks.resolve(fungus.cap(), fungus.capPalette(), blocks, x, y, z, paletteRng); - } - }; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java deleted file mode 100644 index 6708e7edc..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusShelfBuilder.java +++ /dev/null @@ -1,81 +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.procedural.fungi; - -import art.arcane.iris.modules.objects.fungi.Fungus; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.Map; - -public final class FungusShelfBuilder { - private FungusShelfBuilder() { - } - - public static void build(Map roles, Fungus fungus, RNG rng, long seed) { - int radius = Math.max(1, fungus.shelfRadius()); - double azimuth = rng.d(0.0, Math.PI * 2.0); - double fanX = Math.sin(azimuth); - double fanZ = Math.cos(azimuth); - int stubHeight = Math.max(0, Math.min(2, fungus.stemWidth())); - - for (int y = 0; y < stubHeight; y++) { - roles.put(new Vector3i(0, y, 0), FungusCellRole.STEM); - } - - int fanY = stubHeight; - boolean hasGill = FungusCapBuilder.blockOrPaletteSet(fungus.gillBlock(), fungus.gillPalette()); - boolean hasSpot = FungusCapBuilder.blockOrPaletteSet(fungus.spotBlock(), fungus.spotPalette()); - - for (int dx = -radius; dx <= radius; dx++) { - for (int dz = -radius; dz <= radius; dz++) { - double dist = Math.sqrt(dx * dx + dz * dz); - if (dist > radius + 0.5) { - continue; - } - double forward = dx * fanX + dz * fanZ; - if (forward < -0.5) { - continue; - } - double normalized = dist / Math.max(1.0, radius); - int lift = (int) Math.round(radius * 0.25 * (1.0 - normalized)); - int y = fanY + lift; - - FungusCellRole role = FungusCellRole.CAP; - if (hasSpot && spotNoise(dx, y, dz, seed + 9311L) <= fungus.spotChance()) { - role = FungusCellRole.SPOT; - } - roles.putIfAbsent(new Vector3i(dx, y, dz), role); - - if (hasGill && rollNoise(dx, y - 1, dz, seed + 4111L) <= fungus.gillChance()) { - roles.putIfAbsent(new Vector3i(dx, y - 1, dz), FungusCellRole.GILL); - } - } - } - } - - private static double rollNoise(int x, int y, int z, long seed) { - return TreeFunctions.valueNoise3D(x, y, z, seed); - } - - private static double spotNoise(int x, int y, int z, long seed) { - return TreeFunctions.valueNoise3D(Math.floorDiv(x, 2), y, Math.floorDiv(z, 2), seed); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java deleted file mode 100644 index aba9fe361..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusStemBuilder.java +++ /dev/null @@ -1,95 +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.procedural.fungi; - -import art.arcane.iris.modules.objects.fungi.Fungus; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; - -import java.util.Map; - -public final class FungusStemBuilder { - private FungusStemBuilder() { - } - - public static double[] build(Map stemCells, Fungus fungus, int stemHeight, long seed) { - int width = Math.max(1, Math.min(3, fungus.stemWidth())); - double maxLean = stemHeight * Math.tan(Math.toRadians(Math.max(0.0, fungus.stemCurve()))); - double leanRad = Math.toRadians(fungus.stemLeanAzimuth()); - double leanX = Math.sin(leanRad); - double leanZ = Math.cos(leanRad); - double waveAmp = Math.max(0.0, fungus.stemWaveAmplitude()); - double wavePeriods = fungus.stemWavePeriods() == 0 ? 1.0 : fungus.stemWavePeriods(); - double waveAzimuth = Math.toRadians(fungus.stemLeanAzimuth() + 90.0); - double waveX = Math.sin(waveAzimuth); - double waveZ = Math.cos(waveAzimuth); - - double topCx = 0.0; - double topCz = 0.0; - int topY = Math.max(0, stemHeight - 1); - - for (int y = 0; y < stemHeight; y++) { - double t = stemHeight <= 1 ? 0.0 : y / (double) (stemHeight - 1); - double lean = maxLean * (t * t); - double wave = waveAmp * Math.sin(2.0 * Math.PI * wavePeriods * t + TreeFunctions.valueNoise1D(seed, seed) * Math.PI * 2.0); - double cx = lean * leanX + wave * waveX; - double cz = lean * leanZ + wave * waveZ; - - for (int[] xz : squarePositions(cx, cz, width)) { - stemCells.put(new Vector3i(xz[0], y, xz[1]), null); - } - - topCx = cx; - topCz = cz; - } - - return new double[]{topCx, topY, topCz}; - } - - static int[][] squarePositions(double cx, double cz, int width) { - if (width % 2 == 1) { - int half = width / 2; - int icx = (int) Math.round(cx); - int icz = (int) Math.round(cz); - int[][] out = new int[width * width][2]; - int idx = 0; - for (int dx = -half; dx <= half; dx++) { - for (int dz = -half; dz <= half; dz++) { - out[idx][0] = icx + dx; - out[idx][1] = icz + dz; - idx++; - } - } - return out; - } - int ox = (int) Math.floor(cx) - width / 2 + 1; - int oz = (int) Math.floor(cz) - width / 2 + 1; - int[][] out = new int[width * width][2]; - int idx = 0; - for (int dx = 0; dx < width; dx++) { - for (int dz = 0; dz < width; dz++) { - out[idx][0] = ox + dx; - out[idx][1] = oz + dz; - idx++; - } - } - return out; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java b/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java deleted file mode 100644 index a59cf7130..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/ResolvedFungus.java +++ /dev/null @@ -1,76 +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.procedural.fungi; - -import art.arcane.iris.modules.objects.fungi.Fungus; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.object.PlaceableObject; -import com.volmit.resource.PackResources; - -import java.util.ArrayList; -import java.util.List; - -/** A fungus made placeable: its variants are baked by {@link FungusGenerator}. */ -public final class ResolvedFungus extends ResolvedProceduralPlacement { - private final Fungus settings; - - public ResolvedFungus(Fungus settings, PackResources resources) { - super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), - settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); - this.settings = settings; - } - - @Override - protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { - throw new UnsupportedOperationException("A fungus bakes its variants itself, from the stem heights"); - } - - @Override - protected List bake(ObjectBuilder blocks) { - List baked = new ArrayList<>(); - int count = variantCount(); - int lo = Math.min(settings.stemHeightMin(), settings.stemHeightMax()); - int hi = Math.max(settings.stemHeightMin(), settings.stemHeightMax()); - RNG heightRng = new RNG(seed()); - - for (int i = 0; i < count; i++) { - int height; - if (count == 1 || lo == hi) { - height = heightRng.i(lo, hi + 1); - } else { - double step = (hi - lo) / (double) (count - 1); - double base = lo + step * i; - double jitter = heightRng.d(-step * 0.3, step * 0.3); - height = (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); - } - - ProceduralShape generated = FungusGenerator.generate(settings, Math.max(1, height), variantRng(i), blocks); - if (generated == null || generated.blocks().isEmpty()) { - continue; - } - baked.add(build(blocks, "procedural/" + name() + "#" + i, generated)); - } - - return baked; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java deleted file mode 100644 index f5fcab16a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/ResolvedRuin.java +++ /dev/null @@ -1,43 +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.procedural.ruin; - -import art.arcane.iris.modules.objects.ruin.Ruin; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.resource.PackResources; - -/** A ruin made placeable: its variants are baked by {@link RuinGenerator}. */ -public final class ResolvedRuin extends ResolvedProceduralPlacement { - private final Ruin settings; - - public ResolvedRuin(Ruin settings, PackResources resources) { - super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), - settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); - this.settings = settings; - } - - @Override - protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { - return RuinGenerator.generate(settings, index, rng, blocks); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java deleted file mode 100644 index a45cc8ccd..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinBlockCanvas.java +++ /dev/null @@ -1,107 +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.procedural.ruin; - -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; - -import java.util.HashMap; -import java.util.Map; - -final class RuinBlockCanvas { - enum Role { - STRUCTURE, - ACCENT - } - - static final class Cell { - private Role role; - private boolean structural; - private BlockState accentData; - - Cell(Role role, boolean structural) { - this.role = role; - this.structural = structural; - } - - Role role() { - return role; - } - - boolean structural() { - return structural; - } - - BlockState accentData() { - return accentData; - } - - void promote(Role next, boolean structuralNext) { - this.role = next; - this.structural = this.structural || structuralNext; - } - - void makeAccent(BlockState data) { - this.role = Role.ACCENT; - this.structural = false; - this.accentData = data; - } - } - - private final Map cells = new HashMap<>(); - - Map cells() { - return cells; - } - - void set(int x, int y, int z, Role role, boolean structural) { - Vector3i key = new Vector3i(x, y, z); - Cell existing = cells.get(key); - if (existing == null) { - cells.put(key, new Cell(role, structural)); - } else { - existing.promote(role, structural); - } - } - - void accent(int x, int y, int z, BlockState data) { - if (data == null) { - return; - } - cells.put(new Vector3i(x, y, z), accentCell(data)); - } - - private static Cell accentCell(BlockState data) { - Cell cell = new Cell(Role.ACCENT, false); - cell.makeAccent(data); - return cell; - } - - boolean has(int x, int y, int z) { - return cells.containsKey(new Vector3i(x, y, z)); - } - - Cell get(int x, int y, int z) { - return cells.get(new Vector3i(x, y, z)); - } - - void remove(int x, int y, int z) { - cells.remove(new Vector3i(x, y, z)); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java deleted file mode 100644 index 8136ffc49..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinDecoratorApplier.java +++ /dev/null @@ -1,122 +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.procedural.ruin; - -import art.arcane.iris.modules.objects.ruin.RuinDecorator; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -final class RuinDecoratorApplier { - private static final int[][] HORIZONTAL = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}}; - - private RuinDecoratorApplier() { - } - - static void apply(RuinBlockCanvas canvas, RuinDecorator decorator, ObjectBuilder blocks, long seed, RNG rng) { - List candidates = switch (decorator.target()) { - case TOP -> topCandidates(canvas); - case SURFACE -> surfaceCandidates(canvas); - case BASE_SCATTER -> baseScatterCandidates(canvas, Math.max(1, decorator.scatterRadius())); - }; - - RNG paletteRng = new RNG(seed); - for (Vector3i v : candidates) { - if (!rng.chance(decorator.chance())) { - continue; - } - BlockState bd = IrisProceduralBlocks.resolve(decorator.block(), decorator.palette(), blocks, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); - if (bd != null) { - canvas.accent(v.getBlockX(), v.getBlockY(), v.getBlockZ(), bd); - } - } - } - - private static List topCandidates(RuinBlockCanvas canvas) { - Map highest = new HashMap<>(); - for (Vector3i v : canvas.cells().keySet()) { - long key = columnKey(v.getBlockX(), v.getBlockZ()); - Integer current = highest.get(key); - if (current == null || v.getBlockY() > current) { - highest.put(key, v.getBlockY()); - } - } - List out = new ArrayList<>(); - for (Map.Entry entry : highest.entrySet()) { - int x = (int) (entry.getKey() >> 32); - int z = (int) (entry.getKey() & 0xFFFFFFFFL); - int y = entry.getValue() + 1; - if (!canvas.has(x, y, z)) { - out.add(new Vector3i(x, y, z)); - } - } - return out; - } - - private static List surfaceCandidates(RuinBlockCanvas canvas) { - List out = new ArrayList<>(); - for (Vector3i v : new ArrayList<>(canvas.cells().keySet())) { - for (int[] dir : HORIZONTAL) { - int nx = v.getBlockX() + dir[0]; - int ny = v.getBlockY(); - int nz = v.getBlockZ() + dir[2]; - if (!canvas.has(nx, ny, nz)) { - out.add(new Vector3i(nx, ny, nz)); - } - } - } - return out; - } - - private static List baseScatterCandidates(RuinBlockCanvas canvas, int radius) { - int minX = Integer.MAX_VALUE; - int minZ = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE; - int maxZ = Integer.MIN_VALUE; - int minY = Integer.MAX_VALUE; - for (Vector3i v : canvas.cells().keySet()) { - minX = Math.min(minX, v.getBlockX()); - minZ = Math.min(minZ, v.getBlockZ()); - maxX = Math.max(maxX, v.getBlockX()); - maxZ = Math.max(maxZ, v.getBlockZ()); - minY = Math.min(minY, v.getBlockY()); - } - - List out = new ArrayList<>(); - for (int x = minX - radius; x <= maxX + radius; x++) { - for (int z = minZ - radius; z <= maxZ + radius; z++) { - if (!canvas.has(x, minY, z) && !canvas.has(x, minY + 1, z)) { - out.add(new Vector3i(x, minY, z)); - } - } - } - return out; - } - - private static long columnKey(int x, int z) { - return ((long) x << 32) | (z & 0xFFFFFFFFL); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java deleted file mode 100644 index ff0058a79..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinGenerator.java +++ /dev/null @@ -1,200 +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.procedural.ruin; - -import art.arcane.iris.modules.objects.ruin.RuinDecorator; -import art.arcane.iris.modules.objects.ruin.Ruin; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import com.volmit.block.BlockState; -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public final class RuinGenerator { - private RuinGenerator() { - } - - public static ProceduralShape generate(Ruin ruin, int variantIndex, RNG rng, ObjectBuilder blocks) { - int count = Math.max(1, ruin.variants()); - int height = pick(ruin.heightMin(), ruin.heightMax(), variantIndex, count, rng); - int width = pick(ruin.widthMin(), ruin.widthMax(), variantIndex, count, rng); - int length = pick(ruin.lengthMin(), ruin.lengthMax(), variantIndex, count, rng); - - RuinBlockCanvas canvas = new RuinBlockCanvas(); - switch (ruin.form()) { - case PILLAR -> RuinShapes.pillar(canvas, Math.max(1, width), Math.max(2, height), rng); - case WALL -> RuinShapes.wall(canvas, Math.max(1, width), Math.max(2, length), Math.max(2, height), rng); - case ARCH -> RuinShapes.arch(canvas, Math.max(1, width), Math.max(3, length), Math.max(3, height), rng); - case FLOOR_SLAB -> RuinShapes.floorSlab(canvas, Math.max(3, width), Math.max(3, length), Math.max(1, Math.min(height, 2))); - case RUBBLE -> RuinShapes.rubble(canvas, Math.max(3, width), Math.max(3, length), Math.max(1, Math.min(height, 4)), rng); - } - - applyBurial(ruin, canvas, height); - applyErosion(ruin, canvas); - applyAccents(ruin, canvas, rng, blocks); - - return resolve(ruin, canvas, blocks); - } - - private static int pick(int lo, int hi, int variantIndex, int count, RNG rng) { - int min = Math.min(lo, hi); - int max = Math.max(lo, hi); - if (min == max || count <= 1) { - return rng.i(min, max + 1); - } - double step = (max - min) / (double) (count - 1); - double base = min + step * variantIndex; - double jitter = rng.d(-step * 0.3, step * 0.3); - return (int) Math.round(Math.max(min, Math.min(max, base + jitter))); - } - - private static void applyBurial(Ruin ruin, RuinBlockCanvas canvas, int height) { - double fraction = clamp01(ruin.buriedFraction()); - if (fraction <= 0.0) { - return; - } - int sink = (int) Math.round(height * fraction); - if (sink <= 0) { - return; - } - Map moved = new HashMap<>(); - for (Map.Entry entry : canvas.cells().entrySet()) { - Vector3i v = entry.getKey(); - moved.put(new Vector3i(v.getBlockX(), v.getBlockY() - sink, v.getBlockZ()), entry.getValue()); - } - canvas.cells().clear(); - canvas.cells().putAll(moved); - } - - private static void applyErosion(Ruin ruin, RuinBlockCanvas canvas) { - double erosion = clamp01(ruin.erosion()); - if (erosion <= 0.0) { - return; - } - double scale = Math.max(0.0001, ruin.erosionScale()); - long erosionSeed = ruin.seed() * 0x2545F4914F6CDD1DL + 17L; - int minY = Integer.MAX_VALUE; - for (Vector3i v : canvas.cells().keySet()) { - minY = Math.min(minY, v.getBlockY()); - } - - List doomed = new ArrayList<>(); - for (Map.Entry entry : canvas.cells().entrySet()) { - Vector3i v = entry.getKey(); - RuinBlockCanvas.Cell cell = entry.getValue(); - if (cell.structural() || v.getBlockY() <= minY) { - continue; - } - int sx = (int) Math.round(v.getBlockX() * scale); - int sy = (int) Math.round(v.getBlockY() * scale); - int sz = (int) Math.round(v.getBlockZ() * scale); - double n = TreeFunctions.valueNoise3D(sx, sy, sz, erosionSeed); - if (n < erosion) { - doomed.add(v); - } - } - for (Vector3i v : doomed) { - canvas.cells().remove(v); - } - } - - private static void applyAccents(Ruin ruin, RuinBlockCanvas canvas, RNG rng, ObjectBuilder blocks) { - if (ruin.accents() == null || ruin.accents().isEmpty()) { - return; - } - int decoratorIndex = 0; - for (art.arcane.iris.modules.objects.ruin.RuinDecorator decorator : ruin.accents()) { - RuinDecoratorApplier.apply(canvas, decorator, blocks, ruin.seed() + decoratorIndex * 911L, rng.nextParallelRNG(decoratorIndex + 1)); - decoratorIndex++; - } - } - - private static ProceduralShape resolve(Ruin ruin, RuinBlockCanvas canvas, ObjectBuilder blocks) { - if (canvas.cells().isEmpty()) { - return null; - } - double scale = Math.max(0.0001, ruin.weatheringScale()); - double mossiness = clamp01(ruin.mossiness()); - long weatherSeed = ruin.seed() * 0x9E3779B97F4A7C15L + 101L; - RNG paletteRng = new RNG(ruin.seed()); - - int minY = Integer.MAX_VALUE; - int maxY = Integer.MIN_VALUE; - for (Vector3i v : canvas.cells().keySet()) { - minY = Math.min(minY, v.getBlockY()); - maxY = Math.max(maxY, v.getBlockY()); - } - int span = Math.max(1, maxY - minY); - - Map resolved = new HashMap<>(); - for (Map.Entry entry : canvas.cells().entrySet()) { - Vector3i v = entry.getKey(); - RuinBlockCanvas.Cell cell = entry.getValue(); - BlockState bd; - if (cell.role() == RuinBlockCanvas.Role.ACCENT) { - bd = cell.accentData(); - } else { - bd = structuralBlock(ruin, cell, v, blocks, paletteRng, scale, mossiness, weatherSeed, minY, span); - } - if (bd != null) { - resolved.put(v, bd); - } - } - - return IrisProceduralBlocks.assemble(resolved); - } - - private static BlockState structuralBlock(Ruin ruin, RuinBlockCanvas.Cell cell, Vector3i v, ObjectBuilder blocks, RNG paletteRng, double scale, double mossiness, long weatherSeed, int minY, int span) { - boolean weathered = false; - if (mossiness > 0.0) { - int sx = (int) Math.round(v.getBlockX() * scale); - int sy = (int) Math.round(v.getBlockY() * scale); - int sz = (int) Math.round(v.getBlockZ() * scale); - double n = TreeFunctions.valueNoise3D(sx, sy, sz, weatherSeed); - double normalized = (v.getBlockY() - minY) / (double) span; - double gradient = 1.0 - 0.6 * normalized; - weathered = n < mossiness * gradient; - } - - if (weathered) { - BlockState wd = IrisProceduralBlocks.resolve(ruin.weatheredBlock(), ruin.weatheringPalette(), blocks, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); - if (wd != null) { - return wd; - } - } - return IrisProceduralBlocks.resolve(ruin.block(), ruin.blockPalette(), blocks, v.getBlockX(), v.getBlockY(), v.getBlockZ(), paletteRng); - } - - private static double clamp01(double value) { - if (value < 0.0) { - return 0.0; - } - if (value > 1.0) { - return 1.0; - } - return value; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java b/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java deleted file mode 100644 index 83e8ba91d..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ruin/RuinShapes.java +++ /dev/null @@ -1,146 +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.procedural.ruin; - -import art.arcane.iris.engine.object.procedural.tree.TreeFunctions; -import art.arcane.volmlib.util.math.RNG; - -final class RuinShapes { - private RuinShapes() { - } - - static void pillar(RuinBlockCanvas canvas, int width, int height, RNG rng) { - int half = (width - 1) / 2; - int broken = Math.max(2, height - rng.i(0, Math.max(1, height / 3))); - for (int y = 0; y < broken; y++) { - boolean bottom = y == 0; - int jitter = y >= broken - 1 ? rng.i(0, 2) : 0; - for (int x = -half; x <= half; x++) { - for (int z = -half; z <= half; z++) { - if (y == broken - 1 && jitter > 0 && (Math.abs(x) == half || Math.abs(z) == half) && rng.chance(0.5)) { - continue; - } - canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, bottom); - } - } - } - - int stub = rng.i(0, 3); - if (stub > 0) { - int dir = rng.i(0, 4); - int dx = dir == 0 ? 1 : (dir == 1 ? -1 : 0); - int dz = dir == 2 ? 1 : (dir == 3 ? -1 : 0); - for (int s = 1; s <= stub; s++) { - canvas.set((half + s) * dx, 0, (half + s) * dz, RuinBlockCanvas.Role.STRUCTURE, true); - } - } - } - - static void wall(RuinBlockCanvas canvas, int thickness, int length, int height, RNG rng) { - int half = (length - 1) / 2; - int tHalf = (thickness - 1) / 2; - long edgeSeed = rng.lmax(); - for (int z = -half; z <= half; z++) { - int top = height - jaggedDrop(z, height, edgeSeed); - for (int y = 0; y < top; y++) { - if (y > 0 && rng.chance(0.10)) { - continue; - } - for (int x = -tHalf; x <= thickness - 1 - tHalf; x++) { - canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, y == 0); - } - } - } - } - - static void arch(RuinBlockCanvas canvas, int thickness, int span, int height, RNG rng) { - int legSpacing = Math.max(2, span); - int legGap = (legSpacing - 1) / 2; - int tHalf = (thickness - 1) / 2; - int legTop = Math.max(2, height - Math.max(2, (legSpacing / 2))); - - for (int side = -1; side <= 1; side += 2) { - int legZ = side * legGap; - for (int y = 0; y < legTop; y++) { - for (int x = -tHalf; x <= thickness - 1 - tHalf; x++) { - canvas.set(x, y, legZ, RuinBlockCanvas.Role.STRUCTURE, y <= 1); - } - } - } - - double radius = legGap; - int crown = legTop + (int) Math.round(radius); - for (int z = -legGap; z <= legGap; z++) { - double inside = radius * radius - (z * z); - if (inside < 0) { - continue; - } - int y = legTop + (int) Math.round(Math.sqrt(inside)); - for (int yy = legTop; yy <= y && yy <= crown; yy++) { - boolean keystone = Math.abs(z) <= 1; - for (int x = -tHalf; x <= thickness - 1 - tHalf; x++) { - canvas.set(x, yy, z, RuinBlockCanvas.Role.STRUCTURE, keystone); - } - } - } - } - - static void floorSlab(RuinBlockCanvas canvas, int width, int length, int thickness) { - int xHalf = (width - 1) / 2; - int zHalf = (length - 1) / 2; - for (int y = 0; y < thickness; y++) { - for (int x = -xHalf; x <= width - 1 - xHalf; x++) { - for (int z = -zHalf; z <= length - 1 - zHalf; z++) { - canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, y == 0); - } - } - } - } - - static void rubble(RuinBlockCanvas canvas, int width, int length, int peak, RNG rng) { - int xHalf = (width - 1) / 2; - int zHalf = (length - 1) / 2; - long blobSeed = rng.lmax(); - double rx = Math.max(1.0, width / 2.0); - double rz = Math.max(1.0, length / 2.0); - - for (int x = -xHalf; x <= width - 1 - xHalf; x++) { - for (int z = -zHalf; z <= length - 1 - zHalf; z++) { - double radial = (x * x) / (rx * rx) + (z * z) / (rz * rz); - if (radial > 1.2) { - continue; - } - double falloff = Math.max(0.0, 1.0 - radial); - double noise = art.arcane.iris.engine.object.procedural.tree.TreeFunctions.valueNoise3D(x, 0, z, blobSeed); - int columnHeight = (int) Math.round(peak * falloff * (0.6 + 0.4 * noise)); - for (int y = 0; y <= columnHeight; y++) { - if (y > 0 && rng.chance(0.25)) { - continue; - } - canvas.set(x, y, z, RuinBlockCanvas.Role.STRUCTURE, y == 0 && radial < 0.5); - } - } - } - } - - private static int jaggedDrop(int z, int height, long seed) { - double n = art.arcane.iris.engine.object.procedural.tree.TreeFunctions.valueNoise1D(z * 0.9, seed); - return (int) Math.round(n * Math.max(1, height - 1) * 0.6); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java deleted file mode 100644 index 48bbd4304..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ProceduralTreeGenerator.java +++ /dev/null @@ -1,127 +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.procedural.tree; - -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.block.BlockState; -import com.volmit.object.ObjectBlock; -import com.volmit.geometry.BlockPosition; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public final class ProceduralTreeGenerator { - private ProceduralTreeGenerator() { - } - - public static ProceduralShape generate(Tree tree, int height, RNG rng, ObjectBuilder blocks) { - TreeBlockCanvas canvas = new TreeBlockCanvas(); - long baseSeed = rng.getSeed(); - - List limbs = TreeTrunkBuilder.build(canvas, tree, height); - - boolean wantEndpoints = tree.decorators() != null && !tree.decorators().isEmpty(); - List branchEndpoints = wantEndpoints ? new ArrayList<>() : null; - - int limbIndex = 0; - for (TreeTrunkBuilder.Limb limb : limbs) { - TreeCanopyBuilder.build(canvas, tree, height, limb.offsets(), limb.branchStartY(), baseSeed + limbIndex * 131L, branchEndpoints); - limbIndex++; - } - - if (wantEndpoints) { - TreeDecoratorApplier.apply(canvas, tree, baseSeed, branchEndpoints); - } - - if (tree.roots()) { - TreeRootBuilder.build(canvas, tree, height, baseSeed); - } - - if (tree.plausible()) { - TreeSupport.ensureLeavesSupported(canvas, 24); - } - - Map resolved = new HashMap<>(); - Set trunkPositions = new HashSet<>(); - Set leafPositions = new HashSet<>(); - for (Map.Entry entry : canvas.getCells().entrySet()) { - TreeBlockCanvas.Cell cell = entry.getValue(); - BlockState state = TreeBlockResolver.resolve(tree, blocks, cell, entry.getKey()); - if (state == null) { - continue; - } - resolved.put(entry.getKey(), state); - if (cell.role() == TreeBlockCanvas.Role.TRUNK || cell.role() == TreeBlockCanvas.Role.SECONDARY_TRUNK) { - trunkPositions.add(entry.getKey()); - } else if (cell.role() == TreeBlockCanvas.Role.LEAF || cell.role() == TreeBlockCanvas.Role.SECONDARY_LEAF) { - leafPositions.add(entry.getKey()); - } - } - - TreePlausibility.apply(resolved, trunkPositions, leafPositions, tree, blocks); - - return assemble(resolved); - } - - private static ProceduralShape assemble(Map resolved) { - if (resolved.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 (TreeBlockCanvas.Vec v : resolved.keySet()) { - minX = Math.min(minX, v.x()); - minY = Math.min(minY, v.y()); - minZ = Math.min(minZ, v.z()); - maxX = Math.max(maxX, v.x()); - maxY = Math.max(maxY, v.y()); - maxZ = Math.max(maxZ, v.z()); - } - - int w = maxX - minX + 1; - int h = maxY - minY + 1; - int d = maxZ - minZ + 1; - int cx = w / 2; - int cy = h / 2; - int cz = d / 2; - - List placed = new ArrayList<>(resolved.size()); - for (Map.Entry entry : resolved.entrySet()) { - TreeBlockCanvas.Vec v = entry.getKey(); - int nx = v.x() - minX - cx; - int ny = v.y() - cy + 1; - int nz = v.z() - minZ - cz; - placed.add(new ObjectBlock(new BlockPosition(nx, ny, nz), entry.getValue())); - } - - return new ProceduralShape(w, h, d, placed); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java deleted file mode 100644 index f6560470a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/ResolvedTree.java +++ /dev/null @@ -1,96 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.iris.engine.object.procedural.ProceduralShape; -import art.arcane.iris.engine.object.procedural.ResolvedProceduralPlacement; -import art.arcane.iris.modules.objects.ObjectBuilder; -import art.arcane.volmlib.util.math.RNG; -import com.volmit.object.PlaceableObject; -import com.volmit.resource.PackResources; - -import java.util.ArrayList; -import java.util.List; - -/** A procedural tree made placeable: its variants are baked by {@link ProceduralTreeGenerator}, at heights spread between its limits. */ -public final class ResolvedTree extends ResolvedProceduralPlacement { - private static final long VARIANT_SEED_STRIDE = 7919L; - private static final double HEIGHT_JITTER_FRACTION = 0.3; - private static final int MINIMUM_HEIGHT = 2; - - private final Tree settings; - - public ResolvedTree(Tree settings, PackResources resources) { - super(new Shape(settings.name(), settings.chance(), settings.density(), settings.seed(), settings.variants(), settings.mode(), - settings.rotation(), settings.clamp(), settings.carvingSupport(), settings.underwater(), settings.translate(), - settings.stiltSettings().orElse(null), settings.vacuumSettings().orElse(null)), resources); - this.settings = settings; - } - - public String getVariantLoadKey(int index) { - return Tree.variantLoadKey(settings.name(), index); - } - - @Override - public boolean plausible() { - return settings.plausible(); - } - - @Override - public boolean tree() { - return true; - } - - @Override - protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks) { - throw new UnsupportedOperationException("Tree variants are baked with heights spread over the limits"); - } - - @Override - protected List bake(ObjectBuilder blocks) { - List baked = new ArrayList<>(); - int count = Math.max(1, settings.variants()); - int lo = Math.min(settings.heightMin(), settings.heightMax()); - int hi = Math.max(settings.heightMin(), settings.heightMax()); - RNG heightRng = new RNG(settings.seed()); - - for (int i = 0; i < count; i++) { - int height = variantHeight(heightRng, lo, hi, count, i); - ProceduralShape generated = ProceduralTreeGenerator.generate(settings, Math.max(MINIMUM_HEIGHT, height), - new RNG(settings.seed() + (i * VARIANT_SEED_STRIDE)), blocks); - if (generated == null || generated.blocks().isEmpty()) { - continue; - } - baked.add(build(blocks, getVariantLoadKey(i), generated)); - } - - return baked; - } - - private static int variantHeight(RNG heightRng, int lo, int hi, int count, int index) { - if (count == 1 || lo == hi) { - return heightRng.i(lo, hi + 1); - } - double step = (hi - lo) / (double) (count - 1); - double base = lo + step * index; - double jitter = heightRng.d(-step * HEIGHT_JITTER_FRACTION, step * HEIGHT_JITTER_FRACTION); - return (int) Math.round(Math.max(lo, Math.min(hi, base + jitter))); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java deleted file mode 100644 index ad0261b81..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockCanvas.java +++ /dev/null @@ -1,102 +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.procedural.tree; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class TreeBlockCanvas { - public record Vec(int x, int y, int z) { - } - - public enum Role { - TRUNK, SECONDARY_TRUNK, LEAF, SECONDARY_LEAF, DECORATOR - } - - public enum Axis { - NONE, X, Y, Z - } - - public record Cell(Role role, Axis axis, boolean exposed, int decoratorIndex, String facing) { - } - - private final Map cells = new HashMap<>(); - private final Set trunk = new HashSet<>(); - private final Set leaf = new HashSet<>(); - - public boolean has(int x, int y, int z) { - return cells.containsKey(new Vec(x, y, z)); - } - - public Cell get(int x, int y, int z) { - return cells.get(new Vec(x, y, z)); - } - - public void setTrunk(int x, int y, int z, Role role, Axis axis) { - Vec v = new Vec(x, y, z); - cells.put(v, new Cell(role, axis, false, -1, null)); - trunk.add(v); - leaf.remove(v); - } - - public boolean setLeaf(int x, int y, int z, Role role) { - Vec v = new Vec(x, y, z); - if (cells.containsKey(v)) { - return false; - } - cells.put(v, new Cell(role, Axis.NONE, false, -1, null)); - leaf.add(v); - return true; - } - - public boolean setDecor(int x, int y, int z, int decoratorIndex, String facing) { - Vec v = new Vec(x, y, z); - if (cells.containsKey(v)) { - return false; - } - cells.put(v, new Cell(Role.DECORATOR, Axis.NONE, false, decoratorIndex, facing)); - return true; - } - - public void markExposed(int x, int y, int z) { - Vec v = new Vec(x, y, z); - Cell c = cells.get(v); - if (c != null && !c.exposed()) { - cells.put(v, new Cell(c.role(), c.axis(), true, c.decoratorIndex(), c.facing())); - } - } - - public Map getCells() { - return cells; - } - - public Set getTrunk() { - return trunk; - } - - public Set getLeaf() { - return leaf; - } - - public boolean isEmpty() { - return cells.isEmpty(); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java deleted file mode 100644 index 745cf7d85..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeBlockResolver.java +++ /dev/null @@ -1,165 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeSecondaryLeaf; -import art.arcane.iris.modules.objects.tree.TreeDecorator; -import art.arcane.iris.modules.objects.ObjectBuilder; -import com.volmit.block.PaletteSpec; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.modules.objects.tree.Tree; -import com.volmit.block.BlockState; -import art.arcane.volmlib.util.math.RNG; - -public final class TreeBlockResolver { - private TreeBlockResolver() { - } - - public static BlockState resolve(Tree tree, ObjectBuilder blocks, TreeBlockCanvas.Cell cell, TreeBlockCanvas.Vec pos) { - RNG paletteRng = new RNG(tree.seed()); - RNG posRng = new RNG(tree.seed() ^ positionHash(pos)); - - switch (cell.role()) { - case TRUNK -> { - BlockState state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), blocks, pos, paletteRng); - return finishTrunk(state, cell, blocks); - } - case SECONDARY_TRUNK -> { - BlockState state = resolveBlock(tree.secondaryTrunk().orElse(null), tree.secondaryTrunkPalette().orElse(null), blocks, pos, paletteRng); - if (state == null) { - state = resolveBlock(tree.trunk(), tree.trunkPalette().orElse(null), blocks, pos, paletteRng); - } - return finishTrunk(state, cell, blocks); - } - case LEAF -> { - return resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), blocks, pos, paletteRng); - } - case SECONDARY_LEAF -> { - BlockState state = resolveSecondaryLeaf(tree, blocks, pos, paletteRng, posRng); - if (state == null) { - state = resolveBlock(tree.leaves(), tree.leavesPalette().orElse(null), blocks, pos, paletteRng); - } - return state; - } - case DECORATOR -> { - int index = cell.decoratorIndex(); - if (index < 0 || tree.decorators() == null || index >= tree.decorators().size()) { - return null; - } - TreeDecorator dec = tree.decorators().get(index); - BlockState state = resolveBlock(dec.block(), dec.palette().orElse(null), blocks, pos, paletteRng); - if (state != null && cell.facing() != null && IrisProceduralBlocks.hasProperty(state, "facing")) { - try { - state = blocks.withProperty(state, "facing", cell.facing().toLowerCase()); - } catch (IllegalArgumentException ignored) { - } - } - return state; - } - default -> { - return null; - } - } - } - - private static BlockState finishTrunk(BlockState state, TreeBlockCanvas.Cell cell, ObjectBuilder blocks) { - if (state == null) { - return null; - } - if (cell.axis() != TreeBlockCanvas.Axis.NONE && IrisProceduralBlocks.hasProperty(state, "axis")) { - try { - state = blocks.withProperty(state, "axis", cell.axis().name().toLowerCase()); - } catch (IllegalArgumentException ignored) { - } - } - if (cell.exposed()) { - return woodCap(state, blocks); - } - return state; - } - - private static BlockState resolveSecondaryLeaf(Tree tree, ObjectBuilder blocks, TreeBlockCanvas.Vec pos, RNG paletteRng, RNG posRng) { - PaletteSpec secondaryPalette = tree.secondaryLeavesPalette().orElse(null); - if (IrisProceduralBlocks.paletteSet(secondaryPalette)) { - return blocks.pick(secondaryPalette, paletteRng.getSeed(), pos.x(), pos.y(), pos.z()); - } - if (tree.weightedSecondaryLeaves() != null && !tree.weightedSecondaryLeaves().isEmpty()) { - String picked = pickWeighted(tree, posRng); - return picked == null ? null : blocks.block(picked); - } - if (tree.secondaryLeaves().isPresent() && !tree.secondaryLeaves().get().isEmpty()) { - return blocks.block(tree.secondaryLeaves().get()); - } - return null; - } - - private static String pickWeighted(Tree tree, RNG rng) { - int total = 0; - for (art.arcane.iris.modules.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { - total += Math.max(0, s.weight()); - } - if (total <= 0) { - return null; - } - double r = rng.nextDouble() * total; - double cumulative = 0; - for (art.arcane.iris.modules.objects.tree.TreeSecondaryLeaf s : tree.weightedSecondaryLeaves()) { - cumulative += Math.max(0, s.weight()); - if (r < cumulative) { - return s.block(); - } - } - return tree.weightedSecondaryLeaves().get(tree.weightedSecondaryLeaves().size() - 1).block(); - } - - private static BlockState resolveBlock(String block, PaletteSpec palette, ObjectBuilder blocks, TreeBlockCanvas.Vec pos, RNG paletteRng) { - return IrisProceduralBlocks.resolve(block, palette, blocks, pos.x(), pos.y(), pos.z(), paletteRng); - } - - private static BlockState woodCap(BlockState state, ObjectBuilder blocks) { - String key = state.key(); - int bracket = key.indexOf('['); - String base = bracket < 0 ? key : key.substring(0, bracket); - String woodKey = null; - if (base.endsWith("_log")) { - woodKey = base.substring(0, base.length() - 4) + "_wood"; - } else if (base.endsWith("_stem")) { - woodKey = base.substring(0, base.length() - 5) + "_hyphae"; - } - if (woodKey == null) { - return state; - } - BlockState wood = blocks.block(woodKey); - if (wood == null) { - return state; - } - String axis = IrisProceduralBlocks.propertyValue(state, "axis"); - if (axis != null && IrisProceduralBlocks.hasProperty(wood, "axis")) { - try { - wood = blocks.withProperty(wood, "axis", axis); - } catch (IllegalArgumentException ignored) { - } - } - return wood; - } - - private static long positionHash(TreeBlockCanvas.Vec pos) { - return pos.x() * 73856093L ^ pos.y() * 19349663L ^ pos.z() * 83492791L; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java deleted file mode 100644 index fb5e8dd97..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeCanopyBuilder.java +++ /dev/null @@ -1,352 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeSubBranches; -import art.arcane.iris.modules.objects.tree.TreeLayer; -import art.arcane.iris.modules.objects.tree.TreeCanopy; -import art.arcane.iris.modules.objects.tree.TreeBranches; -import art.arcane.iris.modules.objects.tree.TreeProfile; -import art.arcane.iris.modules.objects.tree.TreeLeafMode; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -import java.util.List; - -public final class TreeCanopyBuilder { - private TreeCanopyBuilder() { - } - - public static void build(TreeBlockCanvas canvas, Tree tree, int height, double[][] offsets, - int branchStartY, long baseSeed, List branchEndpoints) { - TreeCanopy canopy = tree.canopy(); - if (canopy == null) { - canopy = new TreeCanopy(); - } - TreeBranches branches = canopy.branches().orElse(null); - - double[][] layers = resolveLayers(canopy, tree.profile(), height, branches != null); - - if (branches != null) { - if (layers.length > 0) { - double[][] crown = new double[][]{layers[layers.length - 1]}; - volumeCanopy(canvas, tree, crown, canopy, baseSeed, offsets); - } - placeApexCap(canvas, tree, height, layers, offsets, baseSeed); - branchCanopy(canvas, tree, height, branches, branchStartY, baseSeed, offsets, branchEndpoints); - } else { - volumeCanopy(canvas, tree, layers, canopy, baseSeed, offsets); - } - } - - private static void placeApexCap(TreeBlockCanvas canvas, Tree tree, int height, double[][] layers, - double[][] offsets, long baseSeed) { - int ocx = 0; - int ocz = 0; - if (offsets != null && offsets.length > 0) { - ocx = (int) Math.round(offsets[offsets.length - 1][0]); - ocz = (int) Math.round(offsets[offsets.length - 1][1]); - } - double maxR = 2; - for (double[] layer : layers) { - maxR = Math.max(maxR, layer[1]); - } - int capRadius = Math.max(2, Math.min(3, (int) Math.round(maxR * 0.35))); - TreeCanopy canopy = tree.canopy(); - TreeLeafMode mode = canopy != null ? canopy.mode() : TreeLeafMode.TRIMMED; - double density = canopy != null ? canopy.leafDensity() : 1.0; - placeLeafCluster(canvas, tree, ocx, height - 1, ocz, capRadius, mode, density, baseSeed + 5555L); - } - - private static double[][] resolveLayers(TreeCanopy canopy, TreeProfile profile, int height, boolean branchDriven) { - KList explicit = new KList<>(canopy.layers()); - if (explicit != null && !explicit.isEmpty()) { - double[][] out = new double[explicit.size()][2]; - for (int i = 0; i < explicit.size(); i++) { - out[i][0] = explicit.get(i).yOffset(); - out[i][1] = explicit.get(i).radius(); - } - return out; - } - return TreeProfiles.presetLayers(profile, height, branchDriven); - } - - private static void volumeCanopy(TreeBlockCanvas canvas, Tree tree, double[][] layers, - TreeCanopy canopy, long baseSeed, double[][] offsets) { - int ocx = 0; - int ocz = 0; - if (offsets != null && offsets.length > 0) { - ocx = (int) Math.round(offsets[offsets.length - 1][0]); - ocz = (int) Math.round(offsets[offsets.length - 1][1]); - } - - double startAngle = canopy.startAngle(); - double squish = canopy.squish(); - TreeLeafMode mode = canopy.mode(); - double leafDensity = canopy.leafDensity(); - - for (double[] layer : layers) { - int yCenter = (int) Math.round(layer[0]); - double radius = layer[1]; - int halfH = layerHalfHeight(radius, startAngle, squish); - int downH = startAngle < 90.0 - ? (int) Math.ceil(radius * Math.cos(Math.toRadians(startAngle)) * squish) - : 0; - int skirt = downH; - - for (int y = yCenter - skirt; y <= yCenter + halfH; y++) { - int dy = y - yCenter; - double layerR; - if (halfH > 0 && dy >= 0) { - layerR = radius * Math.sqrt(Math.max(0.0, 1.0 - Math.pow(dy / (double) halfH, 2))); - } else if (skirt > 0 && dy < 0) { - layerR = radius * Math.sqrt(Math.max(0.0, 1.0 - Math.pow(dy / (double) skirt, 2))); - } else { - layerR = radius; - } - if (layerR < 0.5) { - continue; - } - placeLeafDisc(canvas, tree, ocx, y, ocz, layerR, mode, leafDensity, baseSeed + y); - } - } - } - - private static int layerHalfHeight(double radius, double startAngle, double squish) { - if (startAngle >= 180.0) { - return 0; - } - return (int) Math.ceil(radius * squish); - } - - private static void placeLeafDisc(TreeBlockCanvas canvas, Tree tree, int cx, int cy, int cz, - double radius, TreeLeafMode mode, double density, long seed) { - double sx = stretchX(tree); - double sz = stretchZ(tree); - RNG rng = new RNG(seed); - int irx = (int) Math.ceil(radius * sx); - int irz = (int) Math.ceil(radius * sz); - for (int dx = -irx; dx <= irx; dx++) { - for (int dz = -irz; dz <= irz; dz++) { - double ddx = dx / sx; - double ddz = dz / sz; - double dist = Math.sqrt(ddx * ddx + ddz * ddz); - boolean corner = Math.abs(dx) == irx && Math.abs(dz) == irz; - if (!passesLeafTest(mode, dist, radius, density, rng, cx + dx, cy, cz + dz, seed, corner)) { - continue; - } - canvas.setLeaf(cx + dx, cy, cz + dz, resolveLeaf(tree, rng)); - } - } - } - - private static void placeLeafCluster(TreeBlockCanvas canvas, Tree tree, int cx, int cy, int cz, - int radius, TreeLeafMode mode, double density, long seed) { - double sx = stretchX(tree); - double sz = stretchZ(tree); - RNG rng = new RNG(seed); - int irx = (int) Math.ceil(radius * sx); - int irz = (int) Math.ceil(radius * sz); - for (int dx = -irx; dx <= irx; dx++) { - for (int dy = -radius; dy <= radius; dy++) { - for (int dz = -irz; dz <= irz; dz++) { - double ddx = dx / sx; - double ddz = dz / sz; - double dist = Math.sqrt(ddx * ddx + dy * dy + ddz * ddz); - boolean corner = Math.abs(dx) == irx && Math.abs(dz) == irz; - if (!passesLeafTest(mode, dist, radius, density, rng, cx + dx, cy + dy, cz + dz, seed, corner)) { - continue; - } - canvas.setLeaf(cx + dx, cy + dy, cz + dz, resolveLeaf(tree, rng)); - } - } - } - } - - private static double stretchX(Tree tree) { - TreeCanopy c = tree.canopy(); - return c == null ? 1.0 : Math.max(0.1, c.crownStretchX()); - } - - private static double stretchZ(Tree tree) { - TreeCanopy c = tree.canopy(); - return c == null ? 1.0 : Math.max(0.1, c.crownStretchZ()); - } - - private static boolean passesLeafTest(TreeLeafMode mode, double dist, double radius, double density, - RNG rng, int wx, int wy, int wz, long seed, boolean corner) { - switch (mode) { - case TRIMMED -> { - return !(dist > radius || corner); - } - case FILLED -> { - return dist <= radius; - } - case DENSITY -> { - if (dist > radius) { - return false; - } - return rng.nextDouble() <= density * (1.0 - (dist / (radius + 1.0))); - } - case NOISE -> { - if (dist > radius) { - return false; - } - return TreeFunctions.valueNoise3D(wx, wy, wz, seed) <= density; - } - case HOLLOW -> { - return dist <= radius && dist > radius - 1.0; - } - case GRADIENT -> { - if (dist > radius) { - return false; - } - return rng.nextDouble() <= density * Math.pow(1.0 - (dist / (radius + 1.0)), 2); - } - case CLUMPED -> { - if (dist > radius) { - return false; - } - return TreeFunctions.valueNoise3D(Math.floorDiv(wx, 2), Math.floorDiv(wy, 2), Math.floorDiv(wz, 2), seed) <= density; - } - case TATTERED -> { - if (dist > radius || corner) { - return false; - } - return !(dist > radius - 1.5 && rng.nextDouble() < 0.6); - } - case SPARSE -> { - if (dist > radius) { - return false; - } - return rng.nextDouble() <= density * 0.4; - } - default -> { - return dist <= radius; - } - } - } - - private static TreeBlockCanvas.Role resolveLeaf(Tree tree, RNG rng) { - boolean hasSecondary = IrisProceduralBlocks.paletteSet(tree.secondaryLeavesPalette()) - || (tree.weightedSecondaryLeaves() != null && !tree.weightedSecondaryLeaves().isEmpty()) - || tree.secondaryLeaves().filter(leaves -> !leaves.isEmpty()).isPresent(); - if (!hasSecondary || tree.secondaryLeafFraction() <= 0.0) { - return TreeBlockCanvas.Role.LEAF; - } - if (rng.nextDouble() >= tree.secondaryLeafFraction()) { - return TreeBlockCanvas.Role.LEAF; - } - return TreeBlockCanvas.Role.SECONDARY_LEAF; - } - - private static void branchCanopy(TreeBlockCanvas canvas, Tree tree, int height, - TreeBranches branches, int branchStartY, long baseSeed, double[][] offsets, - List branchEndpoints) { - long branchSeed = baseSeed + 9999; - RNG branchRng = new RNG(branchSeed); - TreeSubBranches sub = branches.subBranches().orElse(null); - int depth = branches.branchDepth(); - int branchIndex = 0; - - for (int y = Math.max(0, branchStartY); y < height; y++) { - double t = y / (double) Math.max(height - 1, 1); - double p = TreeFunctions.branchProbability(branches, t, branchSeed); - if (branchRng.nextDouble() > p) { - continue; - } - - int ox = 0; - int oz = 0; - if (offsets != null && y < offsets.length) { - ox = (int) Math.round(offsets[y][0]); - oz = (int) Math.round(offsets[y][1]); - } - - double az = TreeFunctions.azimuthDegrees(branches.azimuthMode(), t, branchIndex, tree, branches.azimuth(), branchRng); - branchIndex++; - double branchLen = TreeFunctions.branchLength(branches, t); - double effElevation = branches.leafStartUp() ? Math.max(0.0, branches.elevation()) : branches.elevation(); - int[] end = branchEndpoint(ox, y, oz, az, effElevation, branchLen); - int[] tip = rasterizeBranch(canvas, ox, y, oz, end[0], end[1], end[2], branches.sag()); - - if (branchEndpoints != null) { - branchEndpoints.add(new int[]{tip[0], tip[1], tip[2], ox, oz}); - } - placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], branches.clusterRadius(), - branches.clusterMode(), branches.clusterDensity(), branchSeed + y); - - growSubBranches(canvas, tree, tip[0], tip[1], tip[2], az, effElevation, branchLen, sub, depth, branchSeed + y + 1000L); - } - } - - private static void growSubBranches(TreeBlockCanvas canvas, Tree tree, int ox, int oy, int oz, - double az, double el, double len, TreeSubBranches sub, int depth, long seed) { - if (sub == null || depth <= 0) { - return; - } - int count = Math.max(1, sub.count()); - for (int si = 0; si < count; si++) { - double yawOffset = sub.yawDelta() * (si - (count - 1) / 2.0); - double subAz = az + yawOffset; - double subEl = el + sub.pitchDelta(); - double subLen = len * sub.lengthScale(); - int[] end = branchEndpoint(ox, oy, oz, subAz, subEl, subLen); - int[] tip = rasterizeBranch(canvas, ox, oy, oz, end[0], end[1], end[2], sub.sag()); - placeLeafCluster(canvas, tree, tip[0], tip[1], tip[2], sub.clusterRadius(), - sub.clusterMode(), sub.clusterDensity(), seed + si * 131L); - growSubBranches(canvas, tree, tip[0], tip[1], tip[2], subAz, subEl, subLen, sub, depth - 1, seed + si * 131L + 17L); - } - } - - private static int[] branchEndpoint(int ox, int oy, int oz, double azimuthDeg, double elevationDeg, double length) { - double azRad = Math.toRadians(azimuthDeg); - double elRad = Math.toRadians(elevationDeg); - double dx = length * Math.cos(elRad) * Math.sin(azRad); - double dy = length * Math.sin(elRad); - double dz = length * Math.cos(elRad) * Math.cos(azRad); - return new int[]{ox + (int) Math.round(dx), oy + (int) Math.round(dy), oz + (int) Math.round(dz)}; - } - - private static int[] rasterizeBranch(TreeBlockCanvas canvas, int ox, int oy, int oz, int ex, int ey, int ez, double sag) { - int dx = ex - ox; - int dy = ey - oy; - int dz = ez - oz; - double horizontal = Math.sqrt(dx * dx + dz * dz); - double sagBlocks = sag * horizontal; - int steps = Math.max(Math.max(Math.abs(dx), Math.abs(dz)), - Math.max((int) (Math.abs(dy) + Math.ceil(sagBlocks)), 1)); - TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(dx, dy, dz); - - int[] tip = new int[]{ox, oy, oz}; - for (int i = 0; i <= steps; i++) { - double t = i / (double) steps; - int x = (int) Math.round(ox + dx * t); - int y = (int) Math.round(oy + dy * t - sagBlocks * t * t); - int z = (int) Math.round(oz + dz * t); - if (!canvas.has(x, y, z)) { - canvas.setTrunk(x, y, z, TreeBlockCanvas.Role.TRUNK, axis); - } - tip = new int[]{x, y, z}; - } - return tip; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java deleted file mode 100644 index 4f648781f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeDecoratorApplier.java +++ /dev/null @@ -1,280 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeDecorator; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.math.RNG; - -import java.util.List; -import java.util.Map; - -public final class TreeDecoratorApplier { - private TreeDecoratorApplier() { - } - - public static void apply(TreeBlockCanvas canvas, Tree tree, long baseSeed, List branchEndpoints) { - List decorators = tree.decorators(); - if (decorators == null || decorators.isEmpty()) { - return; - } - RNG rng = new RNG(baseSeed + 77777L); - - for (int idx = 0; idx < decorators.size(); idx++) { - TreeDecorator dec = decorators.get(idx); - boolean hasBlock = (dec.block() != null && !dec.block().isEmpty()) || dec.palette().isPresent(); - if (!hasBlock) { - continue; - } - switch (dec.target()) { - case BRANCH_TIP -> branchTip(canvas, dec, idx, branchEndpoints, rng); - case TRUNK_SURFACE -> trunkSurface(canvas, dec, idx, rng); - case CANOPY_TOP -> canopyTop(canvas, dec, idx, rng); - case CANOPY_BOTTOM -> canopyBottom(canvas, dec, idx, rng); - case TRUNK_BASE -> trunkBase(canvas, dec, idx, rng); - case LEAF_SURFACE -> leafSurface(canvas, dec, idx, rng); - case CANOPY_HANG -> canopyHang(canvas, dec, idx, rng); - case BRANCH_SURFACE -> branchSurface(canvas, dec, idx, rng); - case TRUNK_TOP -> trunkTop(canvas, dec, idx, rng); - case GROUND_SCATTER -> groundScatter(canvas, dec, idx, rng); - } - } - } - - private static void branchTip(TreeBlockCanvas canvas, TreeDecorator dec, int idx, List branchEndpoints, RNG rng) { - if (branchEndpoints == null) { - return; - } - for (int[] e : branchEndpoints) { - if (rng.nextDouble() > dec.chance()) { - continue; - } - if (canvas.has(e[0], e[1], e[2])) { - continue; - } - String facing = dec.axisAware() ? facingAway(e[3], e[4], e[0], e[2]) : null; - canvas.setDecor(e[0], e[1], e[2], idx, facing); - } - } - - private static void trunkSurface(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - String[] facings = {"west", "east", "north", "south"}; - for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { - for (int i = 0; i < sides.length; i++) { - int nx = v.x() + sides[i][0]; - int nz = v.z() + sides[i][1]; - if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(nx, v.y(), nz, idx, dec.axisAware() ? facings[i] : null); - } - } - } - - private static void leafSurface(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - int[][] sides = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - String[] facings = {"west", "east", "north", "south"}; - for (TreeBlockCanvas.Vec v : new KList<>(canvas.getLeaf())) { - for (int i = 0; i < sides.length; i++) { - int nx = v.x() + sides[i][0]; - int nz = v.z() + sides[i][1]; - if (canvas.has(nx, v.y(), nz) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(nx, v.y(), nz, idx, dec.axisAware() ? facings[i] : null); - } - } - } - - private static void branchSurface(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { - int ay = v.y() + 1; - if (canvas.has(v.x(), ay, v.z()) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(v.x(), ay, v.z(), idx, null); - } - } - - private static void canopyTop(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - KMap colTop = new KMap<>(); - for (TreeBlockCanvas.Vec v : canvas.getCells().keySet()) { - long key = pack(v.x(), v.z()); - Integer cur = colTop.get(key); - if (cur == null || v.y() > cur) { - colTop.put(key, v.y()); - } - } - for (Map.Entry e : colTop.entrySet()) { - int x = unpackX(e.getKey()); - int z = unpackZ(e.getKey()); - int aboveY = e.getValue() + 1; - if (canvas.has(x, aboveY, z) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(x, aboveY, z, idx, null); - } - } - - private static void canopyBottom(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - KMap colBottom = columnLeafBottoms(canvas); - for (Map.Entry e : colBottom.entrySet()) { - int x = unpackX(e.getKey()); - int z = unpackZ(e.getKey()); - int belowY = e.getValue() - 1; - if (canvas.has(x, belowY, z) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(x, belowY, z, idx, null); - } - } - - private static void canopyHang(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - int maxLen = Math.max(1, dec.length()); - KMap colBottom = columnLeafBottoms(canvas); - for (Map.Entry e : colBottom.entrySet()) { - if (rng.nextDouble() > dec.chance()) { - continue; - } - int x = unpackX(e.getKey()); - int z = unpackZ(e.getKey()); - int strand = rng.i(1, maxLen + 1); - for (int k = 1; k <= strand; k++) { - int yy = e.getValue() - k; - if (canvas.has(x, yy, z)) { - break; - } - canvas.setDecor(x, yy, z, idx, null); - } - } - } - - private static void trunkBase(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - int[][] sides = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; - for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { - if (v.y() != 0) { - continue; - } - for (int[] side : sides) { - int nx = v.x() + side[0]; - int nz = v.z() + side[1]; - if (canvas.has(nx, 0, nz) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(nx, 0, nz, idx, null); - } - } - } - - private static void trunkTop(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - int maxY = Integer.MIN_VALUE; - for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { - maxY = Math.max(maxY, v.y()); - } - if (maxY == Integer.MIN_VALUE) { - return; - } - for (TreeBlockCanvas.Vec v : new KList<>(canvas.getTrunk())) { - if (v.y() != maxY) { - continue; - } - int aboveY = v.y() + 1; - if (canvas.has(v.x(), aboveY, v.z()) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(v.x(), aboveY, v.z(), idx, null); - } - } - - private static void groundScatter(TreeBlockCanvas canvas, TreeDecorator dec, int idx, RNG rng) { - double cx = 0; - double cz = 0; - int count = 0; - double footprint = 1.0; - for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { - if (v.y() == 0) { - cx += v.x(); - cz += v.z(); - count++; - } - } - if (count == 0) { - return; - } - cx /= count; - cz /= count; - for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { - if (v.y() == 0) { - footprint = Math.max(footprint, Math.hypot(v.x() - cx, v.z() - cz)); - } - } - int radius = (int) Math.ceil(footprint + 3.0); - int icx = (int) Math.round(cx); - int icz = (int) Math.round(cz); - for (int dx = -radius; dx <= radius; dx++) { - for (int dz = -radius; dz <= radius; dz++) { - if (Math.hypot(dx, dz) > radius) { - continue; - } - int x = icx + dx; - int z = icz + dz; - if (canvas.has(x, 0, z) || rng.nextDouble() > dec.chance()) { - continue; - } - canvas.setDecor(x, 0, z, idx, null); - } - } - } - - private static KMap columnLeafBottoms(TreeBlockCanvas canvas) { - KMap colBottom = new KMap<>(); - for (TreeBlockCanvas.Vec v : canvas.getLeaf()) { - long key = pack(v.x(), v.z()); - Integer cur = colBottom.get(key); - if (cur == null || v.y() < cur) { - colBottom.put(key, v.y()); - } - } - return colBottom; - } - - private static String facingAway(int cx, int cz, int x, int z) { - int dx = x - cx; - int dz = z - cz; - if (Math.abs(dx) >= Math.abs(dz)) { - return dx >= 0 ? "east" : "west"; - } - return dz >= 0 ? "south" : "north"; - } - - private static long pack(int x, int z) { - return (((long) x) << 32) ^ (z & 0xFFFFFFFFL); - } - - private static int unpackX(long key) { - return (int) (key >> 32); - } - - private static int unpackZ(long key) { - return (int) (key & 0xFFFFFFFFL); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java deleted file mode 100644 index 7e7eb9afd..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeFunctions.java +++ /dev/null @@ -1,197 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeBranches; -import art.arcane.iris.modules.objects.tree.TreeFunction; -import art.arcane.iris.modules.objects.tree.TreeAzimuthMode; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.volmlib.util.math.RNG; - -public final class TreeFunctions { - private static final double GOLDEN_ANGLE = 137.50776405003785; - - private TreeFunctions() { - } - - public static double trunkWidthMultiplier(Tree tree, double t) { - double start = tree.shapeStart(); - double end = tree.shapeEnd(); - return switch (tree.trunkShape()) { - case CONSTANT -> 1.0; - case LINEAR -> start + (end - start) * t; - case SIGMOID -> 1.0 / (1.0 + Math.exp(tree.shapeSteepness() * (t - 0.5))); - case LOG -> { - double base = Math.max(1.0001, tree.shapeBase()); - if (t <= 0.0) { - yield 1.0; - } - yield Math.max(0.0, 1.0 - Math.log(1.0 + t * (base - 1.0)) / Math.log(base)); - } - case SINE -> { - double period = tree.shapePeriod() == 0 ? 1.0 : tree.shapePeriod(); - yield 1.0 + tree.shapeAmplitude() * Math.sin(2.0 * Math.PI * t / period); - } - case PARABOLIC -> { - double peak = tree.shapePeakOffset(); - double floor = tree.shapeFloor(); - double denom = Math.pow(Math.max(peak, 1.0 - peak), 2); - if (denom == 0) { - denom = 1; - } - yield floor + (1.0 - floor) * (Math.pow(t - peak, 2) / denom); - } - case EXPONENTIAL -> geometric(start, end, t); - case SQRT -> start + (end - start) * Math.sqrt(t); - case STEP -> t < tree.shapePeakOffset() ? start : end; - case BELL -> start + (end - start) * bell(t); - case EASE_IN_OUT -> start + (end - start) * smoothstep(t); - }; - } - - public static double curveProgress(TreeFunction fn, double t, double steepness) { - return switch (fn) { - case LINEAR, CONSTANT, SINE -> t; - case LOG -> Math.log(1.0 + t * (Math.E - 1.0)); - case SIGMOID -> 1.0 / (1.0 + Math.exp(-steepness * (t - 0.5))); - case PARABOLIC, EASE_IN_OUT -> smoothstep(t); - case EXPONENTIAL -> Math.pow(t, Math.max(1.0, steepness)); - case SQRT -> Math.sqrt(t); - case STEP -> t < 0.5 ? 0.0 : 1.0; - case BELL -> bell(t); - }; - } - - public static double branchLength(TreeBranches b, double t) { - double base = b.lengthBase(); - double crown = b.lengthCrown(); - double max = b.lengthMax(); - double v = switch (b.lengthFunction()) { - case CONSTANT -> b.lengthConstant(); - case LINEAR, SINE -> base + (crown - base) * t; - case SIGMOID -> max / (1.0 + Math.exp(-b.lengthSteepness() * (t - 0.5))); - case LOG -> max * Math.log(1.0 + t * (Math.E - 1.0)); - case PARABOLIC -> max * (1.0 - Math.pow(2.0 * t - 1.0, 2)); - case EXPONENTIAL -> geometric(base, crown, t); - case SQRT -> base + (crown - base) * Math.sqrt(t); - case STEP -> t < 0.5 ? base : crown; - case BELL -> base + (max - base) * bell(t); - case EASE_IN_OUT -> base + (crown - base) * smoothstep(t); - }; - return Math.max(1.0, v); - } - - public static double branchProbability(TreeBranches b, double t, long seed) { - double std = Math.max(b.probabilityStd(), 1e-6); - return switch (b.probabilityFunction()) { - case CONSTANT -> b.probabilityConstant(); - case LINEAR -> b.probabilityBase() + (b.probabilityCrown() - b.probabilityBase()) * t; - case SIGMOID -> 1.0 / (1.0 + Math.exp(-b.probabilitySteepness() * (t - b.probabilityMidpoint()))); - case TOP_HEAVY -> Math.pow(t, b.probabilityExponent()); - case GAUSSIAN -> Math.exp(-0.5 * Math.pow((t - b.probabilityMean()) / std, 2)); - case NOISE -> valueNoise1D(t * b.probabilityScale(), seed); - case BOTTOM_HEAVY -> Math.pow(1.0 - t, b.probabilityExponent()); - case PERIODIC -> b.probabilityConstant() * Math.pow(Math.max(0.0, Math.sin(2.0 * Math.PI * t * b.probabilityPeriods())), 8); - case BAND -> Math.abs(t - b.probabilityMean()) <= b.probabilityStd() ? b.probabilityConstant() : 0.0; - case INVERSE_GAUSSIAN -> b.probabilityConstant() * (1.0 - Math.exp(-0.5 * Math.pow((t - b.probabilityMean()) / std, 2))); - case EXPONENTIAL_DECAY -> b.probabilityConstant() * Math.exp(-b.probabilityExponent() * t); - }; - } - - public static double azimuthDegrees(TreeAzimuthMode mode, double t, int index, Tree tree, double constantBase, RNG rng) { - return switch (mode) { - case CONSTANT -> constantBase; - case LINEAR -> tree.azimuthStart() + (tree.azimuthEnd() - tree.azimuthStart()) * t; - case SPIRAL -> tree.azimuthStart() + tree.azimuthTurns() * 360.0 * t; - case SINE -> { - double period = tree.azimuthPeriod() == 0 ? 1.0 : tree.azimuthPeriod(); - yield tree.azimuthOffset() + tree.azimuthAmplitude() * Math.sin(2.0 * Math.PI * t / period); - } - case NOISE -> noiseAzimuth(t, tree.azimuthScale(), tree.seed()); - case RANDOM -> rng != null ? rng.d(0.0, 360.0) : constantBase; - case GOLDEN_ANGLE -> index >= 0 ? constantBase + index * GOLDEN_ANGLE : constantBase; - case ALTERNATING -> index >= 0 ? constantBase + (index % 2) * 180.0 : constantBase; - case WHORL -> { - int count = Math.max(1, tree.azimuthWhorlCount()); - yield index >= 0 ? constantBase + (index % count) * (360.0 / count) : constantBase; - } - case ZIGZAG -> index >= 0 ? constantBase + ((index % 2 == 0) ? -tree.azimuthAmplitude() : tree.azimuthAmplitude()) : constantBase; - }; - } - - public static TreeBlockCanvas.Axis logAxis(double dx, double dy, double dz) { - double ax = Math.abs(dx); - double ay = Math.abs(dy) * 1.8; - double az = Math.abs(dz); - if (ay >= ax && ay >= az) { - return TreeBlockCanvas.Axis.Y; - } - if (ax >= az) { - return TreeBlockCanvas.Axis.X; - } - return TreeBlockCanvas.Axis.Z; - } - - private static double geometric(double a, double b, double t) { - if (a <= 0.0 || b <= 0.0) { - return a + (b - a) * t; - } - return a * Math.pow(b / a, t); - } - - private static double bell(double t) { - return Math.exp(-Math.pow(t - 0.5, 2) / (2.0 * 0.15 * 0.15)); - } - - private static double smoothstep(double t) { - return 3.0 * t * t - 2.0 * t * t * t; - } - - public static double noiseAzimuth(double t, double scale, long seed) { - double a = valueNoise1D(t * scale, seed); - double b = valueNoise1D(t * scale * 0.5, seed + 1); - return ((a + b) / 2.0) * 360.0; - } - - public static double valueNoise1D(double x, long seed) { - long h = mix(seed * 0x9E3779B97F4A7C15L + Math.round(x * 1000.0)); - return unit(h); - } - - public static double valueNoise3D(int x, int y, int z, long seed) { - long h = mix(seed); - h = mix(h + x * 0x9E3779B97F4A7C15L); - h = mix(h + y * 0xC2B2AE3D27D4EB4FL); - h = mix(h + z * 0x165667B19E3779F9L); - return unit(h); - } - - private static long mix(long a) { - a ^= (a >>> 33); - a *= 0xff51afd7ed558ccdL; - a ^= (a >>> 33); - a *= 0xc4ceb9fe1a85ec53L; - a ^= (a >>> 33); - return a; - } - - private static double unit(long h) { - return (h >>> 11) * 0x1.0p-53; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java deleted file mode 100644 index c2e09d7d3..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreePlausibility.java +++ /dev/null @@ -1,109 +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.procedural.tree; - -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.iris.modules.objects.ObjectBuilder; -import com.volmit.block.BlockState; - -import java.util.ArrayDeque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public final class TreePlausibility { - private static final int MAX_DISTANCE = 7; - private static final int[][] NEIGHBORS = { - {1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1} - }; - - private TreePlausibility() { - } - - public static void apply(Map resolved, Set trunkPositions, - Set leafPositions, Tree tree, ObjectBuilder blocks) { - Set realLeaves = new HashSet<>(); - for (TreeBlockCanvas.Vec v : leafPositions) { - BlockState state = resolved.get(v); - if (state != null && IrisProceduralBlocks.hasProperty(state, "persistent") && IrisProceduralBlocks.hasProperty(state, "distance")) { - realLeaves.add(v); - } - } - if (realLeaves.isEmpty()) { - return; - } - - Map distance = computeDistances(trunkPositions, realLeaves); - - for (TreeBlockCanvas.Vec v : realLeaves) { - BlockState leaf = resolved.get(v); - Integer d = distance.get(v); - if (!tree.plausible()) { - leaf = withLeafState(blocks, leaf, "true", "1"); - } else if (d != null && d < MAX_DISTANCE) { - leaf = withLeafState(blocks, leaf, "false", String.valueOf(Math.max(1, d))); - } else { - leaf = withLeafState(blocks, leaf, "true", String.valueOf(MAX_DISTANCE)); - } - resolved.put(v, leaf); - } - } - - private static BlockState withLeafState(ObjectBuilder blocks, BlockState leaf, String persistent, String distance) { - return blocks.withProperty(blocks.withProperty(leaf, "persistent", persistent), "distance", distance); - } - - static Map computeDistances(Set trunkPositions, Set realLeaves) { - Map distance = new HashMap<>(); - ArrayDeque queue = new ArrayDeque<>(); - - for (TreeBlockCanvas.Vec v : realLeaves) { - for (int[] n : NEIGHBORS) { - if (trunkPositions.contains(new TreeBlockCanvas.Vec(v.x() + n[0], v.y() + n[1], v.z() + n[2]))) { - distance.put(v, 1); - queue.add(v); - break; - } - } - } - - while (!queue.isEmpty()) { - TreeBlockCanvas.Vec v = queue.poll(); - int d = distance.get(v); - if (d >= MAX_DISTANCE) { - continue; - } - for (int[] n : NEIGHBORS) { - TreeBlockCanvas.Vec nv = new TreeBlockCanvas.Vec(v.x() + n[0], v.y() + n[1], v.z() + n[2]); - if (!realLeaves.contains(nv)) { - continue; - } - Integer existing = distance.get(nv); - if (existing == null || existing > d + 1) { - distance.put(nv, d + 1); - queue.add(nv); - } - } - } - - return distance; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java deleted file mode 100644 index f5ece60ca..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeProfiles.java +++ /dev/null @@ -1,80 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeProfile; - - -public final class TreeProfiles { - private TreeProfiles() { - } - - static double radiusScale(TreeProfile profile) { - return switch (profile) { - case OAK, DARK_OAK, CHERRY -> 1.0; - case BIRCH -> 0.7; - case SPRUCE -> 0.55; - case JUNGLE -> 0.45; - case ACACIA -> 0.6; - case DARK_OAK_FLAT -> 1.25; - case DARK_OAK_FLAT_WIDE -> 1.8; - case PALM -> 0.5; - case WILLOW -> 1.1; - case COLUMNAR -> 0.35; - case BUSH -> 1.3; - case MEGA_SPRUCE -> 0.7; - }; - } - - static double[][] fractions(TreeProfile profile) { - return switch (profile) { - case OAK -> new double[][]{{0.55, 0.6}, {0.65, 0.9}, {0.75, 1.0}, {0.85, 0.9}, {0.92, 0.65}, {0.98, 0.35}}; - case BIRCH -> new double[][]{{0.6, 0.45}, {0.7, 0.75}, {0.8, 0.85}, {0.88, 0.75}, {0.94, 0.45}, {0.99, 0.2}}; - case SPRUCE, MEGA_SPRUCE -> new double[][]{{0.3, 1.0}, {0.42, 0.85}, {0.54, 0.7}, {0.65, 0.55}, {0.75, 0.4}, {0.84, 0.25}, {0.91, 0.15}, {0.97, 0.05}}; - case JUNGLE -> new double[][]{{0.82, 0.4}, {0.88, 0.8}, {0.93, 1.0}, {0.97, 0.7}, {1.0, 0.3}}; - case ACACIA -> new double[][]{{0.9, 0.5}, {0.95, 0.8}, {0.99, 0.4}}; - case DARK_OAK -> new double[][]{{0.5, 0.7}, {0.62, 1.0}, {0.72, 1.0}, {0.82, 0.9}, {0.91, 0.6}, {0.97, 0.3}}; - case DARK_OAK_FLAT -> new double[][]{{0.74, 0.62}, {0.83, 1.0}, {0.92, 1.0}, {1.0, 0.6}}; - case DARK_OAK_FLAT_WIDE -> new double[][]{{0.74, 0.62}, {0.83, 1.0}, {0.92, 1.0}, {1.0, 0.62}}; - case CHERRY -> new double[][]{{0.5, 0.5}, {0.62, 0.9}, {0.74, 1.0}, {0.84, 1.0}, {0.92, 0.7}, {0.98, 0.4}}; - case PALM -> new double[][]{{0.92, 0.45}, {0.97, 0.9}, {1.0, 1.0}, {1.03, 0.6}}; - case WILLOW -> new double[][]{{0.55, 0.7}, {0.68, 1.0}, {0.8, 1.0}, {0.9, 0.85}, {0.97, 0.6}}; - case COLUMNAR -> new double[][]{{0.4, 0.6}, {0.55, 0.9}, {0.7, 1.0}, {0.82, 0.9}, {0.92, 0.7}, {0.98, 0.4}}; - case BUSH -> new double[][]{{0.25, 0.7}, {0.45, 1.0}, {0.65, 1.0}, {0.82, 0.8}, {0.95, 0.5}}; - }; - } - - static double[][] presetLayers(TreeProfile profile, int height, boolean branchDriven) { - double scale = radiusScale(profile); - int baseRadius = Math.max(3, (int) Math.round(height / 2.0 * scale)); - double[][] fractions = fractions(profile); - - int crownExtra = branchDriven ? 0 : Math.max(2, height / 4); - int yTop = (height - 1) + crownExtra; - - double[][] layers = new double[fractions.length][2]; - for (int i = 0; i < fractions.length; i++) { - int yOff = (int) Math.round(fractions[i][0] * yTop); - double radius = Math.max(1.5, baseRadius * fractions[i][1]); - layers[i][0] = yOff; - layers[i][1] = radius; - } - return layers; - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java deleted file mode 100644 index 7ae8c976f..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeRootBuilder.java +++ /dev/null @@ -1,154 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeRootStyle; -import art.arcane.iris.modules.objects.tree.Tree; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayList; -import java.util.List; - -public final class TreeRootBuilder { - private TreeRootBuilder() { - } - - public static void build(TreeBlockCanvas canvas, Tree tree, int height, long baseSeed) { - List cells = new ArrayList<>(); - for (TreeBlockCanvas.Vec v : canvas.getTrunk()) { - if (v.y() == 0) { - cells.add(new int[]{v.x(), v.z()}); - } - } - if (cells.isEmpty()) { - return; - } - - int depth = tree.rootDepth() > 0 ? tree.rootDepth() : autoDepth(height); - RNG rng = new RNG(baseSeed ^ 0x5009L); - - double cx = 0; - double cz = 0; - for (int[] c : cells) { - cx += c[0]; - cz += c[1]; - } - cx /= cells.size(); - cz /= cells.size(); - - double baseRadius = 1.0; - for (int[] c : cells) { - baseRadius = Math.max(baseRadius, Math.hypot(c[0] - cx, c[1] - cz) + 0.5); - } - double flare = tree.rootFlare() > 0 ? tree.rootFlare() : baseRadius + Math.max(2.0, depth * 0.6); - - TreeRootStyle style = tree.rootStyle(); - switch (style) { - case TAPROOT -> taproot(canvas, cells, cx, cz, baseRadius, depth); - case BUTTRESS -> { - taproot(canvas, cells, cx, cz, baseRadius, depth); - buttress(canvas, cells, cx, cz, baseRadius, depth, flare, rng); - } - case STILT -> { - taproot(canvas, cells, cx, cz, baseRadius, Math.min(depth, 3)); - stilts(canvas, cx, cz, baseRadius, flare, height, cells.size(), rng); - } - } - } - - private static void taproot(TreeBlockCanvas canvas, List cells, double cx, double cz, double baseRadius, int depth) { - int icx = (int) Math.round(cx); - int icz = (int) Math.round(cz); - for (int k = 1; k <= depth; k++) { - double frac = k / (double) depth; - double keepR = baseRadius * (1.0 - 0.6 * frac); - for (int[] c : cells) { - if (Math.hypot(c[0] - cx, c[1] - cz) <= keepR + 1e-6) { - placeRoot(canvas, c[0], -k, c[1], TreeBlockCanvas.Axis.Y); - } - } - placeRoot(canvas, icx, -k, icz, TreeBlockCanvas.Axis.Y); - } - } - - private static void buttress(TreeBlockCanvas canvas, List cells, double cx, double cz, double baseRadius, - int depth, double flare, RNG rng) { - int nLegs = Math.max(4, Math.min(12, cells.size() + 2)); - for (int li = 0; li < nLegs; li++) { - double ang = 2.0 * Math.PI * li / nLegs + rng.d(-0.25, 0.25); - double ca = Math.cos(ang); - double sa = Math.sin(ang); - int prevX = (int) Math.round(cx + baseRadius * ca); - int prevZ = (int) Math.round(cz + baseRadius * sa); - for (int k = 1; k <= depth; k++) { - double frac = k / (double) depth; - double r = baseRadius + (flare - baseRadius) * frac; - int x = (int) Math.round(cx + r * ca); - int z = (int) Math.round(cz + r * sa); - placeRoot(canvas, x, -k, z, TreeBlockCanvas.Axis.Y); - if (x != prevX || z != prevZ) { - placeRoot(canvas, prevX, -k, prevZ, TreeBlockCanvas.Axis.Y); - } - prevX = x; - prevZ = z; - } - } - } - - private static void stilts(TreeBlockCanvas canvas, double cx, double cz, double baseRadius, double flare, - int height, int cellCount, RNG rng) { - int stiltTop = Math.max(2, Math.min(7, (int) Math.round(0.25 * height))); - int nProps = Math.max(4, Math.min(10, cellCount + 2)); - for (int p = 0; p < nProps; p++) { - double ang = 2.0 * Math.PI * p / nProps + rng.d(-0.25, 0.25); - double ca = Math.cos(ang); - double sa = Math.sin(ang); - int sx = (int) Math.round(cx + baseRadius * ca); - int sz = (int) Math.round(cz + baseRadius * sa); - int fx = (int) Math.round(cx + flare * ca); - int fz = (int) Math.round(cz + flare * sa); - rasterizeRoot(canvas, sx, stiltTop, sz, fx, -2, fz); - } - } - - private static void rasterizeRoot(TreeBlockCanvas canvas, int ox, int oy, int oz, int ex, int ey, int ez) { - int dx = ex - ox; - int dy = ey - oy; - int dz = ez - oz; - int steps = Math.max(Math.max(Math.abs(dx), Math.abs(dy)), Math.max(Math.abs(dz), 1)); - TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(dx, dy, dz); - for (int i = 0; i <= steps; i++) { - double t = i / (double) steps; - int x = (int) Math.round(ox + dx * t); - int y = (int) Math.round(oy + dy * t); - int z = (int) Math.round(oz + dz * t); - placeRoot(canvas, x, y, z, axis); - } - } - - private static void placeRoot(TreeBlockCanvas canvas, int x, int y, int z, TreeBlockCanvas.Axis axis) { - if (!canvas.has(x, y, z)) { - canvas.setTrunk(x, y, z, TreeBlockCanvas.Role.TRUNK, axis); - } - } - - private static int autoDepth(int height) { - return Math.max(2, Math.min(16, (int) Math.round(0.18 * height))); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.java deleted file mode 100644 index c6ef85c91..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeSupport.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.procedural.tree; - -import java.util.ArrayList; -import java.util.Map; - -public final class TreeSupport { - private static final int LEGAL_DISTANCE = 6; - private static final int REACH_GAP = 4; - - private TreeSupport() { - } - - public static void ensureLeavesSupported(TreeBlockCanvas canvas, int maxTendrils) { - for (int iter = 0; iter < maxTendrils; iter++) { - Map dist = TreePlausibility.computeDistances(canvas.getTrunk(), canvas.getLeaf()); - - TreeBlockCanvas.Vec worstLeaf = null; - TreeBlockCanvas.Vec worstWood = null; - int worstGap = -1; - - for (TreeBlockCanvas.Vec leaf : new ArrayList<>(canvas.getLeaf())) { - Integer d = dist.get(leaf); - if (d != null && d <= LEGAL_DISTANCE) { - continue; - } - TreeBlockCanvas.Vec nearest = null; - int best = Integer.MAX_VALUE; - for (TreeBlockCanvas.Vec wood : canvas.getTrunk()) { - int cd = chebyshev(leaf, wood); - if (cd < best) { - best = cd; - nearest = wood; - if (cd <= 1) { - break; - } - } - } - if (nearest != null && best > worstGap) { - worstGap = best; - worstLeaf = leaf; - worstWood = nearest; - } - } - - if (worstLeaf == null) { - return; - } - growTendril(canvas, worstWood, worstLeaf); - } - } - - private static void growTendril(TreeBlockCanvas canvas, TreeBlockCanvas.Vec from, TreeBlockCanvas.Vec to) { - int dx = to.x() - from.x(); - int dy = to.y() - from.y(); - int dz = to.z() - from.z(); - int length = Math.max(Math.max(Math.abs(dx), Math.abs(dy)), Math.max(Math.abs(dz), 1)); - int steps = Math.max(1, length - REACH_GAP); - TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(dx, dy, dz); - - for (int i = 1; i <= steps; i++) { - double t = i / (double) length; - int x = from.x() + (int) Math.round(dx * t); - int y = from.y() + (int) Math.round(dy * t); - int z = from.z() + (int) Math.round(dz * t); - canvas.setTrunk(x, y, z, TreeBlockCanvas.Role.TRUNK, axis); - } - } - - private static int chebyshev(TreeBlockCanvas.Vec a, TreeBlockCanvas.Vec b) { - return Math.max(Math.max(Math.abs(a.x() - b.x()), Math.abs(a.y() - b.y())), Math.abs(a.z() - b.z())); - } -} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java b/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java deleted file mode 100644 index b66b10e5a..000000000 --- a/src/main/java/art/arcane/iris/engine/object/procedural/tree/TreeTrunkBuilder.java +++ /dev/null @@ -1,202 +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.procedural.tree; - -import art.arcane.iris.modules.objects.tree.TreeAzimuthMode; -import art.arcane.iris.engine.object.procedural.IrisProceduralBlocks; -import art.arcane.iris.modules.objects.tree.Tree; - -import java.util.ArrayList; -import java.util.List; - -public final class TreeTrunkBuilder { - public record Limb(double[][] offsets, int branchStartY) { - } - - private TreeTrunkBuilder() { - } - - public static List build(TreeBlockCanvas canvas, Tree tree, int height) { - boolean hasSecondary = hasSecondaryTrunk(tree); - double[][] mainOffsets = leanPath(tree, height); - int forks = Math.max(1, tree.trunkForks()); - - List limbs = new ArrayList<>(); - if (forks == 1) { - placeColumn(canvas, tree, mainOffsets, height, 0, height - 1, hasSecondary); - limbs.add(new Limb(mainOffsets, 0)); - markExposedEnds(canvas); - return limbs; - } - - int forkY = Math.max(1, Math.min(height - 2, (int) Math.round(tree.forkHeight() * (height - 1)))); - placeColumn(canvas, tree, mainOffsets, height, 0, forkY, hasSecondary); - - double baseCx = mainOffsets[forkY][0]; - double baseCz = mainOffsets[forkY][1]; - double reachMax = (height - forkY) * Math.tan(Math.toRadians(tree.forkAngle())); - - for (int f = 0; f < forks; f++) { - double az = Math.toRadians((360.0 / forks) * f); - double[][] forkOffsets = new double[height][2]; - for (int y = 0; y <= forkY; y++) { - forkOffsets[y][0] = mainOffsets[y][0]; - forkOffsets[y][1] = mainOffsets[y][1]; - } - for (int y = forkY + 1; y < height; y++) { - double p = (y - forkY) / (double) Math.max(1, height - 1 - forkY); - double reach = reachMax * p; - forkOffsets[y][0] = baseCx + reach * Math.sin(az); - forkOffsets[y][1] = baseCz + reach * Math.cos(az); - } - placeColumn(canvas, tree, forkOffsets, height, forkY + 1, height - 1, hasSecondary); - limbs.add(new Limb(forkOffsets, forkY)); - } - - markExposedEnds(canvas); - return limbs; - } - - private static double[][] leanPath(Tree tree, int height) { - double[][] offsets = new double[height][2]; - for (int y = 0; y < height; y++) { - double[] lean = leanOffset(tree, y, height); - offsets[y][0] = lean[0]; - offsets[y][1] = lean[1]; - } - return offsets; - } - - private static void placeColumn(TreeBlockCanvas canvas, Tree tree, double[][] offsets, int height, - int yStart, int yEnd, boolean hasSecondary) { - double prevCx = yStart > 0 ? offsets[yStart - 1][0] : 0.0; - double prevCz = yStart > 0 ? offsets[yStart - 1][1] : 0.0; - - for (int y = yStart; y <= yEnd; y++) { - double cx = offsets[y][0]; - double cz = offsets[y][1]; - int w = widthAt(tree, y, height); - TreeBlockCanvas.Axis axis = TreeFunctions.logAxis(cx - prevCx, 1.0, cz - prevCz); - TreeBlockCanvas.Role role = trunkRole(tree, hasSecondary, y, height); - - for (int[] xz : squarePositions(cx, cz, w)) { - canvas.setTrunk(xz[0], y, xz[1], role, axis); - } - - double shift = Math.hypot(cx - prevCx, cz - prevCz); - if (shift > 1.0) { - int steps = (int) Math.ceil(shift); - for (int s = 1; s < steps; s++) { - double tFill = s / (double) steps; - double icx = prevCx + (cx - prevCx) * tFill; - double icz = prevCz + (cz - prevCz) * tFill; - int fillY = (int) Math.round(y - 1 + tFill); - for (int[] xz : squarePositions(icx, icz, w)) { - if (!canvas.has(xz[0], fillY, xz[1])) { - canvas.setTrunk(xz[0], fillY, xz[1], role, axis); - } - } - } - } - - prevCx = cx; - prevCz = cz; - } - } - - private static void markExposedEnds(TreeBlockCanvas canvas) { - for (TreeBlockCanvas.Vec v : new ArrayList<>(canvas.getTrunk())) { - if (!canvas.has(v.x(), v.y() + 1, v.z()) || !canvas.has(v.x(), v.y() - 1, v.z())) { - canvas.markExposed(v.x(), v.y(), v.z()); - } - } - } - - private static int widthAt(Tree tree, int y, int height) { - double t = y / (double) Math.max(height - 1, 1); - double multiplier = TreeFunctions.trunkWidthMultiplier(tree, t); - return Math.max(1, (int) Math.round(tree.trunkWidth() * multiplier)); - } - - private static TreeBlockCanvas.Role trunkRole(Tree tree, boolean hasSecondary, int y, int height) { - if (!hasSecondary) { - return TreeBlockCanvas.Role.TRUNK; - } - double t = y / (double) Math.max(height - 1, 1); - if (tree.secondaryTrunkStart() <= t && t <= tree.secondaryTrunkEnd()) { - return TreeBlockCanvas.Role.SECONDARY_TRUNK; - } - return TreeBlockCanvas.Role.TRUNK; - } - - private static boolean hasSecondaryTrunk(Tree tree) { - if (IrisProceduralBlocks.paletteSet(tree.secondaryTrunkPalette())) { - return true; - } - return tree.secondaryTrunk().filter(trunk -> !trunk.isEmpty()).isPresent(); - } - - private static double[] leanOffset(Tree tree, int y, int height) { - if (tree.leanAngle() == 0.0 || height <= 1) { - return new double[]{0.0, 0.0}; - } - double t = y / (double) Math.max(height - 1, 1); - double progress = TreeFunctions.curveProgress(tree.trunkCurve(), t, tree.curveSteepness()); - double maxReach = height * Math.tan(Math.toRadians(tree.leanAngle())); - double reach = maxReach * progress; - double azDeg = tree.leanAzimuthMode() == TreeAzimuthMode.CONSTANT - ? tree.leanAzimuth() - : TreeFunctions.azimuthDegrees(tree.leanAzimuthMode(), t, -1, tree, tree.leanAzimuth(), null); - double azRad = Math.toRadians(azDeg); - double dx = reach * Math.sin(azRad); - double dz = reach * Math.cos(azRad); - return new double[]{dx, dz}; - } - - private static List squarePositions(double cx, double cz, int width) { - List out = new ArrayList<>(); - if (width % 2 == 1) { - int half = width / 2; - int icx = (int) Math.round(cx); - int icz = (int) Math.round(cz); - for (int dx = -half; dx <= half; dx++) { - for (int dz = -half; dz <= half; dz++) { - out.add(new int[]{icx + dx, icz + dz}); - } - } - } else { - int ox = (int) Math.floor(cx) - width / 2 + 1; - int oz = (int) Math.floor(cz) - width / 2 + 1; - for (int dx = 0; dx < width; dx++) { - for (int dz = 0; dz < width; dz++) { - out.add(new int[]{ox + dx, oz + dz}); - } - } - } - return out; - } - - static String stripState(String block) { - if (block == null) { - return null; - } - int idx = block.indexOf('['); - return idx < 0 ? block : block.substring(0, idx); - } -} diff --git a/src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java b/src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java new file mode 100644 index 000000000..75e37ba1c --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/BakeProfile.java @@ -0,0 +1,85 @@ +/* + * 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.procedural; + +/** + * How long baking a pool of variants took, stage by stage, added up over every variant. {@link #NONE} times nothing, + * so world generation bakes at full speed. + */ +public class BakeProfile { + public static final BakeProfile NONE = new BakeProfile() { + @Override + public void startVariant() { + } + + @Override + public void lap(Stage stage) { + } + }; + + /** The steps a variant is baked in, in order. */ + public enum Stage { + PARTS("Parts"), + PAINT("Paint"), + DECORATE("Decorate"), + LEAVES("Leaves"), + BUILD("Build"); + + private final String label; + + Stage(String label) { + this.label = label; + } + + public String label() { + return label; + } + } + + private final long[] nanosByStage = new long[Stage.values().length]; + private long lapStartNanos; + private int variantCount; + + public void startVariant() { + variantCount++; + lapStartNanos = System.nanoTime(); + } + + /** Adds the time since the variant started, or since the last lap, to {@code stage}. */ + public void lap(Stage stage) { + long now = System.nanoTime(); + nanosByStage[stage.ordinal()] += now - lapStartNanos; + lapStartNanos = now; + } + + public long nanos(Stage stage) { + return nanosByStage[stage.ordinal()]; + } + + public long totalNanos() { + long total = 0L; + for (long nanos : nanosByStage) { + total += nanos; + } + return total; + } + + public int variantCount() { + return variantCount; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java b/src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java new file mode 100644 index 000000000..8328b8d65 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/IrisProceduralBlocks.java @@ -0,0 +1,100 @@ +/* + * 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.procedural; + +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; +import com.volmit.block.PaletteSpec; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.ObjectBlock; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * Block helpers for baking procedural objects: reading a state's properties, and assembling a raw block map into a + * shape centered on x and z with its lowest layer one block above the anchor. + */ +public final class IrisProceduralBlocks { + /** The distance vanilla gives a leaf with no wood near enough to keep it. */ + public static final int UNREACHED_LEAF_DISTANCE = 7; + + private IrisProceduralBlocks() { + } + + /** Whether {@code state} is a leaf baked with no wood near enough for vanilla to keep it. */ + public static boolean isLeafTooFarFromWood(BlockState state) { + return hasProperty(state, "persistent") && String.valueOf(UNREACHED_LEAF_DISTANCE).equals(propertyValue(state, "distance")); + } + + public static boolean paletteSet(PaletteSpec palette) { + return palette != null && !palette.palette().isEmpty(); + } + + public static boolean hasProperty(BlockState state, String property) { + return state.properties().containsKey(property); + } + + public static String propertyValue(BlockState state, String property) { + return state.properties().get(property); + } + + /** The blocks centered on x and z, with their lowest layer one block above the anchor; null when there are none. */ + public static ProceduralShape assemble(Map blocks) { + if (blocks == null || blocks.isEmpty()) { + return null; + } + + Anchor anchor = Anchor.of(blocks.keySet()); + List placed = new ArrayList<>(blocks.size()); + for (Map.Entry entry : blocks.entrySet()) { + placed.add(new ObjectBlock(anchor.place(entry.getKey()), entry.getValue())); + } + + return new ProceduralShape(anchor.width(), anchor.height(), anchor.depth(), placed); + } + + /** Where {@link #assemble} moves each block of a set: centered on x and z, its lowest layer one block above the anchor. */ + public record Anchor(int minX, int minZ, int width, int height, int depth) { + public static Anchor of(Collection positions) { + 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 (Vector3i v : positions) { + minX = Math.min(minX, v.getBlockX()); + minY = Math.min(minY, v.getBlockY()); + minZ = Math.min(minZ, v.getBlockZ()); + maxX = Math.max(maxX, v.getBlockX()); + maxY = Math.max(maxY, v.getBlockY()); + maxZ = Math.max(maxZ, v.getBlockZ()); + } + return new Anchor(minX, minZ, maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1); + } + + public BlockPosition place(Vector3i position) { + return new BlockPosition(position.getBlockX() - minX - width / 2, position.getBlockY() - height / 2 + 1, + position.getBlockZ() - minZ - depth / 2); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java b/src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java new file mode 100644 index 000000000..6cd8dd9a2 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/ProceduralObjectCatalog.java @@ -0,0 +1,142 @@ +/* + * 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.procedural; + +import art.arcane.iris.engine.procedural.part.ProceduralObject; +import art.arcane.iris.engine.procedural.part.ResolvedProceduralObject; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The pack's procedural objects, each read from {@code procedural/.json} and placed from any object placement + * as {@code procedural/}, or one variant as {@code procedural/#}. Variants are baked on first use. + */ +public final class ProceduralObjectCatalog { + /** The definitions, in {@code procedural/}; a placement's key for one is its file path, like {@code procedural/trees/oak}. */ + public static final ResourceKind DEFINITIONS = + ResourceKind.of("iris:objects/procedural", "procedural", ProceduralObject.class); + public static final String KEY_PREFIX = DEFINITIONS.folder() + "/"; + public static final char VARIANT_SEPARATOR = '#'; + + private final PackResources resources; + private final ModuleLog log; + private final Map> variantsByPath = new ConcurrentHashMap<>(); + + private ProceduralObjectCatalog(PackResources resources, ModuleLog log) { + this.resources = resources; + this.log = log; + } + + /** The catalog {@code world} keeps, so each definition bakes once per world. */ + public static ProceduralObjectCatalog of(PackWorld world) { + return world.state(ProceduralObjectCatalog.class, generating -> new ProceduralObjectCatalog(generating.resources(), generating.log())); + } + + /** A catalog of its own, for work outside any world such as working out the pack's reach; it bakes anew. */ + public static ProceduralObjectCatalog detached(PackResources resources, ModuleLog log) { + return new ProceduralObjectCatalog(resources, log); + } + + /** Whether {@code key} names a procedural object rather than a pack object. */ + public static boolean isProceduralKey(String key) { + return key != null && key.startsWith(KEY_PREFIX); + } + + /** The variant {@code key} pins, or for a key naming the whole pool the one {@code rng} picks; empty when none. */ + public Optional object(String key, RNG rng) { + ObjectKey parsed = ObjectKey.parse(key); + return variantsNamedBy(parsed).flatMap(variants -> parsed.isPinned() ? variants.variant(parsed.variantIndex()) : variants.variant(rng)); + } + + /** + * The variant {@code key} pins, or for a key naming the whole pool its first variant, so a caller without a random + * stream still gets the same object every time; empty when none. + */ + public Optional object(String key) { + ObjectKey parsed = ObjectKey.parse(key); + return variantsNamedBy(parsed).flatMap(variants -> parsed.isPinned() + ? variants.variant(parsed.variantIndex()) + : variants.variants().stream().findFirst()); + } + + /** The variants {@code key} names, pinned to one or not; empty when the pack has no such object. */ + public Optional variants(String key) { + return variantsNamedBy(ObjectKey.parse(key)); + } + + /** Every variant {@code key} may place: the one it pins, or the whole pool. */ + public List placeable(String key) { + ObjectKey parsed = ObjectKey.parse(key); + return variantsNamedBy(parsed).map(variants -> parsed.isPinned() + ? variants.variant(parsed.variantIndex()).stream().toList() + : variants.variants()).orElse(List.of()); + } + + private Optional variantsNamedBy(ObjectKey key) { + return variantsByPath.computeIfAbsent(key.path(), this::resolve); + } + + private Optional resolve(String path) { + ResourceId id = resources.idOf(path); + Optional definition; + try { + definition = resources.find(DEFINITIONS, id); + } catch (IllegalStateException failedToLoad) { + log.warnOnce("procedural-unreadable:" + path, "Couldn't read procedural object " + KEY_PREFIX + path + ": " + failedToLoad.getMessage()); + return Optional.empty(); + } + if (definition.isEmpty()) { + log.warnOnce("procedural-missing:" + path, "Couldn't find procedural object " + KEY_PREFIX + path); + return Optional.empty(); + } + return Optional.of(new ResolvedProceduralObject(path, definition.get(), resources)); + } + + /** A procedural object key split into the definition's path and, when it pins one, a variant index. */ + private record ObjectKey(String path, int variantIndex) { + private static final int UNPINNED = -1; + + static ObjectKey parse(String key) { + String path = key.substring(KEY_PREFIX.length()); + int separator = path.lastIndexOf(VARIANT_SEPARATOR); + if (separator < 0) { + return new ObjectKey(path, UNPINNED); + } + try { + return new ObjectKey(path.substring(0, separator), Integer.parseInt(path.substring(separator + 1))); + } catch (NumberFormatException notAnIndex) { + return new ObjectKey(path, UNPINNED); + } + } + + boolean isPinned() { + return variantIndex != UNPINNED; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java b/src/main/java/art/arcane/iris/engine/procedural/ProceduralShape.java similarity index 95% rename from src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java rename to src/main/java/art/arcane/iris/engine/procedural/ProceduralShape.java index 4443833b8..65876b4bf 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/ProceduralShape.java +++ b/src/main/java/art/arcane/iris/engine/procedural/ProceduralShape.java @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package art.arcane.iris.engine.object.procedural; +package art.arcane.iris.engine.procedural; import com.volmit.object.ObjectBlock; diff --git a/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java b/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java new file mode 100644 index 000000000..044833df0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java @@ -0,0 +1,152 @@ +/* + * 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.procedural; + +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.iris.modules.objects.ObjectSize; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The pool of variants one procedural definition bakes, placed through the object key {@code procedural/}: a + * placement picks one variant per object it places, or always the same one with {@code procedural/#}. + */ +public abstract class ProceduralVariants { + private static final long VARIANT_SEED_STRIDE = 7919L; + + private final String path; + private final long seed; + private final int variantCount; + private final PackResources resources; + private volatile List baked; + + protected ProceduralVariants(String path, long seed, int variantCount, PackResources resources) { + this.path = path; + this.seed = seed; + this.variantCount = Math.max(1, variantCount); + this.resources = resources; + } + + /** The shape variant {@code index} is baked as, from its own seeded stream; null when it has no blocks. */ + protected abstract ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks, BakeProfile profile); + + /** Where the pack keeps the definition, under {@code procedural/}, like {@code trees/oak}. */ + public String path() { + return path; + } + + /** The key placements name the whole pool by, like {@code procedural/trees/oak}. */ + public String key() { + return ProceduralObjectCatalog.KEY_PREFIX + path; + } + + /** The key variant {@code index} is placed under, like {@code procedural/trees/oak#0}. */ + public String variantKey(int index) { + return key() + ProceduralObjectCatalog.VARIANT_SEPARATOR + index; + } + + /** Every variant, baked on first use. */ + public List variants() { + List known = baked; + if (known != null) { + return known; + } + synchronized (this) { + if (baked == null) { + baked = List.copyOf(bake(newBuilder(), BakeProfile.NONE)); + } + return baked; + } + } + + /** Bakes every variant again the way world generation does, without keeping them, and times each stage. */ + public BakeProfile profileBake() { + BakeProfile profile = new BakeProfile(); + bake(newBuilder(), profile); + return profile; + } + + /** One of the variants, picked with {@code rng}; empty when none baked. */ + public Optional variant(RNG rng) { + List all = variants(); + return all.isEmpty() ? Optional.empty() : Optional.of(all.get(rng.i(all.size()))); + } + + /** The variant baked at {@code index}; empty when it baked no blocks or the definition asks for fewer. */ + public Optional variant(int index) { + String key = variantKey(index); + return variants().stream().filter(variant -> variant.name().equals(key)).findFirst(); + } + + /** The widest, tallest and deepest any variant reaches, each measured on its own. */ + public ObjectSize largestSize() { + int width = 0; + int height = 0; + int depth = 0; + for (PlaceableObject variant : variants()) { + width = Math.max(width, variant.width()); + height = Math.max(height, variant.height()); + depth = Math.max(depth, variant.depth()); + } + return new ObjectSize(width, height, depth); + } + + /** Bakes every variant; variant {@code i} is drawn from {@code seed + i * stride}. */ + private List bake(ObjectBuilder blocks, BakeProfile profile) { + List all = new ArrayList<>(); + for (int i = 0; i < variantCount; i++) { + profile.startVariant(); + ProceduralShape generated = generate(i, variantRng(i), blocks, profile); + if (generated == null || generated.blocks().isEmpty()) { + continue; + } + all.add(blocks.build(variantKey(i), generated.width(), generated.height(), generated.depth(), generated.blocks())); + profile.lap(BakeProfile.Stage.BUILD); + } + return all; + } + + protected final RNG variantRng(int index) { + return new RNG(seed + (index * VARIANT_SEED_STRIDE)); + } + + /** The index {@code variant} was baked at; -1 when it is not one of these variants. */ + protected final int bakeIndexOf(PlaceableObject variant) { + for (int index = 0; index < variantCount; index++) { + if (variantKey(index).equals(variant.name())) { + return index; + } + } + return -1; + } + + protected final ObjectBuilder newBuilder() { + return new ObjectBuilder(resources); + } + + /** The seed every variant is baked from. */ + public final long seed() { + return seed; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java b/src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java new file mode 100644 index 000000000..106884a81 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/BlobShape.java @@ -0,0 +1,160 @@ +/* + * 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.procedural.part; + +import art.arcane.volmlib.util.math.RNG; + +/** + * A blob: a volume around a center whose horizontal cross-section is scaled by a profile from its bottom to its top, + * an ellipsoid unless the pack shapes it, optionally hollowed into a shell. + */ +final class BlobShape implements PartShape { + private static final double LARGEST_RADIUS_BLOCKS = 96; + private static final double MINIMUM_RADIUS_BLOCKS = 0.05; + private static final int[][] SHELL_DIRECTIONS = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, 1, 0}, {0, -1, 0}}; + private static final int[][] OPEN_SHELL_DIRECTIONS = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, 1, 0}}; + + private final double[] center; + private final double radiusX; + private final double radiusZ; + private final double up; + private final double down; + private final ProceduralValue profile; + private final PartSection section; + private final double shell; + private final boolean open; + private final double outward; + + private BlobShape(double[] center, double radiusX, double radiusZ, double up, double down, ProceduralValue profile, + PartSection section, double shell, boolean open, double outward) { + this.center = center; + this.radiusX = radiusX; + this.radiusZ = radiusZ; + this.up = up; + this.down = down; + this.profile = profile; + this.section = section; + this.shell = shell; + this.open = open; + this.outward = outward; + } + + static BlobShape trace(PartBlob blob, PartSpot spot, RNG rng) { + double t = spot.parentT(); + double radius = clampRadius(blob.radius().sample(rng, t)); + double up = blob.height() == null ? radius : clampRadius(blob.height().sample(rng, t)); + double down = blob.depth() == null ? up : Math.max(0, Math.min(LARGEST_RADIUS_BLOCKS, blob.depth().sample(rng, t))); + double shell = Math.max(0, blob.shell().sample(rng, t)); + double outward = spot.hasOutward() ? spot.outward() : rng.d(0, 360); + return new BlobShape(spot.origin(), Math.max(MINIMUM_RADIUS_BLOCKS, radius * blob.stretchX()), + Math.max(MINIMUM_RADIUS_BLOCKS, radius * blob.stretchZ()), up, down, + blob.profile() == null ? null : blob.profile().fix(rng), blob.section(), shell, blob.open(), outward); + } + + void draw(PartFill fill, double roughness, double jitter) { + int reachX = (int) Math.ceil(radiusX * (1 + roughness) + 1); + int reachZ = (int) Math.ceil(radiusZ * (1 + roughness) + 1); + int cx = (int) Math.round(center[0]); + int cy = (int) Math.round(center[1]); + int cz = (int) Math.round(center[2]); + for (int y = cy - (int) Math.ceil(down) - 1; y <= cy + (int) Math.ceil(up) + 1; y++) { + for (int x = cx - reachX; x <= cx + reachX; x++) { + for (int z = cz - reachZ; z <= cz + reachZ; z++) { + drawBlock(fill, x, y, z, roughness, jitter); + } + } + } + } + + private void drawBlock(PartFill fill, int x, int y, int z, double roughness, double jitter) { + if (!inside(x, y, z, roughness, fill.seed())) { + return; + } + if (shell > 0 && !nearSurface(x, y, z, roughness, fill.seed())) { + return; + } + double dx = x - center[0]; + double dy = y - center[1]; + double dz = z - center[2]; + double edge = edge(dx, dy, dz); + if (jitter > 0 && edge > 1 - 1 / (Math.max(radiusX, radiusZ) + 1) && PartNoise.hash(x, y, z, fill.seed() + 77L) < jitter * 0.35) { + return; + } + double height = (dy + down + 0.5) / (up + down + 1); + double falloffEdge = Math.sqrt(sq(dx / (radiusX + 1)) + sq(dy / ((dy >= 0 ? up : down) + 1)) + sq(dz / (radiusZ + 1))); + fill.place(x, y, z, falloffEdge, height, PartCanvas.Axis.Y); + } + + private boolean inside(int x, int y, int z, double roughness, long seed) { + double wobble = roughness <= 0 ? 0 : (PartNoise.hash(x, y, z, seed + 4201L) - 0.5) * roughness * 1.2; + return edge(x - center[0], y - center[1], z - center[2]) <= 1 + wobble; + } + + /** Whether the outside lies within the shell's thickness, looking up and sideways, and down unless the shell is open. */ + private boolean nearSurface(int x, int y, int z, double roughness, long seed) { + int thickness = Math.max(1, (int) Math.round(shell)); + int[][] directions = open ? OPEN_SHELL_DIRECTIONS : SHELL_DIRECTIONS; + for (int step = 1; step <= thickness; step++) { + for (int[] direction : directions) { + if (!inside(x + direction[0] * step, y + direction[1] * step, z + direction[2] * step, roughness, seed)) { + return true; + } + } + } + return false; + } + + /** How far out a point is, where 1 is the surface; above 1 is outside. */ + private double edge(double dx, double dy, double dz) { + double vertical = dy >= 0 ? dy / (up + 0.5) : dy / (down + 0.5); + if (Math.abs(vertical) > 1) { + return Double.MAX_VALUE; + } + double width = profile == null + ? Math.sqrt(1 - vertical * vertical) + : Math.max(0, profile.at((dy + down + 0.5) / (up + down + 1))); + if (width <= 0) { + return Double.MAX_VALUE; + } + return Sections.norm(section, dx / radiusX, dz / radiusZ) / width; + } + + @Override + public PartSpot spotAt(double t) { + double y = center[1] - down + Math.max(0, Math.min(1, t)) * (up + down); + return new PartSpot(new double[]{center[0], y, center[2]}, Vectors.UP.clone(), t, up + down + 1, outward); + } + + @Override + public double length() { + return up + down + 1; + } + + @Override + public double defaultAt() { + return 1; + } + + private static double clampRadius(double radius) { + return Math.max(0, Math.min(LARGEST_RADIUS_BLOCKS, radius)); + } + + private static double sq(double value) { + return value * value; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java b/src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java new file mode 100644 index 000000000..77b1704c9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/BlockChoice.java @@ -0,0 +1,45 @@ +/* + * 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.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import com.volmit.block.PaletteSpec; +import com.volmit.block.BlockState; + +/** A block or a noise palette to take one from, optionally banded by height for strata. */ +record BlockChoice(String block, PaletteSpec palette, int bands) { + /** The block at the position; null when neither block nor palette names one. */ + BlockState at(ObjectBuilder blocks, long seed, int x, int y, int z) { + if (IrisProceduralBlocks.paletteSet(palette)) { + if (bands > 0) { + int band = Math.floorDiv(y, bands); + return blocks.pick(palette, seed + band * 31L, x, band, z); + } + return blocks.pick(palette, seed, x, y, z); + } + if (block == null || block.isEmpty()) { + return null; + } + return blocks.block(block); + } + + boolean isSet() { + return IrisProceduralBlocks.paletteSet(palette) || (block != null && !block.isEmpty()); + } +} diff --git a/src/main/java/art/arcane/iris/modules/objects/coral/CoralBranchAzimuth.java b/src/main/java/art/arcane/iris/engine/procedural/part/BranchAzimuth.java similarity index 57% rename from src/main/java/art/arcane/iris/modules/objects/coral/CoralBranchAzimuth.java rename to src/main/java/art/arcane/iris/engine/procedural/part/BranchAzimuth.java index ec607d0d2..2342eaad0 100644 --- a/src/main/java/art/arcane/iris/modules/objects/coral/CoralBranchAzimuth.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/BranchAzimuth.java @@ -15,19 +15,22 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - -package art.arcane.iris.modules.objects.coral; +package art.arcane.iris.engine.procedural.part; import com.volmit.config.Desc; -@Desc("How the arms of a BRANCHING coral are distributed around the central stalk by compass azimuth.") -public enum CoralBranchAzimuth { - @Desc("Distribute arms by the golden angle (about 137.5 degrees per arm) for a natural phyllotactic spiral where no two arms overlap.") - GOLDEN_ANGLE, - - @Desc("Distribute arms in evenly spaced spokes, dividing 360 degrees equally between them like a radial whorl.") +@Desc("Which way around its parent each new branch points.") +public enum BranchAzimuth { + @Desc("Any direction.") + RANDOM, + @Desc("Each branch turns the golden angle (about 137.5 degrees) from the last, so none line up.") + GOLDEN, + @Desc("Each branch points opposite the last.") + ALTERNATE, + @Desc("Branches come in rings of 'whorl' evenly spaced branches.") + WHORL, + @Desc("All branches are spread evenly around the parent.") EVEN, - - @Desc("Place each arm at a fully random azimuth using the deterministic per-variant RNG, for an irregular wild reef.") - RANDOM + @Desc("Branches fan out side by side around the parent's own direction, 'fan' degrees apart.") + FAN } diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeRootStyle.java b/src/main/java/art/arcane/iris/engine/procedural/part/ClusterLayout.java similarity index 62% rename from src/main/java/art/arcane/iris/modules/objects/tree/TreeRootStyle.java rename to src/main/java/art/arcane/iris/engine/procedural/part/ClusterLayout.java index ff9afcae9..6f9d99d50 100644 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeRootStyle.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ClusterLayout.java @@ -15,17 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - -package art.arcane.iris.modules.objects.tree; +package art.arcane.iris.engine.procedural.part; import com.volmit.config.Desc; -@Desc("How a procedural tree's root system is built below (and around) the trunk base.") -public enum TreeRootStyle { - @Desc("A single tapering taproot straight down from the base.") - TAPROOT, - @Desc("A taproot plus a ring of flared buttress legs that splay outward as they descend (default).") - BUTTRESS, - @Desc("Visible above-ground prop roots that arch out and down from the lower trunk to the ground (mangrove style).") - STILT +@Desc("How the parts of a cluster are laid out around its center.") +public enum ClusterLayout { + @Desc("Anywhere inside the radius.") + RANDOM, + @Desc("Evenly spaced on a circle of the radius.") + RING, + @Desc("In a row across the radius.") + LINE, + @Desc("A sunflower spiral filling the radius evenly.") + GOLDEN } diff --git a/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecoratorTarget.java b/src/main/java/art/arcane/iris/engine/procedural/part/DecorationSpot.java similarity index 56% rename from src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecoratorTarget.java rename to src/main/java/art/arcane/iris/engine/procedural/part/DecorationSpot.java index 9f8021004..578d10932 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecoratorTarget.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/DecorationSpot.java @@ -15,17 +15,24 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - -package art.arcane.iris.modules.objects.ruin; +package art.arcane.iris.engine.procedural.part; import com.volmit.config.Desc; -@Desc("Where a ruin accent block is placed after the ruin has been built and eroded.") -public enum RuinDecoratorTarget { - @Desc("On top of the highest surviving block in each column (moss carpets, snow, sculk, lanterns on broken tops).") +@Desc("Where a decoration is placed on the object.") +public enum DecorationSpot { + @Desc("On every block that is open above.") + ABOVE, + @Desc("Under every block that is open below; set length for hanging strands.") + BELOW, + @Desc("Against every open horizontal side.") + SIDE, + @Desc("On the highest block of each column.") TOP, - @Desc("On air-facing vertical sides of any surviving block (vines, glow lichen, climbing growth on the ruin faces).") - SURFACE, - @Desc("Scattered across the ground footprint around the y=0 base ring, wider than the structure itself (loose rubble, mushrooms, grass tufts ringing the ruin).") - BASE_SCATTER + @Desc("Under the lowest block of each column; set length for hanging strands.") + BOTTOM, + @Desc("Just past the end of every stem.") + TIPS, + @Desc("On the ground around where the object stands, out to the radius.") + GROUND } diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java b/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java new file mode 100644 index 000000000..fc2b5210d --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java @@ -0,0 +1,271 @@ +/* + * 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.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockFace; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +/** + * Places decorations against the painted object. A decoration attaches to the block it rests on: vines and lichen + * grow toward it, directional blocks face away from it and lanterns hang under it. + */ +final class Decorator { + private static final long DECORATION_SEED_STRIDE = 911L; + private static final BlockFace[] SIDES = {BlockFace.EAST, BlockFace.WEST, BlockFace.SOUTH, BlockFace.NORTH}; + + private final PartCanvas canvas; + private final Map painted; + private final ObjectBuilder blocks; + private final long paletteSeed; + private final int groundY; + + /** @param groundY the lowest height above the terrain; anything below it ends up buried, so nothing decorates there */ + Decorator(PartCanvas canvas, Map painted, ObjectBuilder blocks, long paletteSeed, int groundY) { + this.canvas = canvas; + this.painted = painted; + this.blocks = blocks; + this.paletteSeed = paletteSeed; + this.groundY = groundY; + } + + void decorate(List decorations, long seed) { + for (int index = 0; index < decorations.size(); index++) { + ProceduralDecoration decoration = decorations.get(index); + if (!decoration.choice().isSet()) { + continue; + } + long decorationSeed = seed + index * DECORATION_SEED_STRIDE; + RNG rng = new RNG(decorationSeed); + for (Spot spot : spots(decoration, rng)) { + if (spot.y() >= groundY && PartNoise.passes(decoration.pattern(), decoration.chance(), decoration.scale(), spot.x(), spot.y(), spot.z(), decorationSeed)) { + place(decoration, spot, rng); + } + } + } + } + + private void place(ProceduralDecoration decoration, Spot spot, RNG rng) { + boolean hangs = decoration.at() == DecorationSpot.BELOW || decoration.at() == DecorationSpot.BOTTOM; + int strand = hangs ? Math.max(1, (int) Math.round(decoration.length().sample(rng, 0))) : 1; + for (int step = 0; step < strand; step++) { + int y = spot.y() - step; + long key = PartCanvas.key(spot.x(), y, spot.z()); + if (y < groundY || painted.containsKey(key)) { + return; + } + BlockState state = decoration.choice().at(blocks, paletteSeed, spot.x(), y, spot.z()); + if (state == null || blocks.has(state, BlockTrait.AIR)) { + return; + } + painted.put(key, attached(state, spot.support())); + } + } + + private List spots(ProceduralDecoration decoration, RNG rng) { + List decorated = decoratedBlocks(decoration); + return switch (decoration.at()) { + case ABOVE -> besideEach(decorated, BlockFace.UP); + case BELOW -> besideEach(decorated, BlockFace.DOWN); + case SIDE -> besideEach(decorated, SIDES); + case TOP -> columnEnds(decorated, true); + case BOTTOM -> columnEnds(decorated, false); + case TIPS -> tips(decoration); + case GROUND -> ground(decoration.radius().sample(rng, 0)); + }; + } + + /** The painted blocks of the roles the decoration is for, in a stable order. */ + private List decoratedBlocks(ProceduralDecoration decoration) { + Set roles = new HashSet<>(); + for (String role : decoration.on()) { + roles.add(canvas.role(role)); + } + List decorated = new ArrayList<>(); + for (long key : painted.keySet()) { + PartCanvas.Cell cell = canvas.get(key); + if (cell != null && (roles.isEmpty() || roles.contains(cell.role()))) { + decorated.add(key); + } + } + decorated.sort(Long::compare); + return decorated; + } + + private List besideEach(List decorated, BlockFace... faces) { + List spots = new ArrayList<>(); + Set taken = new HashSet<>(); + for (long key : decorated) { + for (BlockFace face : faces) { + int[] step = stepToward(face); + int x = PartCanvas.x(key) + step[0]; + int y = PartCanvas.y(key) + step[1]; + int z = PartCanvas.z(key) + step[2]; + long spotKey = PartCanvas.key(x, y, z); + if (!painted.containsKey(spotKey) && taken.add(spotKey)) { + spots.add(new Spot(x, y, z, opposite(face))); + } + } + } + return spots; + } + + private List columnEnds(List decorated, boolean top) { + Map endByColumn = new HashMap<>(); + for (long key : decorated) { + long column = PartCanvas.key(PartCanvas.x(key), 0, PartCanvas.z(key)); + int y = PartCanvas.y(key); + endByColumn.merge(column, y, top ? Math::max : Math::min); + } + List spots = new ArrayList<>(); + endByColumn.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> { + int x = PartCanvas.x(entry.getKey()); + int z = PartCanvas.z(entry.getKey()); + int y = entry.getValue() + (top ? 1 : -1); + if (!painted.containsKey(PartCanvas.key(x, y, z))) { + spots.add(new Spot(x, y, z, top ? BlockFace.DOWN : BlockFace.UP)); + } + }); + return spots; + } + + private List tips(ProceduralDecoration decoration) { + Set roles = new HashSet<>(); + for (String role : decoration.on()) { + roles.add(canvas.role(role)); + } + List spots = new ArrayList<>(); + for (PartCanvas.Tip tip : canvas.tips()) { + if (!roles.isEmpty() && !roles.contains(tip.role())) { + continue; + } + int x = tip.x() + (int) Math.round(tip.heading()[0]); + int y = tip.y() + (int) Math.round(tip.heading()[1]); + int z = tip.z() + (int) Math.round(tip.heading()[2]); + if (!painted.containsKey(PartCanvas.key(x, y, z))) { + spots.add(new Spot(x, y, z, supportToward(tip.x() - x, tip.y() - y, tip.z() - z))); + } + } + return spots; + } + + /** Every open ground spot within the radius of where the object stands, so an arch gets plants around both feet. */ + private List ground(double radius) { + int reach = (int) Math.ceil(radius); + Set nearby = new TreeSet<>(); + for (long foot : footprint()) { + int footX = PartCanvas.x(foot); + int footZ = PartCanvas.z(foot); + for (int x = footX - reach; x <= footX + reach; x++) { + for (int z = footZ - reach; z <= footZ + reach; z++) { + if (Math.hypot(x - footX, z - footZ) <= radius) { + nearby.add(PartCanvas.key(x, groundY, z)); + } + } + } + } + List spots = new ArrayList<>(); + for (long key : nearby) { + int x = PartCanvas.x(key); + int z = PartCanvas.z(key); + if (!painted.containsKey(key) && !painted.containsKey(PartCanvas.key(x, groundY + 1, z))) { + spots.add(new Spot(x, groundY, z, BlockFace.DOWN)); + } + } + return spots; + } + + /** The columns where the object meets the ground, or its origin if it does not reach the ground. */ + private Set footprint() { + Set footprint = new TreeSet<>(); + for (long key : painted.keySet()) { + if (PartCanvas.y(key) == groundY) { + footprint.add(PartCanvas.key(PartCanvas.x(key), groundY, PartCanvas.z(key))); + } + } + if (footprint.isEmpty()) { + footprint.add(PartCanvas.key(0, groundY, 0)); + } + return footprint; + } + + private static BlockFace supportToward(int dx, int dy, int dz) { + if (dy > 0) { + return BlockFace.UP; + } + if (dy < 0) { + return BlockFace.DOWN; + } + if (Math.abs(dx) >= Math.abs(dz)) { + return dx >= 0 ? BlockFace.EAST : BlockFace.WEST; + } + return dz >= 0 ? BlockFace.SOUTH : BlockFace.NORTH; + } + + /** {@code state} turned to rest on the block toward {@code support}. */ + private BlockState attached(BlockState state, BlockFace support) { + String side = support.name().toLowerCase(); + if ("false".equals(IrisProceduralBlocks.propertyValue(state, side))) { + return blocks.withProperty(state, side, "true"); + } + if (support == BlockFace.UP && IrisProceduralBlocks.hasProperty(state, "hanging")) { + return blocks.withProperty(state, "hanging", "true"); + } + if (IrisProceduralBlocks.hasProperty(state, "facing")) { + return blocks.withProperty(state, "facing", opposite(support).name().toLowerCase()); + } + return state; + } + + private static int[] stepToward(BlockFace face) { + return switch (face) { + case UP -> new int[]{0, 1, 0}; + case DOWN -> new int[]{0, -1, 0}; + case NORTH -> new int[]{0, 0, -1}; + case SOUTH -> new int[]{0, 0, 1}; + case EAST -> new int[]{1, 0, 0}; + case WEST -> new int[]{-1, 0, 0}; + }; + } + + private static BlockFace opposite(BlockFace face) { + return switch (face) { + case UP -> BlockFace.DOWN; + case DOWN -> BlockFace.UP; + case NORTH -> BlockFace.SOUTH; + case SOUTH -> BlockFace.NORTH; + case EAST -> BlockFace.WEST; + case WEST -> BlockFace.EAST; + }; + } + + /** An empty block a decoration may go in, and the side its support is on. */ + private record Spot(int x, int y, int z, BlockFace support) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java b/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java new file mode 100644 index 000000000..1357f3602 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java @@ -0,0 +1,132 @@ +/* + * 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.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Gives leaves the state vanilla decay expects: every leaf is told its distance to wood. Leaves farther from wood than + * vanilla keeps are made persistent, so they stay; the pack's parts should keep wood near them instead. + */ +final class LeafDecay { + private static final int UNREACHED_DISTANCE = IrisProceduralBlocks.UNREACHED_LEAF_DISTANCE; + private static final int[][] NEIGHBORS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}; + + private final Map blocks; + private final ObjectBuilder builder; + private final Set leaves = new LinkedHashSet<>(); + + private LeafDecay(Map blocks, ObjectBuilder builder) { + this.blocks = blocks; + this.builder = builder; + List keys = new ArrayList<>(blocks.keySet()); + keys.sort(Long::compare); + for (long key : keys) { + if (isLeaf(blocks.get(key))) { + leaves.add(key); + } + } + } + + /** Leaves that decay naturally, except those too far from wood, which are kept persistent. */ + static void supportLeaves(Map blocks, ObjectBuilder builder) { + LeafDecay decay = new LeafDecay(blocks, builder); + if (decay.leaves.isEmpty()) { + return; + } + decay.markDistances(); + } + + /** Leaves that never decay. */ + static void persistLeaves(Map blocks, ObjectBuilder builder) { + LeafDecay decay = new LeafDecay(blocks, builder); + for (long leaf : decay.leaves) { + decay.setLeafState(leaf, true, 1); + } + } + + private void markDistances() { + Map distance = distances(); + for (long leaf : leaves) { + Integer d = distance.get(leaf); + if (d != null && d < UNREACHED_DISTANCE) { + setLeafState(leaf, false, Math.max(1, d)); + } else { + setLeafState(leaf, true, UNREACHED_DISTANCE); + } + } + } + + /** How many leaf steps each leaf is from wood, up to the farthest vanilla tracks. */ + private Map distances() { + Map distance = new HashMap<>(); + ArrayDeque queue = new ArrayDeque<>(); + for (long leaf : leaves) { + for (int[] n : NEIGHBORS) { + BlockState neighbor = blocks.get(PartCanvas.key(PartCanvas.x(leaf) + n[0], PartCanvas.y(leaf) + n[1], PartCanvas.z(leaf) + n[2])); + if (neighbor != null && builder.has(neighbor, BlockTrait.LOG)) { + distance.put(leaf, 1); + queue.add(leaf); + break; + } + } + } + while (!queue.isEmpty()) { + long leaf = queue.poll(); + int d = distance.get(leaf); + if (d >= UNREACHED_DISTANCE) { + continue; + } + for (int[] n : NEIGHBORS) { + long next = PartCanvas.key(PartCanvas.x(leaf) + n[0], PartCanvas.y(leaf) + n[1], PartCanvas.z(leaf) + n[2]); + BlockState state = blocks.get(next); + if (state == null || !isLeaf(state)) { + continue; + } + Integer known = distance.get(next); + if (known == null || known > d + 1) { + distance.put(next, d + 1); + queue.add(next); + } + } + } + return distance; + } + + private void setLeafState(long leaf, boolean persistent, int distance) { + BlockState state = blocks.get(leaf); + state = builder.withProperty(state, "persistent", String.valueOf(persistent)); + blocks.put(leaf, builder.withProperty(state, "distance", String.valueOf(distance))); + } + + private static boolean isLeaf(BlockState state) { + return IrisProceduralBlocks.hasProperty(state, "persistent") && IrisProceduralBlocks.hasProperty(state, "distance"); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java b/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java new file mode 100644 index 000000000..994c0f759 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java @@ -0,0 +1,135 @@ +/* + * 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.procedural.part; + +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Turns the canvas into block data: each block takes its role's material, or the first of its rules that applies. */ +final class MaterialPainter { + private static final long RULE_SEED_STRIDE = 7907L; + private static final int[][] SIDES = {{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}}; + + private final PartCanvas canvas; + private final Map materialByRole = new HashMap<>(); + private final ProceduralMaterial fallback; + private final ObjectBuilder blocks; + private final long paletteSeed; + private final long ruleSeed; + private final int lowestY; + private final int heightSpan; + + MaterialPainter(PartCanvas canvas, List materials, ObjectBuilder blocks, long paletteSeed, long ruleSeed) { + this.canvas = canvas; + this.blocks = blocks; + this.paletteSeed = paletteSeed; + this.ruleSeed = ruleSeed; + this.fallback = materials.isEmpty() ? null : materials.getFirst(); + for (ProceduralMaterial material : materials) { + materialByRole.putIfAbsent(canvas.role(material.role()), material); + } + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; + for (long key : canvas.cells().keySet()) { + lowest = Math.min(lowest, PartCanvas.y(key)); + highest = Math.max(highest, PartCanvas.y(key)); + } + this.lowestY = lowest; + this.heightSpan = Math.max(1, highest - lowest); + } + + /** The block of every claimed position, leaving out those a rule turned to air. */ + Map paint() { + Map painted = new HashMap<>(); + for (Map.Entry entry : canvas.cells().entrySet()) { + BlockState state = blockFor(entry.getKey(), entry.getValue()); + if (state != null && !blocks.has(state, BlockTrait.AIR)) { + painted.put(entry.getKey(), state); + } + } + return painted; + } + + private BlockState blockFor(long key, PartCanvas.Cell cell) { + ProceduralMaterial material = materialByRole.getOrDefault(cell.role(), fallback); + if (material == null) { + return null; + } + int x = PartCanvas.x(key); + int y = PartCanvas.y(key); + int z = PartCanvas.z(key); + BlockChoice choice = material.choice(); + List rules = material.rules(); + for (int index = 0; index < rules.size(); index++) { + if (applies(rules.get(index), index, x, y, z, cell)) { + choice = rules.get(index).choice(); + break; + } + } + BlockState state = choice.at(blocks, paletteSeed, x, y, z); + if (state == null || blocks.has(state, BlockTrait.AIR)) { + return state; + } + return alignedToAxis(state, cell.axis()); + } + + private boolean applies(MaterialRule rule, int index, int x, int y, int z, PartCanvas.Cell cell) { + double height = (y - lowestY) / (double) heightSpan; + if (rule.height() != null && !rule.height().contains(height)) { + return false; + } + if (rule.along() != null && !rule.along().contains(cell.along())) { + return false; + } + if (rule.face() != null && !open(rule.face(), x, y, z)) { + return false; + } + return PartNoise.passes(rule.pattern(), rule.chance().at(height), rule.scale(), x, y, z, ruleSeed + index * RULE_SEED_STRIDE); + } + + private boolean open(RuleFace face, int x, int y, int z) { + return switch (face) { + case UP -> !canvas.has(x, y + 1, z); + case DOWN -> !canvas.has(x, y - 1, z); + case SIDE -> openSide(x, y, z); + case ANY -> openSide(x, y, z) || !canvas.has(x, y + 1, z) || !canvas.has(x, y - 1, z); + }; + } + + private boolean openSide(int x, int y, int z) { + for (int[] side : SIDES) { + if (!canvas.has(x + side[0], y, z + side[2])) { + return true; + } + } + return false; + } + + private BlockState alignedToAxis(BlockState state, PartCanvas.Axis axis) { + if (axis == PartCanvas.Axis.NONE || !IrisProceduralBlocks.hasProperty(state, "axis")) { + return state; + } + return blocks.withProperty(state, "axis", axis.name().toLowerCase()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java b/src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java new file mode 100644 index 000000000..08cce07fe --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/MaterialRule.java @@ -0,0 +1,85 @@ +/* + * 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.procedural.part; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +@Desc("Swaps a material's block where its conditions hold, such as moss on top faces or a cap on the highest blocks. Use minecraft:air to erode blocks away.") +public final class MaterialRule { + @Ref(Reference.BLOCK) + @Desc("The block to swap in. Ignored when palette is set.") + private String block; + + @Desc("A noise palette to swap in.") + private PaletteSpec palette; + + @MinNumber(0) + @Desc("If above 0, the palette changes every this many blocks of height, for strata.") + private int bands = 0; + + @Desc("The chance a block that meets the conditions is swapped. A curve runs from the bottom (0) to the top (1) of the object.") + private ProceduralValue chance = ProceduralValue.constant(1); + + @Desc("How the chance is spread over the blocks.") + private PartPattern pattern = PartPattern.RANDOM; + + @MinNumber(1) + @Desc("The size of the patches in blocks for the PATCHES pattern.") + private double scale = 3; + + @Desc("Only swaps blocks within this stretch of the object's height, from the bottom (0) to the top (1).") + private ProceduralSpan height; + + @Desc("Only swaps blocks within this stretch of their own part, from its base (0) to its tip (1).") + private ProceduralSpan along; + + @Desc("Only swaps blocks open to the air on this side.") + private RuleFace face; + + public BlockChoice choice() { + return new BlockChoice(block, palette, bands); + } + + public ProceduralValue chance() { + return chance == null ? ProceduralValue.constant(1) : chance; + } + + public PartPattern pattern() { + return pattern == null ? PartPattern.RANDOM : pattern; + } + + public double scale() { + return scale; + } + + public ProceduralSpan height() { + return height; + } + + public ProceduralSpan along() { + return along; + } + + public RuleFace face() { + return face; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java b/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java new file mode 100644 index 000000000..c417bd9d0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java @@ -0,0 +1,120 @@ +/* + * 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.procedural.part; + +import art.arcane.iris.engine.procedural.BakeProfile; +import com.volmit.geometry.BlockPosition; +import art.arcane.iris.engine.procedural.IrisProceduralBlocks; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.iris.engine.procedural.ProceduralShape; +import art.arcane.volmlib.util.math.RNG; +import art.arcane.volmlib.util.math.Vector3i; +import com.volmit.block.BlockState; + +import java.util.HashMap; +import java.util.Map; + +/** Bakes one variant of a procedural object: grows its parts, paints them, decorates them and settles the leaves. */ +final class ObjectBaker { + private static final long DECORATION_SEED_SALT = 77777L; + private static final long RULE_SEED_SALT = 4111L; + + private ObjectBaker() { + } + + static ProceduralShape bake(ProceduralObject definition, PartOutline outline, RNG rng, ObjectBuilder blocks, BakeProfile profile) { + BakedBlocks baked = bakeBlocks(definition, outline, rng, blocks, profile); + return baked == null ? null : IrisProceduralBlocks.assemble(baked.placed()); + } + + /** Bakes the variant {@code rng} draws, the same as {@link #bake}, and tells which part placed each of its blocks. */ + static PartTrace trace(ProceduralObject definition, PartOutline outline, RNG rng, ObjectBuilder blocks) { + BakedBlocks baked = bakeBlocks(definition, outline, rng, blocks, BakeProfile.NONE); + if (baked == null) { + return PartTrace.EMPTY; + } + IrisProceduralBlocks.Anchor anchor = IrisProceduralBlocks.Anchor.of(baked.placed().keySet()); + Map partsByBlock = new HashMap<>(); + for (long key : baked.painted().keySet()) { + PartCanvas.Cell cell = baked.canvas().get(key); + if (cell == null) { + continue; + } + BlockPosition position = anchor.place(baked.sunkPosition(key)); + partsByBlock.put(PartCanvas.key(position.x(), position.y(), position.z()), cell.part()); + } + return new PartTrace(partsByBlock); + } + + private static BakedBlocks bakeBlocks(ProceduralObject definition, PartOutline outline, RNG rng, ObjectBuilder blocks, + BakeProfile profile) { + PartCanvas canvas = new PartCanvas(); + long variantSeed = rng.nextLong(); + new PartGrower(canvas, definition.defaultRole(), outline).growRoots(definition.parts(), variantSeed); + profile.lap(BakeProfile.Stage.PARTS); + if (canvas.isEmpty()) { + return null; + } + + Map painted = new MaterialPainter(canvas, definition.materials(), blocks, definition.seed(), + variantSeed + RULE_SEED_SALT).paint(); + int sinkDepth = sinkDepth(painted, definition.sink()); + profile.lap(BakeProfile.Stage.PAINT); + new Decorator(canvas, painted, blocks, definition.seed(), sinkDepth).decorate(definition.decorations(), variantSeed + DECORATION_SEED_SALT); + profile.lap(BakeProfile.Stage.DECORATE); + if (definition.leafDecay()) { + LeafDecay.supportLeaves(painted, blocks); + } else { + LeafDecay.persistLeaves(painted, blocks); + } + if (definition.waterlogged()) { + waterlog(painted, blocks); + } + profile.lap(BakeProfile.Stage.LEAVES); + return new BakedBlocks(canvas, painted, sinkDepth); + } + + private static void waterlog(Map painted, ObjectBuilder blocks) { + painted.replaceAll((key, state) -> "false".equals(IrisProceduralBlocks.propertyValue(state, "waterlogged")) + ? blocks.withProperty(state, "waterlogged", "true") : state); + } + + /** How far the object sinks: a fraction of its height. Heights below it end up underground. */ + private static int sinkDepth(Map painted, double sink) { + int lowest = Integer.MAX_VALUE; + int highest = Integer.MIN_VALUE; + for (long key : painted.keySet()) { + lowest = Math.min(lowest, PartCanvas.y(key)); + highest = Math.max(highest, PartCanvas.y(key)); + } + return (int) Math.round(Math.max(0, Math.min(1, sink)) * (highest - lowest + 1)); + } + + /** A variant's blocks before they are anchored: the parts' canvas, the painted blocks and how far they sink. */ + private record BakedBlocks(PartCanvas canvas, Map painted, int sinkDepth) { + Map placed() { + Map placed = new HashMap<>(); + painted.forEach((key, state) -> placed.put(sunkPosition(key), state)); + return placed; + } + + Vector3i sunkPosition(long key) { + return new Vector3i(PartCanvas.x(key), PartCanvas.y(key) - sinkDepth, PartCanvas.z(key)); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java new file mode 100644 index 000000000..a67ba8348 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartBlob.java @@ -0,0 +1,108 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +@Desc("A rounded volume centered where the part sits: a leaf crown, boulder, cap, coral head or base. Values given as a curve run over where the blob sits on its parent.") +public final class PartBlob { + @Desc("The horizontal radius in blocks.") + private ProceduralValue radius = ProceduralValue.constant(2); + + @Desc("How far the blob reaches above its center, in blocks. Unset, it matches the radius.") + private ProceduralValue height; + + @Desc("How far the blob reaches below its center, in blocks. Unset, it matches the height; 0 makes a dome.") + private ProceduralValue depth; + + @MinNumber(0) + @Desc("Stretches the blob along east-west; 0.1 flattens it into a north-south fan.") + private double stretchX = 1; + + @MinNumber(0) + @Desc("Stretches the blob along north-south; 0.1 flattens it into an east-west fan.") + private double stretchZ = 1; + + @Desc("A multiplier on the radius from the bottom (0) to the top (1) of the blob. Unset, the blob is an ellipsoid; [[0, 1], [1, 0]] makes a cone, [[0, 1], [1, 1]] a cylinder.") + private ProceduralValue profile; + + @Desc("The horizontal cross-section of the blob.") + private PartSection section = PartSection.ROUND; + + @Desc("If above 0, the blob is hollow, keeping only the blocks this many blocks or fewer from its surface.") + private ProceduralValue shell = ProceduralValue.constant(0); + + @Desc("If true the shell has no floor: only the surface above and around counts, like a mushroom cap.") + private boolean open = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How lumpy the surface is, from 0 (smooth) to 1 (very lumpy).") + private double roughness = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How many blocks along the surface are knocked off at random, from 0 to 1.") + private double jitter = 0; + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(2) : radius; + } + + public ProceduralValue height() { + return height; + } + + public ProceduralValue depth() { + return depth; + } + + public double stretchX() { + return stretchX; + } + + public double stretchZ() { + return stretchZ; + } + + public ProceduralValue profile() { + return profile; + } + + public PartSection section() { + return section == null ? PartSection.ROUND : section; + } + + public ProceduralValue shell() { + return shell == null ? ProceduralValue.constant(0) : shell; + } + + public boolean open() { + return open; + } + + public double roughness() { + return roughness; + } + + public double jitter() { + return jitter; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java new file mode 100644 index 000000000..c2432bfad --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartBranches.java @@ -0,0 +1,107 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; + +@Desc("Grows copies of a part out of its parent: branches off a trunk, arms off a coral stalk, forks at a tip. Values given as a curve run from the parent's base (0) to its tip (1).") +public final class PartBranches { + @Desc("How many copies grow. Ignored when chance is set.") + private ProceduralValue count = ProceduralValue.constant(4); + + @Desc("If set, every block along the parent rolls this chance to grow a copy, such as {\"shape\": \"power\", \"exponent\": 2} for more toward the top.") + private ProceduralValue chance; + + @Desc("The stretch of the parent copies grow from; from 1 to 1 grows them all at the tip.") + private ProceduralSpan along = new ProceduralSpan(); + + @Desc("Which way around the parent each copy points.") + private BranchAzimuth azimuth = BranchAzimuth.RANDOM; + + @Desc("Turns every copy this many degrees further around the parent.") + private ProceduralValue azimuthOffset = ProceduralValue.constant(0); + + @MinNumber(1) + @Desc("How many copies make a ring for the WHORL azimuth.") + private int whorl = 4; + + @Desc("The degrees between copies for the FAN azimuth.") + private double fan = 40; + + @Desc("The angle in degrees above the horizon each copy grows toward; negative droops. With relative set, the angle is added to the parent's own.") + private ProceduralValue pitch = ProceduralValue.constant(0); + + @Desc("If true the copies point relative to the parent's direction instead of the compass, as forks and twigs do.") + private boolean relative = false; + + @MinNumber(1) + @MaxNumber(6) + @Desc("How many times branching repeats: 2 grows copies off the copies too, and so on.") + private int depth = 1; + + @Required + @Desc("The part each copy is made of.") + private ProceduralPart part; + + public ProceduralValue count() { + return count == null ? ProceduralValue.constant(4) : count; + } + + public ProceduralValue chance() { + return chance; + } + + public ProceduralSpan along() { + return along == null ? new ProceduralSpan() : along; + } + + public BranchAzimuth azimuth() { + return azimuth == null ? BranchAzimuth.RANDOM : azimuth; + } + + public ProceduralValue azimuthOffset() { + return azimuthOffset == null ? ProceduralValue.constant(0) : azimuthOffset; + } + + public int whorl() { + return Math.max(1, whorl); + } + + public double fan() { + return fan; + } + + public ProceduralValue pitch() { + return pitch == null ? ProceduralValue.constant(0) : pitch; + } + + public boolean relative() { + return relative; + } + + public int depth() { + return Math.max(1, Math.min(6, depth)); + } + + public ProceduralPart part() { + return part; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java new file mode 100644 index 000000000..72e6a8d9f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartCanvas.java @@ -0,0 +1,140 @@ +/* + * 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.procedural.part; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The blocks the parts of one variant claim, before materials turn them into block data: each with the role of the + * part that placed it, how far along that part it sits, and the axis a log there would follow. + */ +final class PartCanvas { + /** Enough for any sensible object; a typo asking for more stops growing instead of baking for minutes. */ + static final int MAXIMUM_BLOCKS = 1_500_000; + + enum Axis { + NONE, X, Y, Z; + + /** The axis a log along {@code direction} lies on, leaning toward upright as trees do. */ + static Axis along(double[] direction) { + double x = Math.abs(direction[0]); + double y = Math.abs(direction[1]) * 1.8; + double z = Math.abs(direction[2]); + if (y >= x && y >= z) { + return Y; + } + return x >= z ? X : Z; + } + } + + /** @param part the {@link PartOutline} id of the part that placed the block */ + record Cell(int role, float along, Axis axis, int part) { + } + + /** The end of a stem, where tip decorations go. */ + record Tip(int x, int y, int z, double[] heading, int role) { + } + + private final Map cells = new HashMap<>(); + private final List tips = new ArrayList<>(); + private final List roles = new ArrayList<>(); + private boolean full; + + int role(String name) { + int index = roles.indexOf(name); + if (index >= 0) { + return index; + } + roles.add(name); + return roles.size() - 1; + } + + String roleName(int role) { + return roles.get(role); + } + + void place(int x, int y, int z, PartMode mode, Cell cell) { + long key = key(x, y, z); + switch (mode) { + case ADD -> { + if (!full || cells.containsKey(key)) { + cells.put(key, cell); + } + } + case FILL -> { + if (!full && !cells.containsKey(key)) { + cells.put(key, cell); + } + } + case CARVE -> cells.remove(key); + } + full = cells.size() >= MAXIMUM_BLOCKS; + } + + boolean has(int x, int y, int z) { + return cells.containsKey(key(x, y, z)); + } + + Cell get(long key) { + return cells.get(key); + } + + Map cells() { + return Collections.unmodifiableMap(cells); + } + + void addTip(Tip tip) { + tips.add(tip); + } + + List tips() { + return Collections.unmodifiableList(tips); + } + + boolean isEmpty() { + return cells.isEmpty(); + } + + boolean isFull() { + return full; + } + + static long key(int x, int y, int z) { + return ((long) (x & 0x1FFFFF)) | ((long) (y & 0x1FFFFF) << 21) | ((long) (z & 0x1FFFFF) << 42); + } + + static int x(long key) { + return signed((int) (key & 0x1FFFFF)); + } + + static int y(long key) { + return signed((int) ((key >>> 21) & 0x1FFFFF)); + } + + static int z(long key) { + return signed((int) ((key >>> 42) & 0x1FFFFF)); + } + + private static int signed(int value) { + return (value << 11) >> 11; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java new file mode 100644 index 000000000..f2fd488d7 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartCluster.java @@ -0,0 +1,60 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.Required; + +@Desc("Places copies of a part around a center: columns in a causeway, peaks on an iceberg, shards on a crystal. Each copy leans away from the center unless its stem says otherwise.") +public final class PartCluster { + @Desc("How many copies to place.") + private ProceduralValue count = ProceduralValue.constant(5); + + @Desc("How far from the center copies are placed, in blocks.") + private ProceduralValue radius = ProceduralValue.constant(2); + + @Desc("How the copies are laid out.") + private ClusterLayout layout = ClusterLayout.RANDOM; + + @Desc("How far each copy tilts away from the center, in degrees from straight up. A range gives each copy its own tilt; a curve runs from the center (0) to the edge (1).") + private ProceduralValue tilt = ProceduralValue.constant(0); + + @Required + @Desc("The part each copy is made of.") + private ProceduralPart part; + + public ProceduralValue count() { + return count == null ? ProceduralValue.constant(5) : count; + } + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(2) : radius; + } + + public ClusterLayout layout() { + return layout == null ? ClusterLayout.RANDOM : layout; + } + + public ProceduralValue tilt() { + return tilt == null ? ProceduralValue.constant(0) : tilt; + } + + public ProceduralPart part() { + return part; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java new file mode 100644 index 000000000..fff683b1f --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartFill.java @@ -0,0 +1,41 @@ +/* + * 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.procedural.part; + +/** How one part writes its blocks: the mode it combines with, and the density that thins it. */ +record PartFill(PartCanvas canvas, PartMode mode, int role, int partId, double density, PartPattern pattern, double scale, + double falloff, long seed) { + static PartFill of(PartCanvas canvas, ProceduralPart part, int partId, int role, long seed) { + return new PartFill(canvas, part.mode(), role, partId, part.density(), part.pattern(), part.scale(), part.falloff(), seed); + } + + /** + * Places the block if the density lets it; {@code edge} is how far toward the shape's edge it is, from 0 at the + * center to 1 at the edge, for the falloff. + */ + void place(int x, int y, int z, double edge, double along, PartCanvas.Axis axis) { + double chance = density; + if (falloff > 0) { + chance *= Math.pow(Math.max(0, 1 - edge), falloff); + } + if (!PartNoise.passes(pattern, chance, scale, x, y, z, seed)) { + return; + } + canvas.place(x, y, z, mode, new PartCanvas.Cell(role, (float) along, axis, partId)); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java new file mode 100644 index 000000000..af93ea4e1 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartGrower.java @@ -0,0 +1,201 @@ +/* + * 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.procedural.part; + +import art.arcane.volmlib.util.math.RNG; + +import java.util.ArrayList; +import java.util.List; + +/** + * Grows a part tree onto a canvas: each part is drawn from where it sits on its parent, then its children grow from it. + * Every part draws from its own seed, taken from its parent's in order, so adding a part only changes what grows after it. + */ +final class PartGrower { + private static final double GOLDEN_ANGLE_DEGREES = 137.50776405003785; + private static final int MOST_COPIES = 256; + private static final int DEEPEST_NESTING = 24; + + private final PartCanvas canvas; + private final String defaultRole; + private final PartOutline outline; + + PartGrower(PartCanvas canvas, String defaultRole, PartOutline outline) { + this.canvas = canvas; + this.defaultRole = defaultRole; + this.outline = outline; + } + + void growRoots(List parts, long seed) { + RNG seeds = new RNG(seed); + for (ProceduralPart part : parts) { + growChild(part, PartShape.ROOT, canvas.role(defaultRole), seeds.nextLong(), 0); + } + } + + /** Grows a part that sits on its parent where its own 'at' and 'offset' say. */ + private void growChild(ProceduralPart part, PartShape parent, int parentRole, long seed, int nesting) { + if (part == null || canvas.isFull()) { + return; + } + RNG rng = new RNG(seed); + double at = part.at() == null ? parent.defaultAt() : part.at().sample(rng, 0); + PartSpot spot = parent.spotAt(at); + if (part.offset() != null) { + spot = spot.movedBy(part.offset().roll(rng)); + } + grow(part, parent, spot, parentRole, rng, List.of(), nesting); + } + + /** Grows a part at {@code spot}, then its children, then any branching it repeats from its own copy. */ + private void grow(ProceduralPart part, PartShape parent, PartSpot spot, int parentRole, RNG rng, + List repeats, int nesting) { + if (nesting > DEEPEST_NESTING || canvas.isFull()) { + return; + } + int role = part.role() == null || part.role().isBlank() ? parentRole : canvas.role(part.role()); + PartFill fill = PartFill.of(canvas, part, outline.idOf(part), role, rng.nextLong()); + PartShape shape = parent; + if (part.stem() != null) { + StemShape stem = StemShape.trace(part.stem(), spot, rng); + stem.draw(fill, part.stem().section(), part.stem().roughness(), part.stem().jitter()); + shape = stem; + } else if (part.blob() != null) { + BlobShape blob = BlobShape.trace(part.blob(), spot, rng); + blob.draw(fill, part.blob().roughness(), part.blob().jitter()); + shape = blob; + } else if (part.branches() != null) { + branch(part.branches(), parent, role, rng, part.branches().depth(), nesting); + } else if (part.cluster() != null) { + cluster(part.cluster(), spot, role, rng, nesting); + } + + for (ProceduralPart child : part.children()) { + growChild(child, shape, role, rng.nextLong(), nesting + 1); + } + for (Repeat repeat : repeats) { + branch(repeat.branches(), shape, role, rng, repeat.depthLeft(), nesting); + } + } + + private void branch(PartBranches branches, PartShape parent, int role, RNG rng, int depthLeft, int nesting) { + if (branches.part() == null || depthLeft <= 0) { + return; + } + List positions = branchPositions(branches, parent, rng); + List repeats = depthLeft > 1 ? List.of(new Repeat(branches, depthLeft - 1)) : List.of(); + double azimuthOffset = branches.azimuthOffset().sample(rng, 0); + for (int index = 0; index < positions.size(); index++) { + double t = positions.get(index); + PartSpot onParent = parent.spotAt(t); + double pitch = branches.pitch().sample(rng, t); + double[] heading = branchHeading(branches, onParent, index, positions.size(), azimuthOffset, pitch, rng); + PartSpot spot = new PartSpot(onParent.origin(), heading, t, parent.length(), Vectors.azimuth(heading)); + RNG copyRng = new RNG(rng.nextLong()); + ProceduralPart copy = branches.part(); + if (copy.offset() != null) { + spot = spot.movedBy(copy.offset().roll(copyRng)); + } + grow(copy, parent, spot, role, copyRng, repeats, nesting + 1); + } + } + + private static List branchPositions(PartBranches branches, PartShape parent, RNG rng) { + ProceduralSpan along = branches.along(); + List positions = new ArrayList<>(); + if (branches.chance() != null) { + double blocks = Math.max(1, parent.length()); + int first = (int) Math.ceil(along.from() * blocks); + int last = (int) Math.floor(along.to() * blocks); + for (int block = first; block <= last && positions.size() < MOST_COPIES; block++) { + double t = Math.min(1, block / blocks); + if (rng.nextDouble() < branches.chance().at(t)) { + positions.add(t); + } + } + return positions; + } + int count = Math.min(MOST_COPIES, Math.max(0, (int) Math.round(branches.count().sample(rng, 0)))); + for (int index = 0; index < count; index++) { + double fraction = along.to() - along.from() < 1e-9 ? 0 : (index + rng.d(0.25, 0.75)) / count; + positions.add(along.from() + (along.to() - along.from()) * fraction); + } + return positions; + } + + private static double[] branchHeading(PartBranches branches, PartSpot onParent, int index, int count, + double azimuthOffset, double pitch, RNG rng) { + double parentAzimuth = Vectors.isVertical(onParent.heading()) && onParent.hasOutward() + ? onParent.outward() : Vectors.azimuth(onParent.heading()); + double turn = switch (branches.azimuth()) { + case RANDOM -> rng.d(0, 360); + case GOLDEN -> index * GOLDEN_ANGLE_DEGREES; + case ALTERNATE -> (index % 2) * 180.0; + case WHORL -> (index % branches.whorl()) * (360.0 / branches.whorl()); + case EVEN -> index * (360.0 / Math.max(1, count)); + case FAN -> branches.fan() * (index - (count - 1) / 2.0); + }; + boolean relative = branches.relative() || branches.azimuth() == BranchAzimuth.FAN; + double azimuth = (relative ? parentAzimuth : 0) + turn + azimuthOffset; + double finalPitch = branches.relative() ? Vectors.pitch(onParent.heading()) + pitch : pitch; + return Vectors.direction(azimuth, Math.max(-90, Math.min(90, finalPitch))); + } + + private void cluster(PartCluster cluster, PartSpot spot, int role, RNG rng, int nesting) { + if (cluster.part() == null) { + return; + } + int count = Math.min(MOST_COPIES, Math.max(0, (int) Math.round(cluster.count().sample(rng, 0)))); + double radius = Math.max(0, cluster.radius().sample(rng, 0)); + double phase = rng.d(0, 360); + for (int index = 0; index < count; index++) { + Placed placed = placeInCluster(cluster.layout(), index, count, radius, phase, rng); + double[] origin = Vectors.add(spot.origin(), Vectors.scale(Vectors.direction(placed.azimuth(), 0), placed.distance())); + RNG copyRng = new RNG(rng.nextLong()); + double fromCenter = radius <= 0 ? 0 : Math.min(1, placed.distance() / radius); + double tilt = cluster.tilt().sample(copyRng, fromCenter); + double[] heading = tilt == 0 ? spot.heading().clone() : Vectors.tilted(spot.heading(), placed.azimuth(), tilt); + PartSpot copySpot = new PartSpot(origin, heading, fromCenter, Math.max(1, radius), placed.azimuth()); + ProceduralPart copy = cluster.part(); + if (copy.offset() != null) { + copySpot = copySpot.movedBy(copy.offset().roll(copyRng)); + } + grow(copy, PartShape.ROOT, copySpot, role, copyRng, List.of(), nesting + 1); + } + } + + private static Placed placeInCluster(ClusterLayout layout, int index, int count, double radius, double phase, RNG rng) { + return switch (layout) { + case RANDOM -> new Placed(rng.d(0, 360), radius * Math.sqrt(rng.nextDouble())); + case RING -> new Placed(phase + index * 360.0 / Math.max(1, count), radius); + case GOLDEN -> new Placed(phase + index * GOLDEN_ANGLE_DEGREES, radius * Math.sqrt((index + 0.5) / Math.max(1, count))); + case LINE -> { + double lane = count <= 1 ? 0 : -radius + 2 * radius * index / (count - 1.0); + yield new Placed(lane < 0 ? phase + 180 : phase, Math.abs(lane)); + } + }; + } + + /** A branching that repeats on the copies it grows, with how many more times it may. */ + private record Repeat(PartBranches branches, int depthLeft) { + } + + /** Where a cluster copy sits: which way from the center, and how far. */ + private record Placed(double azimuth, double distance) { + } +} diff --git a/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalDistribution.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartMode.java similarity index 59% rename from src/main/java/art/arcane/iris/modules/objects/crystal/CrystalDistribution.java rename to src/main/java/art/arcane/iris/engine/procedural/part/PartMode.java index e4dbc5517..83b978c04 100644 --- a/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalDistribution.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartMode.java @@ -15,16 +15,16 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ - -package art.arcane.iris.modules.objects.crystal; +package art.arcane.iris.engine.procedural.part; import com.volmit.config.Desc; -@Desc("How the shards of a crystal cluster are angularly distributed around the surface normal.") -public enum CrystalDistribution { - @Desc("Each shard gets a uniformly random azimuth around the normal. Produces a chaotic, naturally clumped cluster.") - RANDOM, - - @Desc("Each shard's azimuth advances by the golden angle (~137.5 degrees) from the previous one. Produces an evenly spaced sunflower-like fan with no two shards overlapping, ideal for a geode rosette.") - GOLDEN_ANGLE +@Desc("How a part's blocks combine with the blocks already there.") +public enum PartMode { + @Desc("Places blocks, replacing whatever earlier parts put there.") + ADD, + @Desc("Places blocks only where nothing is yet, like leaves around wood.") + FILL, + @Desc("Removes the blocks earlier parts put inside this part's shape.") + CARVE } diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java new file mode 100644 index 000000000..1ba2ac509 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartNoise.java @@ -0,0 +1,98 @@ +/* + * 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.procedural.part; + +/** Seeded noise for parts: a hash per block for speckle, and smooth value noise for patches and wandering. */ +final class PartNoise { + private static final double PATCH_CONTRAST = 1.8; + + private PartNoise() { + } + + /** A value from 0 to 1 that is the same for the same block and seed. */ + static double hash(int x, int y, int z, long seed) { + long h = mix(seed); + h = mix(h + x * 0x9E3779B97F4A7C15L); + h = mix(h + y * 0xC2B2AE3D27D4EB4FL); + h = mix(h + z * 0x165667B19E3779F9L); + return unit(h); + } + + /** Smooth value noise from 0 to 1 with features {@code scale} blocks across, stretched so thresholds split it evenly. */ + static double patches(double x, double y, double z, double scale, long seed) { + double size = Math.max(1, scale); + double value = smooth(x / size, y / size, z / size, seed); + return Math.max(0, Math.min(1, (value - 0.5) * PATCH_CONTRAST + 0.5)); + } + + /** Smooth value noise from 0 to 1 along a line. */ + static double line(double t, long seed) { + int cell = (int) Math.floor(t); + double blend = fade(t - cell); + double a = hash(cell, 0, 0, seed); + double b = hash(cell + 1, 0, 0, seed); + return a + (b - a) * blend; + } + + /** Whether a block passes a chance under a pattern. */ + static boolean passes(PartPattern pattern, double chance, double scale, int x, int y, int z, long seed) { + if (chance >= 1) { + return true; + } + if (chance <= 0) { + return false; + } + double roll = pattern == PartPattern.PATCHES ? patches(x, y, z, scale, seed) : hash(x, y, z, seed); + return roll < chance; + } + + private static double smooth(double x, double y, double z, long seed) { + int x0 = (int) Math.floor(x); + int y0 = (int) Math.floor(y); + int z0 = (int) Math.floor(z); + double fx = fade(x - x0); + double fy = fade(y - y0); + double fz = fade(z - z0); + double c00 = lerp(hash(x0, y0, z0, seed), hash(x0 + 1, y0, z0, seed), fx); + double c10 = lerp(hash(x0, y0 + 1, z0, seed), hash(x0 + 1, y0 + 1, z0, seed), fx); + double c01 = lerp(hash(x0, y0, z0 + 1, seed), hash(x0 + 1, y0, z0 + 1, seed), fx); + double c11 = lerp(hash(x0, y0 + 1, z0 + 1, seed), hash(x0 + 1, y0 + 1, z0 + 1, seed), fx); + return lerp(lerp(c00, c10, fy), lerp(c01, c11, fy), fz); + } + + private static double fade(double t) { + return t * t * (3 - 2 * t); + } + + private static double lerp(double a, double b, double t) { + return a + (b - a) * t; + } + + static long mix(long a) { + a ^= (a >>> 33); + a *= 0xff51afd7ed558ccdL; + a ^= (a >>> 33); + a *= 0xc4ceb9fe1a85ec53L; + a ^= (a >>> 33); + return a; + } + + private static double unit(long h) { + return (h >>> 11) * 0x1.0p-53; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java new file mode 100644 index 000000000..d7a564cf0 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartOffset.java @@ -0,0 +1,41 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; +import art.arcane.volmlib.util.math.RNG; + +@Desc("A shift in blocks along each axis. Each axis takes a number or a [min, max] range.") +public final class PartOffset { + @Desc("Blocks east (negative is west).") + private ProceduralValue x; + + @Desc("Blocks up (negative is down).") + private ProceduralValue y; + + @Desc("Blocks south (negative is north).") + private ProceduralValue z; + + public double[] roll(RNG rng) { + return new double[]{roll(x, rng), roll(y, rng), roll(z, rng)}; + } + + private static double roll(ProceduralValue value, RNG rng) { + return value == null ? 0 : value.sample(rng, 0); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java new file mode 100644 index 000000000..bd467f82a --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartOutline.java @@ -0,0 +1,134 @@ +/* + * 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.procedural.part; + +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + +/** + * The part tree of a procedural object as a viewer lists it, with an id per node that {@link PartTrace} tags blocks + * with. A part that copies another, like branches, shares its node with the copied part, so the tree reads one level + * shallower than the settings. Ids number the nodes in order, so they stay the same across seeds and variants. + */ +public final class PartOutline { + public static final int NO_PART = -1; + + /** + * One row of the tree. + * + * @param shape what the part is, like {@code Branches ×12 · Stem} + * @param detail the role its blocks get, and whether it carves them away instead + */ + public record Node(int id, String shape, String detail, List children) { + } + + private final Map idsByPart = new IdentityHashMap<>(); + private final List roots; + private int nodeCount; + + private PartOutline(ProceduralObject definition) { + this.roots = nodesFor(definition.parts(), definition.defaultRole()); + } + + public static PartOutline of(ProceduralObject definition) { + return new PartOutline(definition); + } + + public List roots() { + return roots; + } + + public int nodeCount() { + return nodeCount; + } + + public int idOf(ProceduralPart part) { + return idsByPart.getOrDefault(part, NO_PART); + } + + private List nodesFor(List parts, String parentRole) { + List nodes = new ArrayList<>(); + for (ProceduralPart part : parts) { + if (part != null) { + nodes.add(nodeFor(part, parentRole)); + } + } + return nodes; + } + + // Children follow the order the grower draws them in: the copies' own children first, then the part's. + private Node nodeFor(ProceduralPart part, String parentRole) { + int id = nodeCount++; + idsByPart.put(part, id); + String role = roleOf(part, parentRole); + ProceduralPart copied = copiedPart(part); + List children = new ArrayList<>(); + String shape; + String detail; + if (copied != null && copiedPart(copied) == null) { + idsByPart.put(copied, id); + String copiedRole = roleOf(copied, role); + shape = copiesLabel(part) + " · " + shapeName(copied); + detail = detailOf(copied, copiedRole); + children.addAll(nodesFor(copied.children(), copiedRole)); + } else { + shape = copied != null ? copiesLabel(part) : shapeName(part); + detail = detailOf(part, role); + if (copied != null) { + children.add(nodeFor(copied, role)); + } + } + children.addAll(nodesFor(part.children(), role)); + return new Node(id, shape, detail, List.copyOf(children)); + } + + private static String roleOf(ProceduralPart part, String parentRole) { + return part.role() == null || part.role().isBlank() ? parentRole : part.role(); + } + + private static ProceduralPart copiedPart(ProceduralPart part) { + if (part.branches() != null) { + return part.branches().part(); + } + return part.cluster() != null ? part.cluster().part() : null; + } + + private static String copiesLabel(ProceduralPart part) { + if (part.branches() != null) { + return part.branches().chance() != null ? "Branches by chance" : "Branches ×" + part.branches().count().summary(); + } + return "Cluster ×" + part.cluster().count().summary(); + } + + private static String shapeName(ProceduralPart part) { + if (part.stem() != null) { + return "Stem"; + } + if (part.blob() != null) { + return "Blob"; + } + return "Group"; + } + + // Carving places no blocks, so it is named to explain why nothing lights up. + private static String detailOf(ProceduralPart part, String role) { + return part.mode() == PartMode.CARVE ? role + " · carve" : role; + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartPattern.java similarity index 70% rename from src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java rename to src/main/java/art/arcane/iris/engine/procedural/part/PartPattern.java index 14413beac..a28c83017 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/crystal/CrystalRole.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartPattern.java @@ -15,11 +15,14 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +package art.arcane.iris.engine.procedural.part; -package art.arcane.iris.engine.object.procedural.crystal; +import com.volmit.config.Desc; -public enum CrystalRole { - BASE, - SHARD, - TIP +@Desc("How a chance is spread over blocks.") +public enum PartPattern { + @Desc("Every block rolls on its own, for an even speckle.") + RANDOM, + @Desc("Smooth noise decides, so blocks come in patches the size of the scale.") + PATCHES } diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java new file mode 100644 index 000000000..ef53618e6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartSection.java @@ -0,0 +1,32 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; + +@Desc("The cross-section of a stem or blob.") +public enum PartSection { + @Desc("A circle.") + ROUND, + @Desc("A square, like a vanilla trunk.") + SQUARE, + @Desc("A diamond (a square turned 45 degrees).") + DIAMOND, + @Desc("A hexagon, like a basalt column.") + HEX +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java new file mode 100644 index 000000000..caed199d6 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartShape.java @@ -0,0 +1,48 @@ +/* + * 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.procedural.part; + +/** A drawn part that others can grow from. */ +interface PartShape { + /** Where a child sitting at {@code t}, from the base (0) to the tip (1), starts. */ + PartSpot spotAt(double t); + + /** The length children measure against, in blocks. */ + double length(); + + /** Where children sit when they do not say. */ + double defaultAt(); + + /** The parent of the object's root parts: a single point at the base, pointing up. */ + PartShape ROOT = new PartShape() { + @Override + public PartSpot spotAt(double t) { + return PartSpot.root(); + } + + @Override + public double length() { + return 0; + } + + @Override + public double defaultAt() { + return 0; + } + }; +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java new file mode 100644 index 000000000..b43384f90 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartSpot.java @@ -0,0 +1,36 @@ +/* + * 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.procedural.part; + +/** + * Where a part starts: its position, the direction it grows, where it sits on its parent from base (0) to tip (1), + * how long that parent is, and the compass direction pointing away from the parent's center (NaN when there is none). + */ +record PartSpot(double[] origin, double[] heading, double parentT, double parentLength, double outward) { + static PartSpot root() { + return new PartSpot(new double[]{0, 0, 0}, Vectors.UP.clone(), 0, 0, Double.NaN); + } + + PartSpot movedBy(double[] offset) { + return new PartSpot(Vectors.add(origin, offset), heading, parentT, parentLength, outward); + } + + boolean hasOutward() { + return !Double.isNaN(outward); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java new file mode 100644 index 000000000..da289a09e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartStem.java @@ -0,0 +1,170 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +@Desc("A line that grows from where the part sits: a trunk, branch, spire, stalk, root or shard. Values given as a curve run over where the stem sits on its parent, except taper, lean curve, bend curve and helix radius, which run from the stem's base (0) to its tip (1).") +public final class PartStem { + @Desc("How long the stem grows, in blocks.") + private ProceduralValue length = ProceduralValue.constant(8); + + @MinNumber(0) + @Desc("If above 0, the stem is this fraction of its parent stem's length instead, for branches that shrink as they split.") + private double lengthScale = 0; + + @Desc("The radius at the base in blocks. 0.5 is one block wide.") + private ProceduralValue radius = ProceduralValue.constant(0.5); + + @Desc("A multiplier on the radius from the base (0) to the tip (1), such as [[0, 1], [1, 0]] to taper to a point.") + private ProceduralValue taper; + + @Desc("The cross-section of the stem.") + private PartSection section = PartSection.ROUND; + + @Desc("The angle in degrees above the horizon the stem grows toward: 90 is straight up, -90 straight down. Unset, it carries on its parent's direction (up for a root part).") + private ProceduralValue pitch; + + @Desc("The compass direction in degrees the stem grows toward when pitch is set. Unset, it keeps its parent's direction, or grows toward its facing.") + private ProceduralValue azimuth; + + @Desc("The compass direction in degrees the stem leans and bends toward. Unset, it leans away from the center of its cluster or branch, or a random way.") + private ProceduralValue facing; + + @Desc("How far the stem leans, in degrees from its direction, by the time it reaches its tip.") + private ProceduralValue lean = ProceduralValue.constant(0); + + @Desc("How the lean builds up from base (0) to tip (1), from 0 to 1. Unset, it grows evenly.") + private ProceduralValue leanCurve; + + @Desc("How far the stem turns, in degrees, by its tip: 90 turns an upright stem sideways, 180 brings it back down like an arch.") + private ProceduralValue bend = ProceduralValue.constant(0); + + @Desc("How the bend builds up from base (0) to tip (1), from 0 to 1. Unset, it turns evenly.") + private ProceduralValue bendCurve; + + @Desc("How much the stem sags under its own weight, as a fraction of its length: 0.2 drops the tip a fifth of the length.") + private ProceduralValue droop = ProceduralValue.constant(0); + + @Desc("How far the stem wanders sideways at random, in blocks.") + private ProceduralValue sway = ProceduralValue.constant(0); + + @Desc("How far the stem waves from side to side, in blocks.") + private ProceduralValue wave = ProceduralValue.constant(0); + + @Desc("How many full waves the stem makes over its length.") + private ProceduralValue wavePeriods = ProceduralValue.constant(1); + + @Desc("The radius in blocks of a corkscrew the stem winds around, from base (0) to tip (1). It starts on the facing side, so copies facing apart wind as a double helix.") + private ProceduralValue helixRadius = ProceduralValue.constant(0); + + @Desc("How many full turns the corkscrew makes over the stem's length.") + private ProceduralValue helixTurns = ProceduralValue.constant(1); + + @MinNumber(0) + @MaxNumber(1) + @Desc("How rough the surface is, from 0 (smooth) to 1 (heavily pitted).") + private double roughness = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("How many blocks along the surface are knocked off at random, from 0 to 1.") + private double jitter = 0; + + public ProceduralValue length() { + return length == null ? ProceduralValue.constant(8) : length; + } + + public double lengthScale() { + return lengthScale; + } + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(0.5) : radius; + } + + public ProceduralValue taper() { + return taper; + } + + public PartSection section() { + return section == null ? PartSection.ROUND : section; + } + + public ProceduralValue pitch() { + return pitch; + } + + public ProceduralValue azimuth() { + return azimuth; + } + + public ProceduralValue facing() { + return facing; + } + + public ProceduralValue lean() { + return lean; + } + + public ProceduralValue leanCurve() { + return leanCurve; + } + + public ProceduralValue bend() { + return bend; + } + + public ProceduralValue bendCurve() { + return bendCurve; + } + + public ProceduralValue droop() { + return droop; + } + + public ProceduralValue sway() { + return sway; + } + + public ProceduralValue wave() { + return wave; + } + + public ProceduralValue wavePeriods() { + return wavePeriods; + } + + public ProceduralValue helixRadius() { + return helixRadius; + } + + public ProceduralValue helixTurns() { + return helixTurns; + } + + public double roughness() { + return roughness; + } + + public double jitter() { + return jitter; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java b/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java new file mode 100644 index 000000000..c64ff5a2b --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/PartTrace.java @@ -0,0 +1,39 @@ +/* + * 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.procedural.part; + +import java.util.Map; + +/** + * Which part placed each block of one baked variant, by the block's position in the variant's object. Decorations + * belong to no part. + */ +public final class PartTrace { + public static final PartTrace EMPTY = new PartTrace(Map.of()); + + private final Map partsByBlock; + + PartTrace(Map partsByBlock) { + this.partsByBlock = partsByBlock; + } + + /** The {@link PartOutline} id of the part that placed the block, or {@link PartOutline#NO_PART}. */ + public int partAt(int x, int y, int z) { + return partsByBlock.getOrDefault(PartCanvas.key(x, y, z), PartOutline.NO_PART); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java new file mode 100644 index 000000000..1cd6223ba --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java @@ -0,0 +1,96 @@ +/* + * 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.procedural.part; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.MinItems; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; + +import java.util.Collections; +import java.util.List; + +@Desc("Blocks placed against the finished object, such as vines, moss, fruit or lanterns. Vines and lichen attach to the block they touch.") +public final class ProceduralDecoration { + @Ref(Reference.BLOCK) + @Desc("The block to place. Ignored when palette is set.") + private String block = "minecraft:vine"; + + @Desc("A noise palette to place.") + private PaletteSpec palette; + + @MinItems(1) + @Desc("The roles to decorate. Empty decorates every block.") + private List on = List.of(); + + @Desc("Where on those blocks to place it.") + private DecorationSpot at = DecorationSpot.SIDE; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The chance each spot gets one.") + private double chance = 0.3; + + @Desc("How the chance is spread over the spots.") + private PartPattern pattern = PartPattern.RANDOM; + + @MinNumber(1) + @Desc("The size of the patches in blocks for the PATCHES pattern.") + private double scale = 3; + + @Desc("How many blocks long a strand hangs for BELOW and BOTTOM.") + private ProceduralValue length = ProceduralValue.constant(1); + + @Desc("How far from where the object stands GROUND decorations spread, in blocks.") + private ProceduralValue radius = ProceduralValue.constant(3); + + public BlockChoice choice() { + return new BlockChoice(block, palette, 0); + } + + public List on() { + return on == null ? List.of() : Collections.unmodifiableList(on); + } + + public DecorationSpot at() { + return at == null ? DecorationSpot.SIDE : at; + } + + public double chance() { + return chance; + } + + public PartPattern pattern() { + return pattern == null ? PartPattern.RANDOM : pattern; + } + + public double scale() { + return scale; + } + + public ProceduralValue length() { + return length == null ? ProceduralValue.constant(1) : length; + } + + public ProceduralValue radius() { + return radius == null ? ProceduralValue.constant(3) : radius; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java new file mode 100644 index 000000000..a21611c28 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java @@ -0,0 +1,63 @@ +/* + * 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.procedural.part; + +import com.volmit.block.PaletteSpec; +import com.volmit.config.MinItems; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; + +import java.util.Collections; +import java.util.List; + +@Desc("The blocks of one role. Logs are turned along the part they belong to, and leaves get decay distances.") +public final class ProceduralMaterial { + @Required + @Desc("The role the parts refer to, such as wood, leaves, rock or cap.") + private String role = "main"; + + @Ref(Reference.BLOCK) + @Desc("The block. Ignored when palette is set.") + private String block = "minecraft:stone"; + + @Desc("A noise palette mixing several blocks.") + private PaletteSpec palette; + + @MinNumber(0) + @Desc("If above 0, the palette changes every this many blocks of height, for strata.") + private int bands = 0; + + @MinItems(1) + @Desc("Swaps for blocks that meet conditions; the first rule that applies wins.") + private List rules = List.of(); + + public String role() { + return role == null ? "main" : role; + } + + public BlockChoice choice() { + return new BlockChoice(block, palette, bands); + } + + public List rules() { + return rules == null ? List.of() : Collections.unmodifiableList(rules); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java new file mode 100644 index 000000000..34f231309 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java @@ -0,0 +1,98 @@ +/* + * 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.procedural.part; + +import com.volmit.config.MinItems; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +import java.util.Collections; +import java.util.List; + +@Desc("A procedural object built from parts: stems, blobs, branches and clusters, each placing blocks of a role. Anything from a tree to a rock arch to a crystal-studded boulder. Iris bakes a pool of variants from it once. Place it from any object placement as procedural/, or a single variant as procedural/#.") +public final class ProceduralObject { + @MinNumber(1) + @MaxNumber(64) + @Desc("How many different variants to bake. More means more variety for a little memory.") + private int variants = 6; + + @Desc("The seed every variant is baked from. The same seed and settings always bake the same variants.") + private long seed = 1337; + + + @MinItems(1) + @Desc("The blocks of each role. A part whose role has no material uses the first one.") + private List materials = List.of(); + + @MinItems(1) + @Desc("The parts the object grows from, each starting at the object's base.") + private List parts = List.of(); + + @MinItems(1) + @Desc("Blocks placed against the finished object, such as vines, moss or fruit.") + private List decorations = List.of(); + + @Desc("If true leaves get the distances from wood vanilla needs to keep them. Leaves more than 6 blocks from wood are made persistent; the object view in /iris studio map shows them. If false all leaves are persistent.") + private boolean leafDecay = true; + + @Desc("If true every block that can hold water is waterlogged, so coral stays alive.") + private boolean waterlogged = false; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Sinks the object into the ground by this fraction of its height.") + private double sink = 0; + + public int variants() { + return variants; + } + + public long seed() { + return seed; + } + + public List materials() { + return materials == null ? List.of() : Collections.unmodifiableList(materials); + } + + /** The role of a root part that sets none: the first material's. */ + public String defaultRole() { + return materials().isEmpty() ? "main" : materials().getFirst().role(); + } + + public List parts() { + return parts == null ? List.of() : Collections.unmodifiableList(parts); + } + + public List decorations() { + return decorations == null ? List.of() : Collections.unmodifiableList(decorations); + } + + public boolean leafDecay() { + return leafDecay; + } + + public boolean waterlogged() { + return waterlogged; + } + + public double sink() { + return sink; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java new file mode 100644 index 000000000..814e67fd9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java @@ -0,0 +1,127 @@ +/* + * 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.procedural.part; + +import com.volmit.config.MinItems; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Snippet; + +import java.util.Collections; +import java.util.List; + +@Snippet("iris/objects/procedural-part") +@Desc("One piece of a procedural object. Set exactly one of stem, blob, branches or cluster; children grow from this part.") +public final class ProceduralPart { + @Desc("The role of the blocks this part places, matching a material's role, such as wood or leaves. Unset, it takes its parent's role.") + private String role; + + @Desc("Where on its parent this part sits, from the base (0) to the tip (1). Unset, it sits at the tip of a stem or the top of a blob.") + private ProceduralValue at; + + @Desc("Moves this part from where it sits, in blocks.") + private PartOffset offset; + + @Desc("How this part's blocks combine with the blocks earlier parts placed.") + private PartMode mode = PartMode.ADD; + + @MinNumber(0) + @MaxNumber(1) + @Desc("The fraction of this part's blocks that are placed, for sparse leaves or eroded carving.") + private double density = 1; + + @Desc("How the density is spread over the blocks.") + private PartPattern pattern = PartPattern.RANDOM; + + @MinNumber(1) + @Desc("The size of the patches in blocks for the PATCHES pattern.") + private double scale = 3; + + @MinNumber(0) + @Desc("Thins the blocks toward the edge of the shape: 1 thins evenly, 2 keeps a dense core.") + private double falloff = 0; + + @Desc("A line that grows from here: a trunk, branch, spire, stalk or shard.") + private PartStem stem; + + @Desc("A rounded volume: a leaf crown, boulder, cap or coral head.") + private PartBlob blob; + + @Desc("Copies of a part grown out of this part's parent along its length.") + private PartBranches branches; + + @Desc("Copies of a part placed around this spot.") + private PartCluster cluster; + + @MinItems(1) + @Desc("The parts that grow from this one.") + private List children = List.of(); + + public String role() { + return role; + } + + public ProceduralValue at() { + return at; + } + + public PartOffset offset() { + return offset; + } + + public PartMode mode() { + return mode == null ? PartMode.ADD : mode; + } + + public double density() { + return density; + } + + public PartPattern pattern() { + return pattern == null ? PartPattern.RANDOM : pattern; + } + + public double scale() { + return scale; + } + + public double falloff() { + return falloff; + } + + public PartStem stem() { + return stem; + } + + public PartBlob blob() { + return blob; + } + + public PartBranches branches() { + return branches; + } + + public PartCluster cluster() { + return cluster; + } + + public List children() { + return children == null ? List.of() : Collections.unmodifiableList(children); + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java new file mode 100644 index 000000000..417d46d19 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralSpan.java @@ -0,0 +1,55 @@ +/* + * 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.procedural.part; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; + +@Desc("A stretch between two points from 0 to 1, such as from the base (0) to the tip (1) of a part.") +public final class ProceduralSpan { + @MinNumber(0) + @MaxNumber(1) + @Desc("Where the stretch starts.") + private double from = 0; + + @MinNumber(0) + @MaxNumber(1) + @Desc("Where the stretch ends.") + private double to = 1; + + public ProceduralSpan() { + } + + public ProceduralSpan(double from, double to) { + this.from = from; + this.to = to; + } + + public double from() { + return Math.min(from, to); + } + + public double to() { + return Math.max(from, to); + } + + public boolean contains(double t) { + return t >= from() - 1e-9 && t <= to() + 1e-9; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java new file mode 100644 index 000000000..1aa8688be --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralValue.java @@ -0,0 +1,299 @@ +/* + * 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.procedural.part; + +import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Desc; +import com.volmit.config.JsonForms; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * A number a pack author may write as a constant ({@code 5}), a random range ({@code [3, 8]} or + * {@code {"min": 3, "max": 8}}), a curve of keyframes ({@code [[0, 1], [0.6, 0.8], [1, 0.2]]}) or a named curve + * ({@code {"shape": "power", "exponent": 3, "from": 0, "to": 1}}). Each field says what a curve runs over. + */ +@Desc("A number, a [min, max] range rolled once per use, or a curve: [[t, value], ...] keyframes or {\"shape\": ..., \"from\": ..., \"to\": ...}.") +@JsonForms(ProceduralValue.Forms.class) +public final class ProceduralValue { + private final Object written; + private final Form form; + + private ProceduralValue(Object written, Form form) { + this.written = written; + this.form = form; + } + + public static ProceduralValue constant(double value) { + return new ProceduralValue(value, new Constant(value)); + } + + public static ProceduralValue range(double min, double max) { + return new ProceduralValue(List.of(min, max), new Range(min, max)); + } + + /** This value with any range rolled once, so a curve or constant is all that is left. */ + public ProceduralValue fix(RNG rng) { + if (form instanceof Range range) { + return constant(range.roll(rng)); + } + return this; + } + + /** The value at {@code t}, from 0 to 1; a range gives its middle, so fix it first to roll it. */ + public double at(double t) { + return form.at(Math.max(0, Math.min(1, t))); + } + + /** The value at {@code t}, with a range rolled with {@code rng}. */ + public double sample(RNG rng, double t) { + return fix(rng).at(t); + } + + public boolean isCurve() { + return form instanceof Keyframes || form instanceof Shape; + } + + /** A short reading of the value for labels: {@code 12}, {@code 4–9} or {@code curve}. */ + public String summary() { + return switch (form) { + case Constant constant -> shortNumber(constant.value()); + case Range range -> shortNumber(range.min()) + "–" + shortNumber(range.max()); + case Keyframes ignored -> "curve"; + case Shape ignored -> "curve"; + }; + } + + private static String shortNumber(double value) { + return value == Math.rint(value) ? Long.toString((long) value) : String.format(Locale.ROOT, "%.4g", value).replaceAll("\\.?0+$", ""); + } + + @Override + public String toString() { + return written.toString(); + } + + private sealed interface Form permits Constant, Range, Keyframes, Shape { + double at(double t); + } + + private record Constant(double value) implements Form { + @Override + public double at(double t) { + return value; + } + } + + private record Range(double min, double max) implements Form { + double roll(RNG rng) { + return min == max ? min : rng.d(Math.min(min, max), Math.max(min, max)); + } + + @Override + public double at(double t) { + return (min + max) / 2; + } + } + + private record Keyframes(double[] times, double[] values) implements Form { + @Override + public double at(double t) { + if (t <= times[0]) { + return values[0]; + } + for (int i = 1; i < times.length; i++) { + if (t <= times[i]) { + double span = times[i] - times[i - 1]; + double blend = span <= 0 ? 1 : (t - times[i - 1]) / span; + return values[i - 1] + (values[i] - values[i - 1]) * blend; + } + } + return values[values.length - 1]; + } + } + + private record Shape(CurveShape shape, double from, double to, Map parameters) implements Form { + @Override + public double at(double t) { + return from + (to - from) * shape.at(t, parameters); + } + } + + /** The named curves, each running from 0 at t = 0 toward 1, stretched between a value's from and to. */ + public enum CurveShape { + LINEAR(List.of()) { + @Override + double at(double t, Map p) { + return t; + } + }, + SMOOTH(List.of()) { + @Override + double at(double t, Map p) { + return t * t * (3 - 2 * t); + } + }, + POWER(List.of(new Parameter("exponent", 2))) { + @Override + double at(double t, Map p) { + return Math.pow(t, parameter(p, "exponent")); + } + }, + SIGMOID(List.of(new Parameter("steepness", 10), new Parameter("mid", 0.5))) { + @Override + double at(double t, Map p) { + return 1 / (1 + Math.exp(-parameter(p, "steepness") * (t - parameter(p, "mid")))); + } + }, + BELL(List.of(new Parameter("mid", 0.5), new Parameter("width", 0.15))) { + @Override + double at(double t, Map p) { + double spread = Math.max(1e-6, parameter(p, "width")); + return Math.exp(-0.5 * Math.pow((t - parameter(p, "mid")) / spread, 2)); + } + }, + PERIODIC(List.of(new Parameter("periods", 4), new Parameter("sharpness", 8))) { + @Override + double at(double t, Map p) { + double wave = Math.max(0, Math.sin(2 * Math.PI * t * parameter(p, "periods"))); + return Math.pow(wave, parameter(p, "sharpness")); + } + }, + SINE(List.of(new Parameter("periods", 1))) { + @Override + double at(double t, Map p) { + return 0.5 + 0.5 * Math.sin(2 * Math.PI * t * parameter(p, "periods")); + } + }; + + private final List parameters; + + CurveShape(List parameters) { + this.parameters = parameters; + } + + abstract double at(double t, Map parameters); + + /** What shapes this curve beyond its from and to, each with the value it has unless the curve sets it. */ + public List parameters() { + return parameters; + } + + /** As a value writes it, like {@code power}. */ + public String key() { + return name().toLowerCase(Locale.ROOT); + } + + final double parameter(Map written, String name) { + if (written.containsKey(name)) { + return Forms.number(written.get(name), name); + } + return parameters.stream().filter(parameter -> parameter.name().equals(name)).findFirst().orElseThrow().fallback(); + } + + public record Parameter(String name, double fallback) { + } + } + + /** Reads the forms a pack writes and writes a value back exactly as it was read. */ + static final class Forms implements JsonForms.Codec { + private static final String SHAPE = "shape"; + private static final String MIN = "min"; + private static final String MAX = "max"; + private static final String FROM = "from"; + private static final String TO = "to"; + private static final double DEFAULT_FROM = 0; + private static final double DEFAULT_TO = 1; + + @Override + public ProceduralValue read(Object json) { + return new ProceduralValue(json, formOf(json)); + } + + @Override + public Object write(ProceduralValue value) { + return value.written; + } + + private static Form formOf(Object json) { + return switch (json) { + case Number number -> new Constant(number.doubleValue()); + case List list -> listForm(list); + case Map object when object.containsKey(SHAPE) -> shapeForm(object); + case Map object when object.containsKey(MIN) && object.containsKey(MAX) -> + new Range(number(object.get(MIN), MIN), number(object.get(MAX), MAX)); + case Map object -> throw new IllegalArgumentException("A value needs min and max, or a shape: " + object); + default -> throw new IllegalArgumentException("A value is a number, a [min, max] range or a curve, not " + json); + }; + } + + private static Form listForm(List list) { + if (list.isEmpty()) { + throw new IllegalArgumentException("A value can not be an empty list"); + } + if (list.getFirst() instanceof Number) { + if (list.size() != 2) { + throw new IllegalArgumentException("A range is written [min, max]: " + list); + } + return new Range(number(list.get(0), MIN), number(list.get(1), MAX)); + } + return keyframes(list); + } + + private static Form keyframes(List list) { + List keys = new ArrayList<>(); + for (Object key : list) { + if (!(key instanceof List pair) || pair.size() != 2) { + throw new IllegalArgumentException("A keyframe is written [t, value]: " + key); + } + keys.add(new double[]{number(pair.get(0), "t"), number(pair.get(1), "value")}); + } + keys.sort((a, b) -> Double.compare(a[0], b[0])); + double[] times = new double[keys.size()]; + double[] values = new double[keys.size()]; + for (int i = 0; i < keys.size(); i++) { + times[i] = keys.get(i)[0]; + values[i] = keys.get(i)[1]; + } + return new Keyframes(times, values); + } + + private static Form shapeForm(Map object) { + String name = String.valueOf(object.get(SHAPE)).toUpperCase(Locale.ROOT); + CurveShape shape; + try { + shape = CurveShape.valueOf(name); + } catch (IllegalArgumentException unknown) { + throw new IllegalArgumentException("Unknown curve shape " + name.toLowerCase(Locale.ROOT)); + } + double from = object.containsKey(FROM) ? number(object.get(FROM), FROM) : DEFAULT_FROM; + double to = object.containsKey(TO) ? number(object.get(TO), TO) : DEFAULT_TO; + return new Shape(shape, from, to, object); + } + + static double number(Object written, String name) { + if (written instanceof Number number) { + return number.doubleValue(); + } + throw new IllegalArgumentException(name + " needs a number, not " + written); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java b/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java new file mode 100644 index 000000000..6e5f5e0a4 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ResolvedProceduralObject.java @@ -0,0 +1,56 @@ +/* + * 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.procedural.part; + +import art.arcane.iris.engine.procedural.BakeProfile; +import art.arcane.iris.engine.procedural.ProceduralShape; +import art.arcane.iris.engine.procedural.ProceduralVariants; +import art.arcane.iris.modules.objects.ObjectBuilder; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; + +/** The variants of a procedural object, baked by {@link ObjectBaker}. */ +public final class ResolvedProceduralObject extends ProceduralVariants { + private final ProceduralObject definition; + private final PartOutline outline; + + public ResolvedProceduralObject(String path, ProceduralObject definition, PackResources resources) { + super(path, definition.seed(), definition.variants(), resources); + this.definition = definition; + this.outline = PartOutline.of(definition); + } + + @Override + protected ProceduralShape generate(int index, RNG rng, ObjectBuilder blocks, BakeProfile profile) { + return ObjectBaker.bake(definition, outline, rng, blocks, profile); + } + + public PartOutline outline() { + return outline; + } + + /** Which part placed each block of {@code variant}, baked again to find out; empty when it is not one of these. */ + public PartTrace trace(PlaceableObject variant) { + int index = bakeIndexOf(variant); + if (index < 0) { + return PartTrace.EMPTY; + } + return ObjectBaker.trace(definition, outline, variantRng(index), newBuilder()); + } +} diff --git a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java b/src/main/java/art/arcane/iris/engine/procedural/part/RuleFace.java similarity index 69% rename from src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java rename to src/main/java/art/arcane/iris/engine/procedural/part/RuleFace.java index 2dac80c8c..c4adeb49a 100644 --- a/src/main/java/art/arcane/iris/engine/object/procedural/fungi/FungusCellRole.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/RuleFace.java @@ -15,12 +15,18 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ +package art.arcane.iris.engine.procedural.part; -package art.arcane.iris.engine.object.procedural.fungi; +import com.volmit.config.Desc; -enum FungusCellRole { - STEM, - CAP, - GILL, - SPOT +@Desc("Which open side a block needs for a material rule to apply to it.") +public enum RuleFace { + @Desc("Any side open to the air.") + ANY, + @Desc("Open above.") + UP, + @Desc("Open below.") + DOWN, + @Desc("Open on a horizontal side.") + SIDE } diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/Sections.java b/src/main/java/art/arcane/iris/engine/procedural/part/Sections.java new file mode 100644 index 000000000..ef25078a8 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/Sections.java @@ -0,0 +1,37 @@ +/* + * 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.procedural.part; + +/** How far a point is from the center of a cross-section, in the section's own measure, so 1 is on its edge at radius 1. */ +final class Sections { + private static final double HEX_SLANT = Math.sqrt(3) / 2; + + private Sections() { + } + + static double norm(PartSection section, double u, double w) { + double au = Math.abs(u); + double aw = Math.abs(w); + return switch (section) { + case ROUND -> Math.sqrt(u * u + w * w); + case SQUARE -> Math.max(au, aw); + case DIAMOND -> au + aw; + case HEX -> Math.max(aw, au * HEX_SLANT + aw * 0.5); + }; + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java b/src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java new file mode 100644 index 000000000..d9040a79e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/StemShape.java @@ -0,0 +1,243 @@ +/* + * 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.procedural.part; + +import art.arcane.volmlib.util.math.RNG; + +/** + * A stem traced as a path of closely spaced samples, each with a center, a direction and a radius, then swept into + * blocks: one block per sample while it is thin, a slice of its cross-section once it is thicker. + */ +final class StemShape implements PartShape { + static final double LONGEST_BLOCKS = 256; + private static final double SAMPLE_SPACING_BLOCKS = 0.25; + private static final double THIN_RADIUS_BLOCKS = 0.5; + private static final double SWAY_FREQUENCY = 0.35; + + private final double length; + private final double[][] centers; + private final double[][] headings; + private final double[] radii; + private final double outward; + + private StemShape(double length, double[][] centers, double[][] headings, double[] radii, double outward) { + this.length = length; + this.centers = centers; + this.headings = headings; + this.radii = radii; + this.outward = outward; + } + + /** Traces the stem from {@code spot} without placing anything. */ + static StemShape trace(PartStem stem, PartSpot spot, RNG rng) { + double length = stemLength(stem, spot, rng); + double baseRadius = Math.max(0, stem.radius().sample(rng, spot.parentT())); + ProceduralValue taper = stem.taper() == null ? null : stem.taper().fix(rng); + double facing = stem.facing() != null ? stem.facing().sample(rng, spot.parentT()) + : spot.hasOutward() ? spot.outward() : rng.d(0, 360); + double[] heading = startHeading(stem, spot, facing, rng); + double[] toward = Vectors.across(heading, Vectors.direction(facing, 0)); + double[] beside = Vectors.normalize(Vectors.cross(heading, toward), toward); + + Bends bends = Bends.of(stem, spot, rng, length); + double pathLength = Math.max(0, length - 1); + int steps = Math.max(2, (int) Math.ceil(pathLength / SAMPLE_SPACING_BLOCKS)); + double step = pathLength / steps; + double[][] centers = new double[steps + 1][]; + double[] radii = new double[steps + 1]; + double[] base = spot.origin().clone(); + for (int i = 0; i <= steps; i++) { + double t = i / (double) steps; + if (i > 0) { + double middle = (i - 0.5) / steps; + base = Vectors.addScaled(base, bends.heading(heading, toward, middle), step); + } + centers[i] = Vectors.add(base, bends.offset(toward, beside, t, pathLength)); + radii[i] = baseRadius * (taper == null ? 1 : Math.max(0, taper.at(t))); + } + return new StemShape(length, centers, directions(centers, heading), radii, facing); + } + + /** Places the stem's blocks and records its tip. */ + void draw(PartFill fill, PartSection section, double roughness, double jitter) { + for (int i = 0; i < centers.length; i++) { + double t = i / (double) (centers.length - 1); + PartCanvas.Axis axis = PartCanvas.Axis.along(headings[i]); + if (radii[i] <= THIN_RADIUS_BLOCKS && roughness <= 0) { + fill.place(round(centers[i][0]), round(centers[i][1]), round(centers[i][2]), 0, t, axis); + continue; + } + sweepSlice(fill, i, t, axis, section, roughness, jitter); + } + double[] tip = centers[centers.length - 1]; + fill.canvas().addTip(new PartCanvas.Tip(round(tip[0]), round(tip[1]), round(tip[2]), headings[headings.length - 1], fill.role())); + } + + private void sweepSlice(PartFill fill, int index, double t, PartCanvas.Axis axis, PartSection section, double roughness, double jitter) { + double[] center = centers[index]; + double[] heading = headings[index]; + double radius = Math.max(THIN_RADIUS_BLOCKS, radii[index]); + double[] across = Vectors.across(heading, new double[]{1, 0, 0}); + double[] beside = Vectors.cross(heading, across); + double slab = SAMPLE_SPACING_BLOCKS * 0.5 + 0.5; + boolean first = index == 0; + boolean last = index == centers.length - 1; + int squareWidth = Math.max(1, (int) Math.round(radius * 2)); + double squareShift = section == PartSection.SQUARE && squareWidth % 2 == 0 ? 0.5 : 0; + int reach = (int) Math.ceil(radius * (1 + roughness) + 1.5); + int cx = round(center[0]); + int cy = round(center[1]); + int cz = round(center[2]); + for (int x = cx - reach; x <= cx + reach; x++) { + for (int y = cy - reach; y <= cy + reach; y++) { + for (int z = cz - reach; z <= cz + reach; z++) { + double[] offset = {x - center[0], y - center[1], z - center[2]}; + double axial = Vectors.dot(offset, heading); + if (Math.abs(axial) > slab || (first && axial < -0.5) || (last && axial > 0.5)) { + continue; + } + double[] radial = Vectors.addScaled(offset, heading, -axial); + double u = Vectors.dot(radial, across) - squareShift; + double w = Vectors.dot(radial, beside) - squareShift; + double limit = section == PartSection.SQUARE ? squareWidth / 2.0 : radius; + double edge = Sections.norm(section, u, w); + if (roughness > 0) { + limit += (PartNoise.hash(x, y, z, fill.seed() + 9001L) - 0.5) * roughness * (radius + 1); + } + boolean core = x == cx && y == cy && z == cz; + if (!core && edge > limit) { + continue; + } + if (!core && jitter > 0 && edge > limit - 1 && PartNoise.hash(x, y, z, fill.seed() + 77L) < jitter * 0.5) { + continue; + } + fill.place(x, y, z, Math.min(edge, limit) / (limit + 1), t, axis); + } + } + } + } + + @Override + public PartSpot spotAt(double t) { + double position = Math.max(0, Math.min(1, t)) * (centers.length - 1); + int index = (int) Math.floor(position); + int next = Math.min(centers.length - 1, index + 1); + double blend = position - index; + double[] center = Vectors.add(Vectors.scale(centers[index], 1 - blend), Vectors.scale(centers[next], blend)); + double[] heading = headings[index]; + double outwardHere = Vectors.isVertical(heading) ? outward : Vectors.azimuth(heading); + return new PartSpot(center, heading.clone(), t, length, outwardHere); + } + + @Override + public double length() { + return length; + } + + @Override + public double defaultAt() { + return 1; + } + + private static double stemLength(PartStem stem, PartSpot spot, RNG rng) { + double length = stem.lengthScale() > 0 && spot.parentLength() > 0 + ? spot.parentLength() * stem.lengthScale() + : stem.length().sample(rng, spot.parentT()); + return Math.max(1, Math.min(LONGEST_BLOCKS, length)); + } + + private static double[] startHeading(PartStem stem, PartSpot spot, double facing, RNG rng) { + if (stem.pitch() == null && stem.azimuth() == null) { + return spot.heading().clone(); + } + double pitch = stem.pitch() != null ? stem.pitch().sample(rng, spot.parentT()) : Vectors.pitch(spot.heading()); + double azimuth = stem.azimuth() != null ? stem.azimuth().sample(rng, spot.parentT()) + : Vectors.isVertical(spot.heading()) ? facing : Vectors.azimuth(spot.heading()); + return Vectors.direction(azimuth, pitch); + } + + /** The direction at each sample, from its neighbors, so offsets such as lean and corkscrew turn the slices too. */ + private static double[][] directions(double[][] centers, double[] fallback) { + double[][] headings = new double[centers.length][]; + for (int i = 0; i < centers.length; i++) { + double[] before = centers[Math.max(0, i - 1)]; + double[] after = centers[Math.min(centers.length - 1, i + 1)]; + headings[i] = Vectors.normalize(Vectors.subtract(after, before), i > 0 ? headings[i - 1] : fallback); + } + return headings; + } + + private static int round(double value) { + return (int) Math.round(value); + } + + /** Everything that pulls a stem off a straight line, rolled once per stem. */ + private record Bends(double leanTangent, ProceduralValue leanCurve, double bendRadians, ProceduralValue bendCurve, + double droop, double sway, double wave, double wavePeriods, double wavePhase, + ProceduralValue helixRadius, double helixTurns, long swaySeed) { + static Bends of(PartStem stem, PartSpot spot, RNG rng, double length) { + double t = spot.parentT(); + double lean = Math.max(-85, Math.min(85, sample(stem.lean(), rng, t))); + return new Bends(Math.tan(Math.toRadians(lean)), fixed(stem.leanCurve(), rng), + Math.toRadians(sample(stem.bend(), rng, t)), fixed(stem.bendCurve(), rng), + sample(stem.droop(), rng, t), sample(stem.sway(), rng, t), + sample(stem.wave(), rng, t), sample(stem.wavePeriods(), rng, t), rng.d(0, Math.PI * 2), + fixed(stem.helixRadius(), rng), sample(stem.helixTurns(), rng, t), rng.nextLong()); + } + + double[] heading(double[] start, double[] toward, double t) { + if (bendRadians == 0) { + return start; + } + double angle = bendRadians * progress(bendCurve, t); + return Vectors.add(Vectors.scale(start, Math.cos(angle)), Vectors.scale(toward, Math.sin(angle))); + } + + double[] offset(double[] toward, double[] beside, double t, double pathLength) { + double[] offset = Vectors.scale(toward, pathLength * leanTangent * progress(leanCurve, t)); + offset[1] -= droop * pathLength * t * t; + double helix = helixRadius == null ? 0 : helixRadius.at(t); + if (helix != 0) { + double angle = Math.PI * 2 * helixTurns * t; + offset = Vectors.addScaled(offset, toward, Math.cos(angle) * helix); + offset = Vectors.addScaled(offset, beside, Math.sin(angle) * helix); + } + if (wave != 0) { + offset = Vectors.addScaled(offset, beside, wave * Math.sin(Math.PI * 2 * wavePeriods * t + wavePhase)); + } + if (sway != 0) { + double along = t * pathLength * SWAY_FREQUENCY; + offset = Vectors.addScaled(offset, toward, sway * (PartNoise.line(along, swaySeed) * 2 - 1)); + offset = Vectors.addScaled(offset, beside, sway * (PartNoise.line(along, swaySeed + 1) * 2 - 1)); + } + return offset; + } + + private static double progress(ProceduralValue curve, double t) { + return curve == null ? t : curve.at(t); + } + + private static double sample(ProceduralValue value, RNG rng, double t) { + return value == null ? 0 : value.sample(rng, t); + } + + private static ProceduralValue fixed(ProceduralValue value, RNG rng) { + return value == null ? null : value.fix(rng); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java b/src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java new file mode 100644 index 000000000..06b044985 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/procedural/part/Vectors.java @@ -0,0 +1,96 @@ +/* + * 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.procedural.part; + +/** Small vector maths on {@code double[3]}, with compass azimuths measured from south (+z) toward east (+x). */ +final class Vectors { + static final double[] UP = {0, 1, 0}; + + private Vectors() { + } + + /** The unit direction {@code azimuth} degrees around the compass and {@code pitch} degrees above the horizon. */ + static double[] direction(double azimuth, double pitch) { + double a = Math.toRadians(azimuth); + double p = Math.toRadians(pitch); + return new double[]{Math.cos(p) * Math.sin(a), Math.sin(p), Math.cos(p) * Math.cos(a)}; + } + + static double azimuth(double[] direction) { + return Math.toDegrees(Math.atan2(direction[0], direction[2])); + } + + static double pitch(double[] direction) { + return Math.toDegrees(Math.asin(Math.max(-1, Math.min(1, direction[1])))); + } + + static boolean isVertical(double[] direction) { + return Math.abs(direction[1]) > 0.999; + } + + static double[] add(double[] a, double[] b) { + return new double[]{a[0] + b[0], a[1] + b[1], a[2] + b[2]}; + } + + static double[] subtract(double[] a, double[] b) { + return new double[]{a[0] - b[0], a[1] - b[1], a[2] - b[2]}; + } + + static double[] scale(double[] a, double factor) { + return new double[]{a[0] * factor, a[1] * factor, a[2] * factor}; + } + + static double[] addScaled(double[] a, double[] b, double factor) { + return new double[]{a[0] + b[0] * factor, a[1] + b[1] * factor, a[2] + b[2] * factor}; + } + + static double dot(double[] a, double[] b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + + static double[] cross(double[] a, double[] b) { + return new double[]{a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]}; + } + + static double length(double[] a) { + return Math.sqrt(dot(a, a)); + } + + /** {@code a} scaled to length 1; {@code fallback} when it has no length. */ + static double[] normalize(double[] a, double[] fallback) { + double length = length(a); + return length < 1e-9 ? fallback.clone() : scale(a, 1 / length); + } + + /** The unit vector across {@code axis} that points most toward {@code toward}; any across one when they line up. */ + static double[] across(double[] axis, double[] toward) { + double[] flattened = subtract(toward, scale(axis, dot(toward, axis))); + if (length(flattened) > 1e-6) { + return normalize(flattened, UP); + } + double[] reference = Math.abs(axis[0]) < 0.9 ? new double[]{1, 0, 0} : new double[]{0, 0, 1}; + return normalize(subtract(reference, scale(axis, dot(reference, axis))), UP); + } + + /** {@code direction} turned {@code degrees} toward {@code azimuth}, for leaning something away from where it points. */ + static double[] tilted(double[] direction, double azimuth, double degrees) { + double[] toward = across(direction, direction(azimuth, 0)); + double angle = Math.toRadians(degrees); + return normalize(add(scale(direction, Math.cos(angle)), scale(toward, Math.sin(angle))), direction); + } +} diff --git a/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java b/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java index f4dbbab50..68cb05bda 100644 --- a/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java +++ b/src/main/java/art/arcane/iris/modules/objects/EffectiveSettings.java @@ -19,30 +19,15 @@ package art.arcane.iris.modules.objects; import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.objects.PlacementSource; import art.arcane.iris.builtin.prepare.AxisRotationClamp; import art.arcane.iris.builtin.prepare.ObjectRotation; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * The object placement settings a placement is made with: an object placement's own, or the options a procedural object - * is scattered with, with the changes {@code iris:objects} makes for where it places them. One per world, so each - * procedural object's options are made once. - */ +/** The object placement settings a placement is made with: its own, with the changes {@code iris:objects} makes for where it places them. */ public final class EffectiveSettings { private static final double UPSIDE_DOWN_TURN_DEGREES = 180D; private static final double QUARTER_TURN_DEGREES = 90D; - private final Map proceduralOptions = new ConcurrentHashMap<>(); - - /** The settings {@code placement} places with, with {@code changes} made to a copy of them. */ - public ObjectPlacement of(PlacementSource placement, PlacementChanges changes) { - ObjectPlacement base = placement instanceof ObjectPlacement settings - ? settings - : proceduralOptions.computeIfAbsent((ProceduralPlacement) placement, EffectiveSettings::optionsOf); - return withChanges(base, changes); + private EffectiveSettings() { } /** {@code base} with {@code changes} made to a copy of it; {@code base} itself when there are none. */ @@ -75,23 +60,6 @@ public final class EffectiveSettings { return changed.build(); } - /** The options a procedural object is scattered with, as an object placement. */ - private static ObjectPlacement optionsOf(ProceduralPlacement procedural) { - return ObjectPlacement.builder() - .mode(procedural.mode()) - .rotation(procedural.rotation()) - .clamp(procedural.clamp()) - .carvingSupport(procedural.carvingSupport()) - .underwater(procedural.underwater()) - .translate(procedural.translate()) - .stiltSettings(procedural.stiltSettings().orElse(null)) - .vacuumSettings(procedural.vacuumSettings().orElse(null)) - .chance(procedural.chance()) - .density(procedural.density()) - .surfaceSupportBuffer(procedural.surfaceSupportBuffer()) - .build(); - } - private static ObjectRotation upsideDownRotation() { return ObjectRotation.of(true, AxisRotationClamp.of(true, true, UPSIDE_DOWN_TURN_DEGREES, UPSIDE_DOWN_TURN_DEGREES, QUARTER_TURN_DEGREES), diff --git a/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java b/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java index 7fd89c85a..dc0cb9cc7 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java @@ -20,6 +20,7 @@ package art.arcane.iris.modules.objects; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import com.volmit.block.PaletteSpec; import com.volmit.object.ObjectBlock; import com.volmit.object.PackObjects; @@ -51,6 +52,11 @@ public final class ObjectBuilder { return blocks.palette(palette, seed).at(x, y, z); } + /** Whether the platform gives {@code state} the trait, such as a log or air. */ + public boolean has(BlockState state, BlockTrait trait) { + return blocks.hasTrait(state, trait); + } + /** {@code state} with the property set, as the platform sets it. */ public BlockState withProperty(BlockState state, String name, String value) { return blocks.withProperty(state, name, value); diff --git a/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java b/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java index ec6d049c9..014b5ef01 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java @@ -22,6 +22,7 @@ import art.arcane.iris.builtin.LegacyStreams; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectScale; import art.arcane.iris.builtin.objects.ScaleInterpolation; +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.volmlib.util.math.RNG; import com.volmit.object.PackObjects; import com.volmit.object.PlaceableObject; @@ -42,15 +43,17 @@ public final class ObjectPool { private final PackResources resources; private final LegacyStreams streams; + private final ProceduralObjectCatalog procedural; - private ObjectPool(PackResources resources, LegacyStreams streams) { + private ObjectPool(PackResources resources, LegacyStreams streams, ProceduralObjectCatalog procedural) { this.resources = resources; this.streams = streams; + this.procedural = procedural; } - /** The objects of {@code world}'s pack. */ + /** The objects of {@code world}'s pack, its procedural objects among them. */ public static ObjectPool of(PackWorld world) { - return new ObjectPool(world.resources(), world.extension(LegacyStreams.class).orElseThrow()); + return new ObjectPool(world.resources(), world.extension(LegacyStreams.class).orElseThrow(), ProceduralObjectCatalog.of(world)); } /** The random a chunk's objects are placed with. */ @@ -58,8 +61,11 @@ public final class ObjectPool { return streams.objectChunkRandom(chunkX, chunkZ); } - /** The pack object {@code key} names. */ - public Optional object(String key) { + /** The pack object {@code key} names; for a procedural pool, the variant {@code rng} picks. */ + public Optional object(String key, RNG rng) { + if (ProceduralObjectCatalog.isProceduralKey(key)) { + return procedural.object(key, rng); + } return objects().object(resources.idOf(key)); } @@ -69,7 +75,7 @@ public final class ObjectPool { if (keys.isEmpty()) { return Optional.empty(); } - return object(keys.get(rng.nextInt(keys.size()))).map(origin -> scaled(origin, placement.scale(), rng)); + return object(keys.get(rng.nextInt(keys.size())), rng).map(origin -> scaled(origin, placement.scale(), rng)); } /** {@code origin} shrunk or grown by exactly {@code factor}, without filling between its blocks. */ @@ -82,9 +88,10 @@ public final class ObjectPool { return streams.density(placement, rng, x, z); } - /** Builds the noise the placement draws its density from, so the first chunk to place it does not wait. */ + /** Builds the noise the placement draws its density from and bakes its procedural objects, so the first chunk to place it does not wait. */ public void warm(ObjectPlacement placement, RNG rng) { streams.density(placement, rng, 0, 0); + placement.place().stream().filter(ProceduralObjectCatalog::isProceduralKey).forEach(procedural::placeable); } private PlaceableObject scaled(PlaceableObject origin, ObjectScale scale, RNG rng) { diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java deleted file mode 100644 index b313539ed..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectSettings.java +++ /dev/null @@ -1,99 +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.modules.objects; - -import art.arcane.iris.modules.objects.coral.Coral; -import art.arcane.iris.modules.objects.crystal.Crystal; -import art.arcane.iris.modules.objects.formation.Formation; -import art.arcane.iris.modules.objects.fungi.Fungus; -import art.arcane.iris.modules.objects.ruin.Ruin; -import art.arcane.iris.modules.objects.tree.Tree; -import com.volmit.config.Level; -import com.volmit.IrisFeature; -import com.volmit.config.Desc; -import com.volmit.config.Feature; -import com.volmit.config.MinItems; -import com.volmit.config.Snippet; - -import java.util.Collections; -import java.util.List; - -/** - * The procedural objects a region or biome declares, written as {@code "proceduralObjects": {"trees": [...], ...}}: things - * Iris generates from scratch at world-gen time and places like object placements. - */ -@Snippet("iris/objects/procedural-objects") -@Desc("Procedurally generated objects placed in a biome or region. Unlike the objects block (which loads iob files), these are generated from scratch at world-gen time.") -@Feature(id = "iris:objects/procedural", name = "Procedural objects", key = "proceduralObjects", targets = {Level.REGION, Level.BIOME}) -public final class ProceduralObjectSettings implements IrisFeature { - @MinItems(1) - @Desc("Procedurally generated trees.") - private List trees = List.of(); - - @MinItems(1) - @Desc("Procedurally generated ruins (crumbling pillars, walls, arches, rubble).") - private List ruins = List.of(); - - @MinItems(1) - @Desc("Procedurally generated natural rock formations (spires, hoodoos, arches, sea stacks, boulders, basalt columns).") - private List formations = List.of(); - - @MinItems(1) - @Desc("Procedurally generated underwater coral structures.") - private List coral = List.of(); - - @MinItems(1) - @Desc("Procedurally generated mushrooms and shelf fungi.") - private List fungi = List.of(); - - @MinItems(1) - @Desc("Procedurally generated crystal clusters (usually placed in caves).") - private List crystals = List.of(); - - public ProceduralObjectSettings() { - } - - public List trees() { - return view(trees); - } - - public List ruins() { - return view(ruins); - } - - public List formations() { - return view(formations); - } - - public List coral() { - return view(coral); - } - - public List fungi() { - return view(fungi); - } - - public List crystals() { - return view(crystals); - } - - private static List view(List list) { - return list == null ? List.of() : Collections.unmodifiableList(list); - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java deleted file mode 100644 index c8be43476..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/ProceduralPlacement.java +++ /dev/null @@ -1,97 +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.modules.objects; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.objects.PlacementSource; -import com.volmit.object.PlaceableObject; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.carve.CaveAnchorMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import art.arcane.volmlib.util.math.RNG; - -import java.util.List; -import java.util.Optional; - -/** - * A procedural object of a region or biome made placeable: a pool of variants Iris bakes once from its settings, and - * the options it is scattered with, like an object placement. - */ -public interface ProceduralPlacement extends PlacementSource { - String name(); - - @Override - double chance(); - - int density(); - - /** Whether the variants are meant to look like the real thing, so leaves decay. */ - boolean plausible(); - - /** Whether the variants are trees. */ - boolean tree(); - - @Override - ObjectPlaceMode mode(); - - @Override - CarvingMode carvingSupport(); - - @Override - CaveAnchorMode caveAnchorMode(); - - @Override - boolean underwater(); - - @Override - default boolean requireSurfaceSupport() { - return true; - } - - @Override - default int surfaceSupportBuffer() { - return 2; - } - - @Override - default boolean isDolphinTarget() { - return false; - } - - ObjectRotation rotation(); - - ObjectTranslate translate(); - - Optional vacuumSettings(); - - /** The heights the variants may sit between. */ - ObjectLimit clamp(); - - Optional stiltSettings(); - - /** One of the variants, picked with {@code rng}; empty when none baked. */ - Optional variant(RNG rng); - - /** Every variant, baked on first use. */ - List variants(); -} diff --git a/src/main/java/art/arcane/iris/modules/objects/coral/Coral.java b/src/main/java/art/arcane/iris/modules/objects/coral/Coral.java deleted file mode 100644 index 31dc9f77f..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/coral/Coral.java +++ /dev/null @@ -1,344 +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.modules.objects.coral; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Optional; - -@Snippet("iris/objects/coral") -@Desc("A single procedurally generated coral reef structure. Iris bakes a pool of deterministic variants from these settings and scatters them across the seafloor at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Mirrors the procedural tree system but tuned for underwater reefs: structural blocks are waterlogged so the coral stays alive, and placement defaults to anchoring on the terrain beneath the water surface.") -public final class Coral { - @Desc("A human readable name used in logs and as the variant load key.") - private String name = "coral"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per chunk for this coral to attempt placement. Use density for multiple per chunk.") - private double chance = 0.4; - - @MinNumber(1) - @Desc("If the chance check passes, attempt this many placements in the chunk.") - private int density = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("How many distinct variants to pre-bake for this coral. Higher means more variety at a small memory cost.") - private int variants = 6; - - @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") - private long seed = 1337; - - @Desc("The placement mode used to anchor the coral to the seafloor.") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - - @Desc("Rotate this coral's placement.") - private ObjectRotation rotation = new ObjectRotation(); - - @Desc("Limit the max or min height of placement.") - private ObjectLimit clamp = new ObjectLimit(); - - @Desc("Whether this coral may place on the terrain surface, under carvings, or both.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - - @Desc("If true (default for coral), the coral anchors on the terrain height beneath the water, so it grows up from the seafloor rather than floating at the water surface.") - private boolean underwater = true; - - @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the seafloor.") - private ObjectTranslate translate = new ObjectTranslate(); - - @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private StiltSettings stiltSettings; - - @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private VacuumSettings vacuumSettings; - - @Desc("If true (default), every resolved coral block that is waterloggable is forced waterlogged so the coral does not die in water (coral fans, sea pickles and kelp also waterlog). Set false to place dead/dry coral.") - private boolean waterlogged = true; - - @Desc("The overall silhouette this coral grows into (branching, fan, brain, pillar, tendril). Each form runs a different generation routine.") - private CoralForm form = CoralForm.BRANCHING; - - @Required - @Desc("The structural coral block (the living wood of the reef), e.g. minecraft:tube_coral_block. Ignored when blockPalette is set.") - @Ref(Reference.BLOCK) - private String block = "minecraft:tube_coral_block"; - - @Desc("A noise-driven palette for the structural coral block. When set this overrides the single block, letting the reef mix tube/brain/bubble/fire/horn coral_block tones across its body.") - private PaletteSpec blockPalette; - - @Desc("Optional tip block placed at branch tips and at the very top of the structure, e.g. coral fans or minecraft:sea_pickle. Ignored when tipPalette is set. Null disables tips.") - @Ref(Reference.BLOCK) - private String tipBlock = null; - - @Desc("A noise-driven palette for the tip block. When set this overrides the single tipBlock, letting tips mix fan / pickle decorations.") - private PaletteSpec tipPalette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per eligible tip position to place a tip block (coral fan / sea pickle).") - private double tipChance = 0.6; - - @MinNumber(1) - @Desc("Minimum overall height of the coral in blocks.") - private int heightMin = 4; - - @MinNumber(1) - @Desc("Maximum overall height of the coral in blocks.") - private int heightMax = 8; - - @MinNumber(0) - @Desc("Horizontal spread of the structure in blocks. For BRANCHING this is how far arms reach out, for BRAIN/PILLAR/FAN it widens the base footprint.") - private double spread = 3; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Lateral noise wobble (0-1) applied to branches and tendrils so they are not ruler-straight. 0 is perfectly straight, 1 is heavily wandering.") - private double sway = 0.5; - - @MinNumber(1) - @MaxNumber(12) - @Desc("BRANCHING only: how many arms sprout from the central stalk.") - private int branchCount = 4; - - @MinNumber(1) - @Desc("BRANCHING only: the length of each arm in blocks before reaching its tip.") - private double branchLength = 3; - - @MinNumber(0) - @MaxNumber(90) - @Desc("BRANCHING only: the upward elevation in degrees of each arm from horizontal. 90 is straight up, 0 is flat out.") - private double branchElevation = 55; - - @Desc("BRANCHING only: how the arms are distributed around the stalk by azimuth.") - private CoralBranchAzimuth branchAzimuth = CoralBranchAzimuth.GOLDEN_ANGLE; - - @Desc("BRANCHING only: if true, each arm splits once into a small fan of sub-arms for a bushier reef.") - private boolean subBranches = true; - - @MinNumber(1) - @MaxNumber(5) - @Desc("BRANCHING only: how many sub-arms each arm splits into when subBranches is true.") - private int subBranchCount = 2; - - @MinNumber(0) - @MaxNumber(1) - @Desc("BRANCHING only: the length of each sub-arm as a fraction of its parent arm.") - private double subBranchScale = 0.5; - - @MinNumber(0) - @MaxNumber(4) - @Desc("BRANCHING and PILLAR only: the radius of the small coral tip cluster grown at each tip.") - private int tipClusterRadius = 1; - - @MinNumber(1) - @MaxNumber(8) - @Desc("BRAIN only: the horizontal radius of the brain-coral blob in blocks.") - private int brainRadius = 3; - - @MinNumber(0) - @MaxNumber(1) - @Desc("BRAIN only: how strongly 3D value noise perturbs the ellipsoid surface, for a wrinkled organic blob. 0 is a smooth dome.") - private double brainRoughness = 0.35; - - @MinNumber(1) - @MaxNumber(12) - @Desc("PILLAR only: the radius of the stout vertical column in blocks.") - private int pillarRadius = 1; - - @MinNumber(1) - @MaxNumber(8) - @Desc("FAN only: the half-width of the upright fan plane in blocks (the disc widens toward its mid-height).") - private int fanWidth = 3; - - @MinNumber(1) - @MaxNumber(12) - @Desc("TENDRIL only: how many thin wavy stalks rise from the base.") - private int tendrilCount = 4; - - public Coral() { - } - - public String name() { - return name; - } - - public double chance() { - return chance; - } - - public int density() { - return density; - } - - public int variants() { - return variants; - } - - public long seed() { - return seed; - } - - public ObjectPlaceMode mode() { - return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; - } - - public ObjectRotation rotation() { - return rotation; - } - - public ObjectLimit clamp() { - return clamp; - } - - public CarvingMode carvingSupport() { - return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; - } - - public boolean underwater() { - return underwater; - } - - public ObjectTranslate translate() { - return translate; - } - - /** Empty where the pack sets none. */ - public Optional stiltSettings() { - return Optional.ofNullable(stiltSettings); - } - - /** Empty where the pack sets none. */ - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); - } - - public boolean waterlogged() { - return waterlogged; - } - - public CoralForm form() { - return form == null ? CoralForm.BRANCHING : form; - } - - public String block() { - return block; - } - - /** Empty where the pack sets none. */ - public Optional blockPalette() { - return Optional.ofNullable(blockPalette); - } - - /** Empty where the pack sets none. */ - public Optional tipBlock() { - return Optional.ofNullable(tipBlock); - } - - /** Empty where the pack sets none. */ - public Optional tipPalette() { - return Optional.ofNullable(tipPalette); - } - - public double tipChance() { - return tipChance; - } - - public int heightMin() { - return heightMin; - } - - public int heightMax() { - return heightMax; - } - - public double spread() { - return spread; - } - - public double sway() { - return sway; - } - - public int branchCount() { - return branchCount; - } - - public double branchLength() { - return branchLength; - } - - public double branchElevation() { - return branchElevation; - } - - public CoralBranchAzimuth branchAzimuth() { - return branchAzimuth == null ? CoralBranchAzimuth.GOLDEN_ANGLE : branchAzimuth; - } - - public boolean subBranches() { - return subBranches; - } - - public int subBranchCount() { - return subBranchCount; - } - - public double subBranchScale() { - return subBranchScale; - } - - public int tipClusterRadius() { - return tipClusterRadius; - } - - public int brainRadius() { - return brainRadius; - } - - public double brainRoughness() { - return brainRoughness; - } - - public int pillarRadius() { - return pillarRadius; - } - - public int fanWidth() { - return fanWidth; - } - - public int tendrilCount() { - return tendrilCount; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java b/src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java deleted file mode 100644 index 46d645872..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/coral/CoralForm.java +++ /dev/null @@ -1,39 +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.modules.objects.coral; - -import com.volmit.config.Desc; - -@Desc("The overall silhouette a procedural coral grows into. Each form drives a completely different generation routine in the coral generator, from tree-like branching arms to rounded brain blobs and thin wavy tendrils.") -public enum CoralForm { - @Desc("A tree-like coral built from a stout central stalk that sprouts several upward-leaning arms (distributed by golden angle or randomly), each optionally splitting once into sub-arms, with small coral tip clusters (fans / sea pickles) at the ends. The most structurally complex form and the closest analogue to a procedural tree.") - BRANCHING, - - @Desc("A thin, single-block-thick vertical fan plane that rises and widens with height like a sheet of fire or horn coral. Reads as a flat decorative blade rather than a volume.") - FAN, - - @Desc("A rounded, noise-perturbed ellipsoid blob of brain coral that bulges out of the seafloor like a boulder, with an irregular wrinkled surface driven by 3D value noise.") - BRAIN, - - @Desc("A stout, thick vertical column of coral block topped with a dense tip cluster. Wider and blunter than a tendril, reading as a solid coral pillar or stack.") - PILLAR, - - @Desc("Several very thin (one block wide) wavy stalks that rise upward and wander laterally using value noise, like a clump of swaying coral whips or kelp-thin growths.") - TENDRIL -} diff --git a/src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java b/src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java deleted file mode 100644 index f954a4e79..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/crystal/Crystal.java +++ /dev/null @@ -1,314 +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.modules.objects.crystal; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Optional; - -@Snippet("iris/objects/crystal") -@Desc("A single procedurally generated crystal cluster: a budding base blob with faceted, tapered shards radiating from it (geode / amethyst-style). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Built for caves.") -public final class Crystal { - @Desc("A human readable name used in logs and as the variant load key.") - private String name = "crystal"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per chunk for this crystal cluster to attempt placement. Use density for multiple per chunk.") - private double chance = 0.2; - - @MinNumber(1) - @Desc("If the chance check passes, attempt this many placements in the chunk.") - private int density = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("How many distinct variants to pre-bake for this crystal cluster. Higher means more variety at a small memory cost.") - private int variants = 6; - - @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") - private long seed = 1337; - - @Desc("The placement mode used to anchor the crystal cluster to the terrain.") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - - @Desc("Rotate this crystal cluster's placement.") - private ObjectRotation rotation = new ObjectRotation(); - - @Desc("Limit the max or min height of placement.") - private ObjectLimit clamp = new ObjectLimit(); - - @Desc("Whether this crystal cluster may place on the terrain surface, under carvings, or both. Crystals are meant for caves, so this defaults to CARVING_ONLY.") - private CarvingMode carvingSupport = CarvingMode.CARVING_ONLY; - - @Desc("If true, the crystal cluster anchors on the terrain height ignoring the water surface.") - private boolean underwater = false; - - @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private ObjectTranslate translate = new ObjectTranslate(); - - @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private StiltSettings stiltSettings; - - @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private VacuumSettings vacuumSettings; - - @Desc("The surface this crystal grows from (FLOOR shards up, CEILING shards down, WALL shards outward). This orients the baked geometry only.") - private CrystalSurface growthSurface = CrystalSurface.FLOOR; - - @Required - @Desc("The primary crystal shard block, e.g. minecraft:amethyst_block. Ignored when blockPalette is set.") - @Ref(Reference.BLOCK) - private String block = "minecraft:amethyst_block"; - - @Desc("A noise-driven palette for the crystal shards (a prismatic mix, e.g. amethyst_block, calcite, tinted_glass). When set this overrides the single block, letting the shards mix blocks by noise. Palette wins.") - private PaletteSpec blockPalette; - - @Desc("Optional block placed at the very tip of each shard for a different colored or sparkling point (e.g. minecraft:amethyst_cluster or glowstone). Ignored when tipPalette is set. If unset and glow is true, a light-emitting block is sprinkled among the tips instead.") - @Ref(Reference.BLOCK) - private String tipBlock = null; - - @Desc("A noise-driven palette for the shard tips. When set this overrides the single tipBlock. Palette wins.") - private PaletteSpec tipPalette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per shard that its very tip is replaced by the tip block (or glow block).") - private double tipChance = 0.6; - - @Desc("If true and no tipBlock/tipPalette is set, sprinkle a light-emitting block (the glowBlock) among the shard tips for a sparkling geode.") - private boolean glow = false; - - @Desc("The light-emitting block sprinkled among the tips when glow is true and no tip block is configured.") - @Ref(Reference.BLOCK) - private String glowBlock = "minecraft:glowstone"; - - @Desc("Optional block for the budding base blob the shards grow from, e.g. minecraft:budding_amethyst or calcite. Ignored when basePalette is set. If unset, the base is built from the primary shard block.") - @Ref(Reference.BLOCK) - private String baseBlock = "minecraft:budding_amethyst"; - - @Desc("A noise-driven palette for the budding base blob. When set this overrides the single baseBlock. Palette wins.") - private PaletteSpec basePalette; - - @MinNumber(0) - @Desc("Radius in blocks of the budding base blob the shards radiate from. 0 places no base blob (shards spring from a single point).") - private double baseRadius = 1.6; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How strongly value noise perturbs the surface of the base blob, for a lumpy organic budding base rather than a clean sphere.") - private double baseNoise = 0.35; - - @MinNumber(1) - @Desc("Minimum number of shards radiating from the base.") - private int shardCountMin = 5; - - @MinNumber(1) - @Desc("Maximum number of shards radiating from the base.") - private int shardCountMax = 11; - - @MinNumber(1) - @Desc("Minimum length in blocks of a shard, measured from the base out to its pointed tip.") - private int shardLengthMin = 3; - - @MinNumber(1) - @Desc("Maximum length in blocks of a shard, measured from the base out to its pointed tip.") - private int shardLengthMax = 8; - - @MinNumber(0.5) - @Desc("Starting radius in blocks of a shard at its thick base end. The shard tapers from this down to a single block at the tip.") - private double shardBaseRadius = 1.4; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How aggressively each shard narrows from base to tip. 0 keeps a near-constant column; 1 tapers fully to a sharp point at the very tip. Each shard always ends in a single pointed block.") - private double shardTaper = 0.85; - - @MinNumber(0) - @MaxNumber(90) - @Desc("The half-angle in degrees of the cone the shards fan within around the surface normal. 0 makes all shards parallel to the normal; larger values splay them outward into a starburst.") - private double spreadAngle = 45; - - @Desc("How the shard azimuths are distributed around the normal (RANDOM for a chaotic clump, GOLDEN_ANGLE for an evenly spaced rosette).") - private CrystalDistribution distribution = CrystalDistribution.GOLDEN_ANGLE; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Per-shard angular randomness (0-1) added on top of the chosen distribution so the cluster never looks mechanically regular. 0 is perfectly distributed; 1 is heavily jittered.") - private double jitter = 0.25; - - public Crystal() { - } - - public String name() { - return name; - } - - public double chance() { - return chance; - } - - public int density() { - return density; - } - - public int variants() { - return variants; - } - - public long seed() { - return seed; - } - - public ObjectPlaceMode mode() { - return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; - } - - public ObjectRotation rotation() { - return rotation; - } - - public ObjectLimit clamp() { - return clamp; - } - - public CarvingMode carvingSupport() { - return carvingSupport == null ? CarvingMode.CARVING_ONLY : carvingSupport; - } - - public boolean underwater() { - return underwater; - } - - public ObjectTranslate translate() { - return translate; - } - - /** Empty where the pack sets none. */ - public Optional stiltSettings() { - return Optional.ofNullable(stiltSettings); - } - - /** Empty where the pack sets none. */ - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); - } - - public CrystalSurface growthSurface() { - return growthSurface == null ? CrystalSurface.FLOOR : growthSurface; - } - - public String block() { - return block; - } - - /** Empty where the pack sets none. */ - public Optional blockPalette() { - return Optional.ofNullable(blockPalette); - } - - /** Empty where the pack sets none. */ - public Optional tipBlock() { - return Optional.ofNullable(tipBlock); - } - - /** Empty where the pack sets none. */ - public Optional tipPalette() { - return Optional.ofNullable(tipPalette); - } - - public double tipChance() { - return tipChance; - } - - public boolean glow() { - return glow; - } - - public String glowBlock() { - return glowBlock; - } - - public String baseBlock() { - return baseBlock; - } - - /** Empty where the pack sets none. */ - public Optional basePalette() { - return Optional.ofNullable(basePalette); - } - - public double baseRadius() { - return baseRadius; - } - - public double baseNoise() { - return baseNoise; - } - - public int shardCountMin() { - return shardCountMin; - } - - public int shardCountMax() { - return shardCountMax; - } - - public int shardLengthMin() { - return shardLengthMin; - } - - public int shardLengthMax() { - return shardLengthMax; - } - - public double shardBaseRadius() { - return shardBaseRadius; - } - - public double shardTaper() { - return shardTaper; - } - - public double spreadAngle() { - return spreadAngle; - } - - public CrystalDistribution distribution() { - return distribution == null ? CrystalDistribution.GOLDEN_ANGLE : distribution; - } - - public double jitter() { - return jitter; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java b/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java deleted file mode 100644 index 66d456e8d..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/crystal/CrystalSurface.java +++ /dev/null @@ -1,33 +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.modules.objects.crystal; - -import com.volmit.config.Desc; - -@Desc("The surface a crystal cluster grows from. This only orients the baked geometry (which way the shards point); placement of the object into a cave is handled by the placement system, not here.") -public enum CrystalSurface { - @Desc("Grows from a cave floor. The budding base sits at the bottom and the shards point upward, fanning within the spread cone around the up axis. Built with positive py so the cluster grows up from the base layer.") - FLOOR, - - @Desc("Grows from a cave ceiling. The budding base sits at the top and the shards point downward like stalactites, fanning within the spread cone around the down axis. Built with negative py so the cluster grows down from the ceiling.") - CEILING, - - @Desc("Grows from a cave wall. The budding base hugs the wall and the shards point outward and slightly upward, fanning within the spread cone around a tilted normal so the cluster reads as a wall sconce of shards.") - WALL -} diff --git a/src/main/java/art/arcane/iris/modules/objects/formation/Formation.java b/src/main/java/art/arcane/iris/modules/objects/formation/Formation.java deleted file mode 100644 index eeb8b93db..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/formation/Formation.java +++ /dev/null @@ -1,447 +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.modules.objects.formation; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Optional; - -@Snippet("iris/objects/formation") -@Desc("A single procedurally generated natural formation, including rock landmarks and magical glacial silhouettes. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") -public final class Formation { - @Desc("A human readable name used in logs and as the variant load key.") - private String name = "formation"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per chunk for this formation to attempt placement. Use density for multiple per chunk.") - private double chance = 0.02; - - @MinNumber(1) - @Desc("If the chance check passes, attempt this many placements in the chunk.") - private int density = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("How many distinct variants to pre-bake for this formation. Higher means more variety at a small memory cost.") - private int variants = 6; - - @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") - private long seed = 1337; - - @Desc("The placement mode used to anchor the formation to the terrain.") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - - @Desc("Rotate this formation's placement.") - private ObjectRotation rotation = new ObjectRotation(); - - @Desc("Limit the max or min height of placement.") - private ObjectLimit clamp = new ObjectLimit(); - - @Desc("Whether this formation may place on the terrain surface, under carvings, or both.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - - @MinNumber(0) - @MaxNumber(16) - @Desc("Horizontal buffer, in blocks, beyond each lowest solid foundation block that must also be solid, un-carved ground.") - private int surfaceSupportBuffer = 3; - - @Desc("If true, the formation anchors on the terrain height ignoring the water surface.") - private boolean underwater = false; - - @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private ObjectTranslate translate = new ObjectTranslate(); - - @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private StiltSettings stiltSettings; - - @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private VacuumSettings vacuumSettings; - - @Desc("The overall silhouette of the formation. Drives which sculpting routine the generator uses.") - private FormationForm form = FormationForm.SPIRE; - - @Required - @Desc("The main rock block, e.g. minecraft:stone. Ignored when blockPalette is set.") - @Ref(Reference.BLOCK) - private String block = "minecraft:stone"; - - @Desc("A noise-driven palette for the main rock body. When set this overrides the single block, letting the body mix blocks by noise.") - private PaletteSpec blockPalette; - - @Desc("Optional caprock block placed on the top crown of the formation (and the wide overhanging cap for HOODOO). Ignored when capPalette is set. When null and capPalette is unset, the formation uses its main rock everywhere.") - @Ref(Reference.BLOCK) - private String capBlock = null; - - @Desc("A noise-driven palette for the caprock. When set this overrides the single capBlock.") - private PaletteSpec capPalette; - - @Desc("Optional palette of strata (horizontal colored bands) blended into the rock body by y level. When set, every strataThickness blocks of height switches to the next strata block, producing the signature banded look. Falls back to the main block where unset.") - private PaletteSpec strataPalette; - - @MinNumber(1) - @MaxNumber(32) - @Desc("The thickness in blocks of each horizontal strata band when strataPalette is set.") - private int strataThickness = 3; - - @MinNumber(1) - @Desc("Minimum total height of the formation in blocks.") - private int heightMin = 14; - - @MinNumber(1) - @Desc("Maximum total height of the formation in blocks.") - private int heightMax = 26; - - @MinNumber(1) - @Desc("Minimum base radius (half-width) of the formation in blocks.") - private int baseWidthMin = 3; - - @MinNumber(1) - @Desc("Maximum base radius (half-width) of the formation in blocks.") - private int baseWidthMax = 6; - - @MinNumber(0) - @Desc("The target radius (half-width) at the very top of the formation in blocks, before the profile is applied. 0 means taper to a point.") - private int topWidth = 0; - - @Desc("The function used to shape the formation radius over its height.") - private FormationProfile profile = FormationProfile.TAPER; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The normalized height (0 base, 1 top) of the pinched waist for the PARABOLIC profile (used by HOODOO).") - private double profileWaist = 0.55; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The minimum radius fraction at the waist for the PARABOLIC profile. Lower values pinch the waist tighter.") - private double profileWaistFloor = 0.35; - - @MinNumber(0) - @Desc("How far the formation leans, in degrees from vertical. 0 is perfectly upright. The whole body is sheared by this amount over its height.") - private double lean = 0; - - @Desc("Compass direction in degrees the formation leans toward when lean is non-zero.") - private double leanAzimuth = 0; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Surface roughness from 0 (a clean smooth solid) to 1 (heavily eroded and pitted). Driven by 3D value noise that perturbs the radius so the formation never reads as a clean cylinder.") - private double roughness = 0.3; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Per-block surface jitter from 0 (none) to 1 (maximum). Randomly carves and adds isolated edge blocks to break up the silhouette.") - private double jitter = 0.15; - - @MinNumber(0) - @Desc("Extra wide cap radius in blocks added on top for the HOODOO form, producing the overhanging mushroom caprock. 0 disables the overhang.") - private int hoodooCapRadius = 3; - - @MinNumber(1) - @MaxNumber(6) - @Desc("The height in blocks of the HOODOO overhanging caprock slab.") - private int hoodooCapHeight = 3; - - @MinNumber(0) - @Desc("How wide the ARCH opening is in blocks (the gap between the two legs). The arch span is rasterized over this width.") - private int archSpan = 10; - - @MinNumber(1) - @Desc("The thickness in blocks of the ARCH legs and spanning curve.") - private int archThickness = 3; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How strongly an ARCH varies its leg steepness, crown position, depth bow and tube width between deterministic variants. 0 is symmetric and 1 is highly organic.") - private double archAsymmetry = 0.35; - - @MinNumber(2) - @MaxNumber(12) - @Desc("How many separate columns make up a BASALT_COLUMN cluster. Each column gets a randomized height around the formation height range.") - private int basaltColumns = 5; - - @MinNumber(1) - @Desc("The radius (half-width) in blocks of each individual column in a BASALT_COLUMN cluster.") - private int basaltColumnRadius = 1; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How much the heights of individual BASALT_COLUMN columns vary from each other, from 0 (all equal) to 1 (highly varied).") - private double basaltHeightVariance = 0.45; - - @MinNumber(1) - @MaxNumber(12) - @Desc("How many tapered summits crown an ICEBERG formation.") - private int icebergPeaks = 3; - - @MinNumber(2) - @MaxNumber(8) - @Desc("How many separated shards form a FISSURE.") - private int fractureCount = 3; - - @MinNumber(1) - @MaxNumber(16) - @Desc("Open-air separation in blocks between the shards of a FISSURE.") - private int fractureSeparation = 2; - - @MinNumber(0.25) - @MaxNumber(6) - @Desc("How many complete turns a SPIRAL makes from base to tip.") - private double spiralTurns = 1.5; - - @MinNumber(1) - @MaxNumber(32) - @Desc("The starting distance in blocks between a SPIRAL and its open center.") - private int spiralRadius = 4; - - @MinNumber(1) - @MaxNumber(8) - @Desc("The radius in blocks of the tube swept along a SPIRAL.") - private int spiralThickness = 2; - - @MinNumber(1) - @MaxNumber(32) - @Desc("How far the hooked arm of an OVERHANG projects from its base.") - private int overhangReach = 8; - - @MinNumber(0) - @MaxNumber(16) - @Desc("How many blocks the tip of an OVERHANG curls downward.") - private int overhangDrop = 3; - - public Formation() { - } - - public String name() { - return name; - } - - public double chance() { - return chance; - } - - public int density() { - return density; - } - - public int variants() { - return variants; - } - - public long seed() { - return seed; - } - - public ObjectPlaceMode mode() { - return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; - } - - public ObjectRotation rotation() { - return rotation; - } - - public ObjectLimit clamp() { - return clamp; - } - - public CarvingMode carvingSupport() { - return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; - } - - public int surfaceSupportBuffer() { - return surfaceSupportBuffer; - } - - public boolean underwater() { - return underwater; - } - - public ObjectTranslate translate() { - return translate; - } - - /** Empty where the pack sets none. */ - public Optional stiltSettings() { - return Optional.ofNullable(stiltSettings); - } - - /** Empty where the pack sets none. */ - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); - } - - public FormationForm form() { - return form == null ? FormationForm.SPIRE : form; - } - - public String block() { - return block; - } - - /** Empty where the pack sets none. */ - public Optional blockPalette() { - return Optional.ofNullable(blockPalette); - } - - /** Empty where the pack sets none. */ - public Optional capBlock() { - return Optional.ofNullable(capBlock); - } - - /** Empty where the pack sets none. */ - public Optional capPalette() { - return Optional.ofNullable(capPalette); - } - - /** Empty where the pack sets none. */ - public Optional strataPalette() { - return Optional.ofNullable(strataPalette); - } - - public int strataThickness() { - return strataThickness; - } - - public int heightMin() { - return heightMin; - } - - public int heightMax() { - return heightMax; - } - - public int baseWidthMin() { - return baseWidthMin; - } - - public int baseWidthMax() { - return baseWidthMax; - } - - public int topWidth() { - return topWidth; - } - - public FormationProfile profile() { - return profile == null ? FormationProfile.TAPER : profile; - } - - public double profileWaist() { - return profileWaist; - } - - public double profileWaistFloor() { - return profileWaistFloor; - } - - public double lean() { - return lean; - } - - public double leanAzimuth() { - return leanAzimuth; - } - - public double roughness() { - return roughness; - } - - public double jitter() { - return jitter; - } - - public int hoodooCapRadius() { - return hoodooCapRadius; - } - - public int hoodooCapHeight() { - return hoodooCapHeight; - } - - public int archSpan() { - return archSpan; - } - - public int archThickness() { - return archThickness; - } - - public double archAsymmetry() { - return archAsymmetry; - } - - public int basaltColumns() { - return basaltColumns; - } - - public int basaltColumnRadius() { - return basaltColumnRadius; - } - - public double basaltHeightVariance() { - return basaltHeightVariance; - } - - public int icebergPeaks() { - return icebergPeaks; - } - - public int fractureCount() { - return fractureCount; - } - - public int fractureSeparation() { - return fractureSeparation; - } - - public double spiralTurns() { - return spiralTurns; - } - - public int spiralRadius() { - return spiralRadius; - } - - public int spiralThickness() { - return spiralThickness; - } - - public int overhangReach() { - return overhangReach; - } - - public int overhangDrop() { - return overhangDrop; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java b/src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java deleted file mode 100644 index 6ffbefc54..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/formation/FormationForm.java +++ /dev/null @@ -1,45 +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.modules.objects.formation; - -import com.volmit.config.Desc; - -@Desc("The overall silhouette of a procedural natural formation. Each form drives a distinct sculpting routine in the formation generator.") -public enum FormationForm { - @Desc("A tall, slender needle of rock that tapers smoothly to a point at the top (a sharp pinnacle or stone spire).") - SPIRE, - @Desc("A column with a pinched, eroded waist and a wide overhanging caprock balanced on top (the classic desert hoodoo / mushroom rock).") - HOODOO, - @Desc("Two stout legs joined by a spanning curved bridge of rock overhead (a natural stone arch).") - ARCH, - @Desc("A chunky, blocky stack that tapers gently as it rises, like an isolated pillar of rock standing in water (a sea stack).") - SEA_STACK, - @Desc("A rounded, lumpy boulder formed from a noise-perturbed ellipsoid that sits low on the terrain.") - BOULDER, - @Desc("A tightly packed cluster of several vertical, near-hexagonal columns of varying height (a basalt column formation / giant's causeway).") - BASALT_COLUMN, - @Desc("A broad, faceted mound crowned by several irregular tapered peaks, suitable for icebergs and glacial outcrops.") - ICEBERG, - @Desc("Several separated, outward-leaning shards divided by open cracks.") - FISSURE, - @Desc("A tapered tube swept around a tightening helix, leaving open air through its curled center.") - SPIRAL, - @Desc("A grounded pillar that bends into a long hooked cantilever and curls downward at its tip.") - OVERHANG -} diff --git a/src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java b/src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java deleted file mode 100644 index c63462b8f..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/formation/FormationProfile.java +++ /dev/null @@ -1,35 +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.modules.objects.formation; - -import com.volmit.config.Desc; - -@Desc("A width-shaping function evaluated over normalized height (0 at the base, 1 at the top). Controls how the formation radius scales between baseWidth at the bottom and topWidth at the top.") -public enum FormationProfile { - @Desc("Same radius at every height (a straight cylinder of constant baseWidth).") - CONSTANT, - @Desc("Radius ramps straight from baseWidth at the bottom to topWidth at the top.") - LINEAR, - @Desc("Radius shrinks smoothly toward a point as height increases (an ease that drives the SPIRE needle and gentle SEA_STACK taper).") - TAPER, - @Desc("Radius pinches to a narrow waist near profileWaist then widens again toward the top (the eroded waist used by HOODOO columns).") - PARABOLIC, - @Desc("Radius bulges out to its maximum in the middle of the height range and narrows at both ends (a barrel / bulged column).") - BULGE -} diff --git a/src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java b/src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java deleted file mode 100644 index 8098f9d59..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/fungi/Fungus.java +++ /dev/null @@ -1,355 +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.modules.objects.fungi; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Optional; - -@Snippet("iris/objects/fungus") -@Desc("A single procedurally generated fungus (giant mushroom or shelf fungus). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. The fungus is built as a stem column with a cap dome grown on top, mirroring the trunk-and-canopy model used by procedural trees.") -public final class Fungus { - @Desc("A human readable name used in logs and as the variant load key.") - private String name = "fungus"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per chunk for this fungus to attempt placement. Use density for multiple per chunk.") - private double chance = 0.4; - - @MinNumber(1) - @Desc("If the chance check passes, attempt this many placements in the chunk.") - private int density = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("How many distinct variants to pre-bake for this fungus. Higher means more variety at a small memory cost.") - private int variants = 6; - - @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") - private long seed = 1337; - - @Desc("The placement mode used to anchor the fungus to the terrain.") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - - @Desc("Rotate this fungus's placement.") - private ObjectRotation rotation = new ObjectRotation(); - - @Desc("Limit the max or min height of placement.") - private ObjectLimit clamp = new ObjectLimit(); - - @Desc("Whether this fungus may place on the terrain surface, under carvings, or both.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - - @Desc("If true, the fungus anchors on the terrain height ignoring the water surface.") - private boolean underwater = false; - - @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private ObjectTranslate translate = new ObjectTranslate(); - - @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private StiltSettings stiltSettings; - - @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private VacuumSettings vacuumSettings; - - @Required - @Desc("The stem block, e.g. minecraft:mushroom_stem. Ignored when stemPalette is set.") - @Ref(Reference.BLOCK) - private String stem = "minecraft:mushroom_stem"; - - @Desc("A noise-driven palette for the stem. When set this overrides the single stem block, letting the stem mix blocks by noise.") - private PaletteSpec stemPalette; - - @Required - @Desc("The cap block, e.g. minecraft:red_mushroom_block. Ignored when capPalette is set.") - @Ref(Reference.BLOCK) - private String cap = "minecraft:red_mushroom_block"; - - @Desc("A noise-driven palette for the cap. When set this overrides the single cap block, letting the cap mix blocks by noise.") - private PaletteSpec capPalette; - - @MinNumber(1) - @Desc("Minimum total stem height in blocks. Variants spread between this and stemHeightMax.") - private int stemHeightMin = 5; - - @MinNumber(1) - @Desc("Maximum total stem height in blocks. Variants spread between stemHeightMin and this.") - private int stemHeightMax = 9; - - @MinNumber(1) - @MaxNumber(3) - @Desc("Base stem width in blocks. 1 is a single column, 2 is a 2x2 stem, 3 is a chunky 3x3 trunk.") - private int stemWidth = 1; - - @Desc("How far the stem leans away from vertical, in degrees. 0 is perfectly upright; small values give an organic tilt.") - private double stemCurve = 0; - - @Desc("Compass direction in degrees the stem leans toward when stemCurve is non-zero.") - private double stemLeanAzimuth = 0; - - @MinNumber(0) - @Desc("Amplitude in blocks of a gentle sideways wave applied up the stem so it is not a perfectly straight ruler.") - private double stemWaveAmplitude = 0.4; - - @MinNumber(0.0001) - @Desc("The number of full sine wobbles applied over the stem height for the stem wave.") - private double stemWavePeriods = 1; - - @Desc("The silhouette of the cap (dome, flat umbrella, funnel, cone, or wide shallow slab).") - private FungusCapShape capShape = FungusCapShape.DOME; - - @MinNumber(1) - @Desc("Minimum cap radius in blocks (measured from the cap center to its rim).") - private int capRadiusMin = 3; - - @MinNumber(1) - @Desc("Maximum cap radius in blocks (measured from the cap center to its rim).") - private int capRadiusMax = 5; - - @MinNumber(1) - @MaxNumber(3) - @Desc("How many blocks thick the cap shell is. 1 is a thin skin, 3 is a fleshy slab.") - private int capThickness = 1; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Vertical flatten factor for the cap. 0 leaves the cap at full height, 1 squashes it flat into a disc.") - private double capSquish = 0.4; - - @MinNumber(0) - @Desc("How far the cap rim droops downward, in degrees, curling the edge of the cap toward the ground.") - private double capDroop = 20; - - @MinNumber(0) - @Desc("How far the cap radius extends past the stem before the rim begins, in blocks. Larger values make the cap overhang the stem more.") - private double capOverhang = 2; - - @Desc("Optional block forming the gill layer on the underside of the cap (gills or a glow layer), e.g. minecraft:brown_mushroom_block or minecraft:shroomlight. Ignored when gillPalette is set or left null.") - @Ref(Reference.BLOCK) - private String gillBlock = null; - - @Desc("A noise-driven palette for the underside gill layer. When set this overrides the single gillBlock.") - private PaletteSpec gillPalette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The fraction of underside cap blocks replaced by the gill block when a gill block or palette is set.") - private double gillChance = 0.85; - - @Desc("Optional block speckled across the top of the cap by noise (white toadstool dots, warts, glowing spots), e.g. minecraft:bone_block or minecraft:white_concrete. Ignored when spotPalette is set or left null.") - @Ref(Reference.BLOCK) - private String spotBlock = null; - - @Desc("A noise-driven palette for the cap top spots. When set this overrides the single spotBlock.") - private PaletteSpec spotPalette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The fraction of top cap blocks replaced by the spot block, selected by value noise so spots cluster naturally.") - private double spotChance = 0.18; - - @Desc("If true, generate a bracket / shelf fungus instead of an upright mushroom: a small flat fan that grows sideways off a very short or absent stem, like a polypore clinging to a trunk.") - private boolean shelf = false; - - @MinNumber(1) - @Desc("The radius in blocks of the sideways fan when shelf is true.") - private int shelfRadius = 3; - - public Fungus() { - } - - public String name() { - return name; - } - - public double chance() { - return chance; - } - - public int density() { - return density; - } - - public int variants() { - return variants; - } - - public long seed() { - return seed; - } - - public ObjectPlaceMode mode() { - return mode == null ? ObjectPlaceMode.CENTER_HEIGHT : mode; - } - - public ObjectRotation rotation() { - return rotation; - } - - public ObjectLimit clamp() { - return clamp; - } - - public CarvingMode carvingSupport() { - return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; - } - - public boolean underwater() { - return underwater; - } - - public ObjectTranslate translate() { - return translate; - } - - /** Empty where the pack sets none. */ - public Optional stiltSettings() { - return Optional.ofNullable(stiltSettings); - } - - /** Empty where the pack sets none. */ - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); - } - - public String stem() { - return stem; - } - - /** Empty where the pack sets none. */ - public Optional stemPalette() { - return Optional.ofNullable(stemPalette); - } - - public String cap() { - return cap; - } - - /** Empty where the pack sets none. */ - public Optional capPalette() { - return Optional.ofNullable(capPalette); - } - - public int stemHeightMin() { - return stemHeightMin; - } - - public int stemHeightMax() { - return stemHeightMax; - } - - public int stemWidth() { - return stemWidth; - } - - public double stemCurve() { - return stemCurve; - } - - public double stemLeanAzimuth() { - return stemLeanAzimuth; - } - - public double stemWaveAmplitude() { - return stemWaveAmplitude; - } - - public double stemWavePeriods() { - return stemWavePeriods; - } - - public FungusCapShape capShape() { - return capShape == null ? FungusCapShape.DOME : capShape; - } - - public int capRadiusMin() { - return capRadiusMin; - } - - public int capRadiusMax() { - return capRadiusMax; - } - - public int capThickness() { - return capThickness; - } - - public double capSquish() { - return capSquish; - } - - public double capDroop() { - return capDroop; - } - - public double capOverhang() { - return capOverhang; - } - - /** Empty where the pack sets none. */ - public Optional gillBlock() { - return Optional.ofNullable(gillBlock); - } - - /** Empty where the pack sets none. */ - public Optional gillPalette() { - return Optional.ofNullable(gillPalette); - } - - public double gillChance() { - return gillChance; - } - - /** Empty where the pack sets none. */ - public Optional spotBlock() { - return Optional.ofNullable(spotBlock); - } - - /** Empty where the pack sets none. */ - public Optional spotPalette() { - return Optional.ofNullable(spotPalette); - } - - public double spotChance() { - return spotChance; - } - - public boolean shelf() { - return shelf; - } - - public int shelfRadius() { - return shelfRadius; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java b/src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java deleted file mode 100644 index b57ec317e..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/fungi/FungusCapShape.java +++ /dev/null @@ -1,35 +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.modules.objects.fungi; - -import com.volmit.config.Desc; - -@Desc("The silhouette of the mushroom cap. Each shape drives how the cap radius and thickness vary from its apex down to the rim, giving the fungus a distinct profile.") -public enum FungusCapShape { - @Desc("A rounded hemisphere cap that bulges up and curls slightly under at the rim, the classic red toadstool dome.") - DOME, - @Desc("A wide, nearly flat umbrella that holds its full radius almost to the edge before dropping, the brown-mushroom plate look.") - FLAT, - @Desc("An upturned bowl whose rim lifts higher than its center, cupping upward like a chanterelle or funnel mushroom.") - FUNNEL, - @Desc("A tall pointed cone that tapers from a broad base to a sharp apex, the witch-hat parasol silhouette.") - CONICAL, - @Desc("A very wide but shallow slab, a low overhanging shelf-like roof that spreads far past the stem with minimal vertical rise.") - FLAT_WIDE -} diff --git a/src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java b/src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java deleted file mode 100644 index 3de150eef..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/ruin/Ruin.java +++ /dev/null @@ -1,286 +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.modules.objects.ruin; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -@Snippet("iris/objects/ruin") -@Desc("A single procedurally generated ruin: a crumbling man-made structure (pillar, wall, arch, foundation slab, or rubble pile). Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file. Weathering swaps blocks for mossy or cracked variants by noise, erosion deletes blocks so the shape reads as collapsed, and a buried fraction sinks the ruin into the terrain.") -public final class Ruin { - @Desc("A human readable name used in logs and as the variant load key (procedural/#).") - private String name = "ruin"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance (0-1) per chunk for this ruin to attempt placement. Use density to attempt more than one per chunk once the chance check passes.") - private double chance = 0.05; - - @MinNumber(1) - @Desc("If the chance check passes, attempt this many placements in the chunk. Defaults to a single ruin per qualifying chunk.") - private int density = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("How many distinct variants to pre-bake for this ruin. Higher means more variety (different heights, gap patterns, erosion seeds) at a small memory cost.") - private int variants = 6; - - @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants. Every random choice (size, weathering mask, erosion mask, accents) is derived from this.") - private long seed = 1337; - - @Desc("The placement mode used to anchor the ruin to the terrain. MIN_HEIGHT plants the lowest footprint corner on the ground (good for slabs and rubble on slopes); CENTER_HEIGHT averages the footprint (good for tall pillars and arches).") - private ObjectPlaceMode mode = ObjectPlaceMode.MIN_HEIGHT; - - @Desc("Rotate this ruin's placement so variants do not all face the same way.") - private ObjectRotation rotation = new ObjectRotation(); - - @Desc("Limit the max or min terrain height at which this ruin may place.") - private ObjectLimit clamp = new ObjectLimit(); - - @Desc("Whether this ruin may place on the terrain surface, under carvings (caves), or both. SURFACE_ONLY keeps ruins above ground.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - - @Desc("If true the ruin anchors on the terrain height ignoring the water surface, so it can sit submerged. If false (default) it anchors to the surface and avoids water.") - private boolean underwater = false; - - @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private ObjectTranslate translate = new ObjectTranslate(); - - @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private StiltSettings stiltSettings; - - @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private VacuumSettings vacuumSettings; - - @Required - @Desc("The primary structural block, e.g. minecraft:cobblestone or minecraft:stone_bricks. Ignored when blockPalette is set. This is the bulk material of the ruin before weathering swaps some of it out.") - @Ref(Reference.BLOCK) - private String block = "minecraft:cobblestone"; - - @Desc("A noise-driven palette for the primary block. When set this overrides the single block, letting the structure mix materials by noise. Palette wins over the block string via IrisProceduralBlocks.resolve.") - private PaletteSpec blockPalette; - - @Desc("The overall silhouette of the ruin: PILLAR (broken column), WALL (gapped segment), ARCH (two legs plus a curved span), FLOOR_SLAB (foundation patch), or RUBBLE (low scattered pile).") - private RuinForm form = RuinForm.PILLAR; - - @MinNumber(1) - @Desc("Minimum structure height in blocks (PILLAR/WALL/ARCH height, slab thickness for FLOOR_SLAB, mound height for RUBBLE). Variants interpolate between this and heightMax.") - private int heightMin = 4; - - @MinNumber(1) - @Desc("Maximum structure height in blocks. Variants interpolate between heightMin and this so taller and shorter ruins coexist.") - private int heightMax = 9; - - @MinNumber(1) - @Desc("Minimum footprint width (X axis) in blocks: column/leg thickness for PILLAR/ARCH, wall thickness for WALL, slab width for FLOOR_SLAB, blob width for RUBBLE.") - private int widthMin = 1; - - @MinNumber(1) - @Desc("Maximum footprint width (X axis) in blocks. Variants interpolate between widthMin and this.") - private int widthMax = 3; - - @MinNumber(1) - @Desc("Minimum footprint length (Z axis) in blocks: wall run length, arch leg spacing, slab length, rubble blob length.") - private int lengthMin = 3; - - @MinNumber(1) - @Desc("Maximum footprint length (Z axis) in blocks. Variants interpolate between lengthMin and this.") - private int lengthMax = 7; - - @Desc("A palette of weathered variants (mossy/cracked block ids) blended over the structure by noise. When set this drives weathering; otherwise weatheredBlock is used.") - private PaletteSpec weatheringPalette; - - @Desc("A single weathered block id used when weatheringPalette is not set, e.g. minecraft:mossy_cobblestone. Applied to a noise-selected fraction of the structure, biased toward the lower rows.") - @Ref(Reference.BLOCK) - private String weatheredBlock = "minecraft:mossy_cobblestone"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How much of the structure is replaced by weathered blocks (0 none, 1 nearly all). The replacement mask is value-noise driven and weighted so lower rows weather more than upper rows, mimicking moss climbing from the ground.") - private double mossiness = 0.45; - - @MinNumber(0) - @MaxNumber(8) - @Desc("The scale of the weathering noise. Higher values produce smaller, busier moss/crack patches; lower values produce broad continuous weathered zones.") - private double weatheringScale = 1.0; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How crumbled the ruin is (0 intact, 1 mostly gone). Blocks whose value-noise falls below this threshold are deleted, so the shape reads as collapsed. Structural integrity is preserved: the bottom row and core legs are never eroded away.") - private double erosion = 0.25; - - @MinNumber(0) - @MaxNumber(8) - @Desc("The scale of the erosion noise. Higher values knock out small speckled holes; lower values carve larger missing chunks out of the silhouette.") - private double erosionScale = 1.5; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How far the structure extends below the surface as a fraction of its height (0 sits fully on top, 1 sinks it a full height into the ground). The buried rows live at negative y so the ruin reads as settled and partly swallowed by the terrain.") - private double buriedFraction = 0.2; - - @MinItems(1) - @Desc("Accent decorators applied after the ruin is built and eroded (moss carpets and lanterns on broken tops, vines and lichen on the faces, rubble and growth scattered around the base).") - private List accents = List.of(); - - public Ruin() { - } - - public String name() { - return name; - } - - public double chance() { - return chance; - } - - public int density() { - return density; - } - - public int variants() { - return variants; - } - - public long seed() { - return seed; - } - - public ObjectPlaceMode mode() { - return mode == null ? ObjectPlaceMode.MIN_HEIGHT : mode; - } - - public ObjectRotation rotation() { - return rotation; - } - - public ObjectLimit clamp() { - return clamp; - } - - public CarvingMode carvingSupport() { - return carvingSupport == null ? CarvingMode.SURFACE_ONLY : carvingSupport; - } - - public boolean underwater() { - return underwater; - } - - public ObjectTranslate translate() { - return translate; - } - - /** Empty where the pack sets none. */ - public Optional stiltSettings() { - return Optional.ofNullable(stiltSettings); - } - - /** Empty where the pack sets none. */ - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); - } - - public String block() { - return block; - } - - /** Empty where the pack sets none. */ - public Optional blockPalette() { - return Optional.ofNullable(blockPalette); - } - - public RuinForm form() { - return form == null ? RuinForm.PILLAR : form; - } - - public int heightMin() { - return heightMin; - } - - public int heightMax() { - return heightMax; - } - - public int widthMin() { - return widthMin; - } - - public int widthMax() { - return widthMax; - } - - public int lengthMin() { - return lengthMin; - } - - public int lengthMax() { - return lengthMax; - } - - /** Empty where the pack sets none. */ - public Optional weatheringPalette() { - return Optional.ofNullable(weatheringPalette); - } - - public String weatheredBlock() { - return weatheredBlock; - } - - public double mossiness() { - return mossiness; - } - - public double weatheringScale() { - return weatheringScale; - } - - public double erosion() { - return erosion; - } - - public double erosionScale() { - return erosionScale; - } - - public double buriedFraction() { - return buriedFraction; - } - - public List accents() { - return accents == null ? List.of() : Collections.unmodifiableList(accents); - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java deleted file mode 100644 index 5c77731b2..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/ruin/RuinDecorator.java +++ /dev/null @@ -1,78 +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.modules.objects.ruin; - -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Optional; - -@Snippet("iris/objects/ruin-decorator") -@Desc("An accent block applied to a generated ruin after it is built and eroded, such as moss carpets on broken tops, vines on the faces, or rubble scattered around the base.") -public final class RuinDecorator { - @Desc("Where on the ruin this accent is placed. TOP sits on the highest block of each column, SURFACE clings to air-facing vertical faces, BASE_SCATTER rings the ground footprint around the base.") - private RuinDecoratorTarget target = RuinDecoratorTarget.TOP; - - @Required - @Desc("The block id to place, e.g. minecraft:moss_carpet or minecraft:vine. Ignored when palette is set.") - @Ref(Reference.BLOCK) - private String block = ""; - - @Desc("A noise-driven palette for this decorator. When set this overrides the single block, letting the accent mix blocks by noise. Resolved through IrisProceduralBlocks.resolve so the palette wins over the string.") - private PaletteSpec palette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance (0-1) per candidate position for this decorator to actually place. 1 covers every candidate, lower values leave sparse, patchy accents.") - private double chance = 0.4; - - @MinNumber(1) - @Desc("For the BASE_SCATTER target, how many blocks beyond the ruin footprint the scatter ring extends outward in each direction. Higher values fling rubble and growth further from the structure.") - private int scatterRadius = 2; - - public RuinDecorator() { - } - - public RuinDecoratorTarget target() { - return target == null ? RuinDecoratorTarget.TOP : target; - } - - public String block() { - return block; - } - - /** Empty where the pack sets none. */ - public Optional palette() { - return Optional.ofNullable(palette); - } - - public double chance() { - return chance; - } - - public int scatterRadius() { - return scatterRadius; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java b/src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java deleted file mode 100644 index 9b469e02f..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/ruin/RuinForm.java +++ /dev/null @@ -1,35 +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.modules.objects.ruin; - -import com.volmit.config.Desc; - -@Desc("The overall silhouette of a procedural ruin. Each form rasterizes a different crumbling man-made shape from the same size, weathering, and erosion settings.") -public enum RuinForm { - @Desc("A broken vertical column. A square trunk (widthMin..widthMax footprint) rises to a randomized height then snaps off with a jagged crown, leaving a toppled stub. Use for ancient pillars and obelisk stumps.") - PILLAR, - @Desc("A standing wall segment. A flat slab spanning lengthMin..lengthMax long and heightMin..heightMax tall, thickness widthMin..widthMax, punched through with noise-driven gaps and a ragged top edge. Use for collapsed building sides and fortifications.") - WALL, - @Desc("A freestanding arch. Two legs spaced by lengthMin..lengthMax joined at the top by a rasterized semicircular span (the lintel), so the structure literally arches. Use for gateways, aqueduct bays, and ruined doorways.") - ARCH, - @Desc("A flat foundation patch. A single (or few) block-thick slab covering a widthMin..lengthMax footprint at ground level, heavily eroded into an irregular outline. Use for floor remnants, plazas, and building foundations.") - FLOOR_SLAB, - @Desc("A low scattered debris pile. A noise blob of partial blocks mounded near the ground, tallest at the center and thinning toward the edges. Use for collapsed-structure rubble and scree.") - RUBBLE -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/Tree.java b/src/main/java/art/arcane/iris/modules/objects/tree/Tree.java deleted file mode 100644 index 49d18a983..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/Tree.java +++ /dev/null @@ -1,511 +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.modules.objects.tree; - -import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.builtin.carve.CarvingMode; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.builtin.prepare.ObjectTranslate; -import art.arcane.iris.builtin.stilt.StiltSettings; -import art.arcane.iris.builtin.vacuum.VacuumSettings; -import art.arcane.iris.builtin.validate.ObjectLimit; -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; -import com.volmit.config.Snippet; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -@Snippet("iris/objects/procedural-tree") -@Desc("A single procedurally generated tree. Iris bakes a pool of deterministic variants from these settings and scatters them at world-gen time, exactly like an object placement but generated from scratch instead of loaded from an iob file.") -public final class Tree { - @Desc("A human readable name used in logs and as the variant load key.") - private String name = "procedural-tree"; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per chunk for this tree to attempt placement. Use density for multiple per chunk.") - private double chance = 0.4; - - @MinNumber(1) - @Desc("If the chance check passes, attempt this many placements in the chunk.") - private int density = 1; - - @MinNumber(1) - @MaxNumber(64) - @Desc("How many distinct variants to pre-bake for this tree. Higher means more variety at a small memory cost.") - private int variants = 8; - - @Desc("The base seed for deterministic generation. The same seed and settings always bake the same variants.") - private long seed = 1337; - - @Desc("If true (default) leaves are placed with vanilla distance-from-wood values and persistent=false so leaf decay behaves naturally and the tree reads as plausible. If false, leaves are forced persistent and never decay (a raw object dump).") - private boolean plausible = true; - - @Desc("The placement mode used to anchor the tree to the terrain.") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - - @Desc("Rotate this tree's placement.") - private ObjectRotation rotation = new ObjectRotation(); - - @Desc("Limit the max or min height of placement.") - private ObjectLimit clamp = new ObjectLimit(); - - @Desc("Whether this tree may place on the terrain surface, under carvings, or both.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - - @Desc("If true, the tree anchors on the terrain height ignoring the water surface.") - private boolean underwater = false; - - @Desc("Translate (offset) this placement along each axis; for example set a negative y to sink it into the ground.") - private ObjectTranslate translate = new ObjectTranslate(); - - @Desc("Settings for the stilt place modes (STILT, MIN_STILT, FAST_STILT, CENTER_STILT, ERODE_STILT, ORGANIC_STILT).") - private StiltSettings stiltSettings; - - @Desc("Settings for the vacuum place modes (VACUUM, VACUUM_HIGH, VACUUM_FAST, VACUUM_ORGANIC).") - private VacuumSettings vacuumSettings; - - @Required - @Desc("The trunk (log) block, e.g. minecraft:oak_log. Ignored when trunkPalette is set.") - @Ref(Reference.BLOCK) - private String trunk = "minecraft:oak_log"; - - @Desc("A noise-driven palette for the trunk. When set this overrides the single trunk block, letting the trunk mix blocks by noise.") - private PaletteSpec trunkPalette; - - @Required - @Desc("The leaf block, e.g. minecraft:oak_leaves. Ignored when leavesPalette is set.") - @Ref(Reference.BLOCK) - private String leaves = "minecraft:oak_leaves"; - - @Desc("A noise-driven palette for the leaves. When set this overrides the single leaf block, letting the canopy mix leaf (or other) blocks by noise. Only blocks that are actually leaves get vanilla decay distances.") - private PaletteSpec leavesPalette; - - @Desc("The named canopy profile that drives default crown radii and shape.") - private TreeProfile profile = TreeProfile.OAK; - - @MinNumber(1) - @Desc("Minimum trunk height in blocks.") - private int heightMin = 8; - - @MinNumber(1) - @Desc("Maximum trunk height in blocks.") - private int heightMax = 12; - - @MinNumber(1) - @Desc("Base trunk width in blocks. 1 is a single column, 2 is a 2x2 trunk, etc.") - private int trunkWidth = 1; - - @Desc("The function used to shape trunk width over height.") - private TreeFunction trunkShape = TreeFunction.CONSTANT; - - @Desc("Width multiplier at the base for the LINEAR trunk shape.") - private double shapeStart = 1; - - @Desc("Width multiplier at the top for the LINEAR trunk shape.") - private double shapeEnd = 1; - - @Desc("Steepness for the SIGMOID trunk shape.") - private double shapeSteepness = 5; - - @Desc("Base for the LOG trunk shape.") - private double shapeBase = 2.718281828; - - @Desc("Period for the SINE trunk shape.") - private double shapePeriod = 1; - - @Desc("Amplitude for the SINE trunk shape.") - private double shapeAmplitude = 0.2; - - @Desc("Pinch position (0-1) for the PARABOLIC trunk shape.") - private double shapePeakOffset = 0.5; - - @Desc("Minimum width fraction at the waist for the PARABOLIC trunk shape.") - private double shapeFloor = 0.5; - - @Desc("Compass direction in degrees the trunk leans toward.") - private double leanAzimuth = 0; - - @Desc("How far the trunk leans, in degrees from vertical. 0 is perfectly upright.") - private double leanAngle = 0; - - @Desc("How the lean accumulates over height.") - private TreeFunction trunkCurve = TreeFunction.LINEAR; - - @Desc("Steepness for the SIGMOID trunk curve.") - private double curveSteepness = 8; - - @Desc("How the lean azimuth itself changes over height (for spiraling or wandering trunks).") - private TreeAzimuthMode leanAzimuthMode = TreeAzimuthMode.CONSTANT; - - @Desc("Azimuth at the base for the LINEAR azimuth mode.") - private double azimuthStart = 0; - - @Desc("Azimuth at the top for the LINEAR azimuth mode.") - private double azimuthEnd = 0; - - @Desc("Number of full turns for the SPIRAL azimuth mode.") - private double azimuthTurns = 1; - - @Desc("Amplitude for the SINE azimuth mode.") - private double azimuthAmplitude = 90; - - @Desc("Period for the SINE azimuth mode.") - private double azimuthPeriod = 1; - - @Desc("Offset for the SINE azimuth mode.") - private double azimuthOffset = 0; - - @Desc("Scale for the NOISE azimuth mode.") - private double azimuthScale = 1; - - @MinNumber(1) - @Desc("Number of branches per whorl ring for the WHORL branch azimuth mode.") - private int azimuthWhorlCount = 5; - - @Desc("Optional accent leaf block scattered through the canopy (blossoms, shroomlight).") - @Ref(Reference.BLOCK) - private String secondaryLeaves; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The fraction of leaves replaced by the secondary leaf block(s).") - private double secondaryLeafFraction = 0.35; - - @MinItems(1) - @Desc("Optional weighted set of accent leaf blocks. When set this overrides the single secondaryLeaves block.") - private List weightedSecondaryLeaves = List.of(); - - @Desc("A noise-driven palette for the secondary (accent) leaves. When set this overrides both secondaryLeaves and weightedSecondaryLeaves.") - private PaletteSpec secondaryLeavesPalette; - - @Desc("Optional secondary trunk block used over a height band (for color-banded trunks). Ignored when secondaryTrunkPalette is set.") - @Ref(Reference.BLOCK) - private String secondaryTrunk; - - @Desc("A noise-driven palette for the secondary trunk band. When set this overrides the single secondaryTrunk block.") - private PaletteSpec secondaryTrunkPalette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The normalized height where the secondary trunk band starts.") - private double secondaryTrunkStart = 0.5; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The normalized height where the secondary trunk band ends.") - private double secondaryTrunkEnd = 1; - - @Desc("If true, a root system extends below (and around) the base so the tree connects to the ground on uneven terrain.") - private boolean roots = true; - - @Desc("How the root system is built when roots is true.") - private TreeRootStyle rootStyle = TreeRootStyle.BUTTRESS; - - @MinNumber(0) - @Desc("Override the root depth/reach in blocks. 0 means auto (scales with tree height).") - private int rootDepth = 0; - - @MinNumber(0) - @Desc("Override the root flare radius in blocks. 0 means auto.") - private double rootFlare = 0; - - @MinNumber(1) - @MaxNumber(6) - @Desc("How many separate trunks the tree splits into above forkHeight. 1 is a single trunk.") - private int trunkForks = 1; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The normalized height where the trunk splits into forks.") - private double forkHeight = 0.5; - - @Desc("The outward lean angle in degrees of each fork.") - private double forkAngle = 25; - - @Desc("The leaf crown configuration.") - private TreeCanopy canopy = new TreeCanopy(); - - @MinItems(1) - @Desc("Accent decorators applied after the tree is built (fruit, vines, snow, glow).") - private List decorators = List.of(); - - public Tree() { - } - - /** The key the variant {@code index} of the tree named {@code name} is loaded under, which placement markers and the sapling tree list name. */ - public static String variantLoadKey(String name, int index) { - if (index < 0) { - throw new IllegalArgumentException("index must not be negative"); - } - return "procedural/tree/" + name + "#" + index; - } - - public String name() { - return name; - } - - public double chance() { - return chance; - } - - public int density() { - return density; - } - - public int variants() { - return variants; - } - - public long seed() { - return seed; - } - - public boolean plausible() { - return plausible; - } - - public ObjectPlaceMode mode() { - return mode; - } - - public ObjectRotation rotation() { - return rotation; - } - - public ObjectLimit clamp() { - return clamp; - } - - public CarvingMode carvingSupport() { - return carvingSupport; - } - - public boolean underwater() { - return underwater; - } - - public ObjectTranslate translate() { - return translate; - } - - public Optional stiltSettings() { - return Optional.ofNullable(stiltSettings); - } - - public Optional vacuumSettings() { - return Optional.ofNullable(vacuumSettings); - } - - public String trunk() { - return trunk; - } - - public Optional trunkPalette() { - return Optional.ofNullable(trunkPalette); - } - - public String leaves() { - return leaves; - } - - public Optional leavesPalette() { - return Optional.ofNullable(leavesPalette); - } - - public TreeProfile profile() { - return profile; - } - - public int heightMin() { - return heightMin; - } - - public int heightMax() { - return heightMax; - } - - public int trunkWidth() { - return trunkWidth; - } - - public TreeFunction trunkShape() { - return trunkShape; - } - - public double shapeStart() { - return shapeStart; - } - - public double shapeEnd() { - return shapeEnd; - } - - public double shapeSteepness() { - return shapeSteepness; - } - - public double shapeBase() { - return shapeBase; - } - - public double shapePeriod() { - return shapePeriod; - } - - public double shapeAmplitude() { - return shapeAmplitude; - } - - public double shapePeakOffset() { - return shapePeakOffset; - } - - public double shapeFloor() { - return shapeFloor; - } - - public double leanAzimuth() { - return leanAzimuth; - } - - public double leanAngle() { - return leanAngle; - } - - public TreeFunction trunkCurve() { - return trunkCurve; - } - - public double curveSteepness() { - return curveSteepness; - } - - public TreeAzimuthMode leanAzimuthMode() { - return leanAzimuthMode; - } - - public double azimuthStart() { - return azimuthStart; - } - - public double azimuthEnd() { - return azimuthEnd; - } - - public double azimuthTurns() { - return azimuthTurns; - } - - public double azimuthAmplitude() { - return azimuthAmplitude; - } - - public double azimuthPeriod() { - return azimuthPeriod; - } - - public double azimuthOffset() { - return azimuthOffset; - } - - public double azimuthScale() { - return azimuthScale; - } - - public int azimuthWhorlCount() { - return azimuthWhorlCount; - } - - public Optional secondaryLeaves() { - return Optional.ofNullable(secondaryLeaves); - } - - public double secondaryLeafFraction() { - return secondaryLeafFraction; - } - - public List weightedSecondaryLeaves() { - return weightedSecondaryLeaves == null ? List.of() : Collections.unmodifiableList(weightedSecondaryLeaves); - } - - public Optional secondaryLeavesPalette() { - return Optional.ofNullable(secondaryLeavesPalette); - } - - public Optional secondaryTrunk() { - return Optional.ofNullable(secondaryTrunk); - } - - public Optional secondaryTrunkPalette() { - return Optional.ofNullable(secondaryTrunkPalette); - } - - public double secondaryTrunkStart() { - return secondaryTrunkStart; - } - - public double secondaryTrunkEnd() { - return secondaryTrunkEnd; - } - - public boolean roots() { - return roots; - } - - public TreeRootStyle rootStyle() { - return rootStyle; - } - - public int rootDepth() { - return rootDepth; - } - - public double rootFlare() { - return rootFlare; - } - - public int trunkForks() { - return trunkForks; - } - - public double forkHeight() { - return forkHeight; - } - - public double forkAngle() { - return forkAngle; - } - - public TreeCanopy canopy() { - return canopy; - } - - public List decorators() { - return decorators == null ? List.of() : Collections.unmodifiableList(decorators); - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java deleted file mode 100644 index 92ffc4a19..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeAzimuthMode.java +++ /dev/null @@ -1,45 +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.modules.objects.tree; - -import com.volmit.config.Desc; - -@Desc("Controls the compass direction (azimuth) of trunk lean as it rises, or the direction each branch is thrown.") -public enum TreeAzimuthMode { - @Desc("A single fixed azimuth.") - CONSTANT, - @Desc("Azimuth ramps straight from start to end with height.") - LINEAR, - @Desc("Azimuth winds around the trunk a number of turns (corkscrew).") - SPIRAL, - @Desc("Azimuth oscillates with a sine wave.") - SINE, - @Desc("Azimuth wanders using deterministic noise.") - NOISE, - @Desc("Each branch picks a uniformly random azimuth (falls back to constant for trunk lean).") - RANDOM, - @Desc("Phyllotaxis: each successive branch is offset by the 137.5 degree golden angle for the most natural spiral packing (branches).") - GOLDEN_ANGLE, - @Desc("Each successive branch is thrown to the opposite side (180 degrees apart).") - ALTERNATING, - @Desc("Branches are grouped into evenly spaced whorls of azimuthWhorlCount around each ring.") - WHORL, - @Desc("Azimuth zigzags by +/- amplitude on alternating branches.") - ZIGZAG -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java deleted file mode 100644 index d0b680898..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranchProbability.java +++ /dev/null @@ -1,47 +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.modules.objects.tree; - -import com.volmit.config.Desc; - -@Desc("Controls how the chance of spawning a branch varies with trunk height (0 at the base, 1 at the top).") -public enum TreeBranchProbability { - @Desc("Same branch chance at every height.") - CONSTANT, - @Desc("Ramps straight from base chance to crown chance.") - LINEAR, - @Desc("S-curve that switches on around a midpoint height.") - SIGMOID, - @Desc("Chance rises with height raised to an exponent, clustering branches near the crown.") - TOP_HEAVY, - @Desc("Bell curve peaking in a height band.") - GAUSSIAN, - @Desc("Irregular organic branching from deterministic noise.") - NOISE, - @Desc("Chance falls with height (1-t)^exponent, clustering branches near the base.") - BOTTOM_HEAVY, - @Desc("Regular whorl rings of branches at evenly spaced heights (periods controls count).") - PERIODIC, - @Desc("Branches only within a height window around mean +/- std.") - BAND, - @Desc("Inverse of GAUSSIAN: branches avoid the mean band and favor base and crown.") - INVERSE_GAUSSIAN, - @Desc("Exponential decay from the base upward (constant * e^-exponent*t).") - EXPONENTIAL_DECAY -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java deleted file mode 100644 index 62ff4bf6b..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeBranches.java +++ /dev/null @@ -1,237 +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.modules.objects.tree; - -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; - -import java.util.Optional; - -@Snippet("iris/objects/tree-branches") -@Desc("A branch system that throws limbs out of the trunk and places a leaf ball at each tip. When present, branches drive the canopy and only the topmost crown disc of the profile is still placed.") -public final class TreeBranches { - @Desc("How branch spawn chance varies over trunk height.") - private TreeBranchProbability probabilityFunction = TreeBranchProbability.TOP_HEAVY; - - @MinNumber(0) - @Desc("Branch chance for the CONSTANT probability function.") - private double probabilityConstant = 0.5; - - @MinNumber(0) - @Desc("Branch chance at the base for the LINEAR probability function.") - private double probabilityBase = 0; - - @MinNumber(0) - @Desc("Branch chance at the crown for the LINEAR probability function.") - private double probabilityCrown = 1; - - @Desc("Steepness for the SIGMOID probability function.") - private double probabilitySteepness = 10; - - @Desc("Midpoint height (0-1) for the SIGMOID probability function.") - private double probabilityMidpoint = 0.7; - - @Desc("Exponent for the TOP_HEAVY probability function.") - private double probabilityExponent = 2; - - @Desc("Mean height (0-1) for the GAUSSIAN probability function.") - private double probabilityMean = 0.7; - - @Desc("Standard deviation for the GAUSSIAN probability function.") - private double probabilityStd = 0.15; - - @Desc("Noise scale for the NOISE probability function.") - private double probabilityScale = 1; - - @MinNumber(0) - @Desc("Number of whorl rings over the trunk height for the PERIODIC probability function.") - private double probabilityPeriods = 5; - - @Desc("How branch length varies over trunk height.") - private TreeFunction lengthFunction = TreeFunction.LINEAR; - - @MinNumber(0) - @Desc("Branch length at the base for the LINEAR length function.") - private double lengthBase = 1; - - @MinNumber(0) - @Desc("Branch length at the crown for the LINEAR length function.") - private double lengthCrown = 4; - - @MinNumber(0) - @Desc("Branch length for the CONSTANT length function.") - private double lengthConstant = 3; - - @MinNumber(0) - @Desc("Maximum branch length for the SIGMOID, LOG and PARABOLIC length functions.") - private double lengthMax = 4; - - @Desc("Steepness for the SIGMOID length function.") - private double lengthSteepness = 5; - - @Desc("How the compass direction of each branch is chosen.") - private TreeAzimuthMode azimuthMode = TreeAzimuthMode.RANDOM; - - @Desc("Fixed azimuth in degrees when azimuthMode is CONSTANT.") - private double azimuth = 0; - - @Desc("Elevation angle in degrees from horizontal. 0 is flat, positive points up, negative droops down.") - private double elevation = 0; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How much each branch sags/droops along its length (catenary). 0 is a straight branch; higher values arc the branch and its tip downward.") - private double sag = 0; - - @MinNumber(0) - @MaxNumber(6) - @Desc("How many recursive levels of sub-branches to grow. 0 is none, 1 is a single level, 2+ produces fractal branching.") - private int branchDepth = 1; - - @Desc("If true, branches are clamped to never droop below horizontal (useful for upright species).") - private boolean leafStartUp = false; - - @MinNumber(0) - @Desc("Leaf ball radius placed at each branch tip.") - private int clusterRadius = 2; - - @Desc("How the branch tip leaf cluster fills.") - private TreeLeafMode clusterMode = TreeLeafMode.TRIMMED; - - @MinNumber(0) - @Desc("Fill density for the branch tip leaf cluster when clusterMode is density or noise.") - private double clusterDensity = 0.85; - - @Desc("Optional one level of recursive sub-branches sprouting from each branch tip.") - private TreeSubBranches subBranches = null; - - public TreeBranches() { - } - - public TreeBranchProbability probabilityFunction() { - return probabilityFunction == null ? TreeBranchProbability.TOP_HEAVY : probabilityFunction; - } - - public double probabilityConstant() { - return probabilityConstant; - } - - public double probabilityBase() { - return probabilityBase; - } - - public double probabilityCrown() { - return probabilityCrown; - } - - public double probabilitySteepness() { - return probabilitySteepness; - } - - public double probabilityMidpoint() { - return probabilityMidpoint; - } - - public double probabilityExponent() { - return probabilityExponent; - } - - public double probabilityMean() { - return probabilityMean; - } - - public double probabilityStd() { - return probabilityStd; - } - - public double probabilityScale() { - return probabilityScale; - } - - public double probabilityPeriods() { - return probabilityPeriods; - } - - public TreeFunction lengthFunction() { - return lengthFunction == null ? TreeFunction.LINEAR : lengthFunction; - } - - public double lengthBase() { - return lengthBase; - } - - public double lengthCrown() { - return lengthCrown; - } - - public double lengthConstant() { - return lengthConstant; - } - - public double lengthMax() { - return lengthMax; - } - - public double lengthSteepness() { - return lengthSteepness; - } - - public TreeAzimuthMode azimuthMode() { - return azimuthMode == null ? TreeAzimuthMode.RANDOM : azimuthMode; - } - - public double azimuth() { - return azimuth; - } - - public double elevation() { - return elevation; - } - - public double sag() { - return sag; - } - - public int branchDepth() { - return branchDepth; - } - - public boolean leafStartUp() { - return leafStartUp; - } - - public int clusterRadius() { - return clusterRadius; - } - - public TreeLeafMode clusterMode() { - return clusterMode == null ? TreeLeafMode.TRIMMED : clusterMode; - } - - public double clusterDensity() { - return clusterDensity; - } - - /** Empty where the pack sets none. */ - public Optional subBranches() { - return Optional.ofNullable(subBranches); - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java deleted file mode 100644 index 2d8fc1e7e..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeCanopy.java +++ /dev/null @@ -1,102 +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.modules.objects.tree; - -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; -import com.volmit.config.MinNumber; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; - -@Snippet("iris/objects/tree-canopy") -@Desc("The leaf crown of a procedural tree. Built from stacked dome-shaped discs (driven by the profile or by explicit layers) and optionally a branch system.") -public final class TreeCanopy { - @MinNumber(0) - @MaxNumber(180) - @Desc("Elevation angle in degrees from vertical for each leaf dome. 90 is a flat disc, below 90 domes downward into a sphere, above 90 flares outward into an umbrella.") - private double startAngle = 90; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Vertical scale of the canopy volume. Lower values flatten the crown.") - private double squish = 1; - - @Desc("How leaves fill each canopy disc.") - private TreeLeafMode mode = TreeLeafMode.TRIMMED; - - @MinNumber(0) - @MaxNumber(1) - @Desc("Fill probability used by the density and noise leaf modes.") - private double leafDensity = 0.85; - - @MinNumber(0.1) - @Desc("Horizontal X stretch of the crown for elliptical or wind-blown shapes. 1 is circular.") - private double crownStretchX = 1; - - @MinNumber(0.1) - @Desc("Horizontal Z stretch of the crown for elliptical or wind-blown shapes. 1 is circular.") - private double crownStretchZ = 1; - - @MinItems(1) - @Desc("Optional explicit crown discs. When provided these replace the profile-driven layers and let you sculpt the silhouette by hand.") - private List layers = List.of(); - - @Desc("Optional branch system. When present, branches build most of the canopy and only the topmost profile disc is still placed as a crown.") - private TreeBranches branches = null; - - public TreeCanopy() { - } - - public double startAngle() { - return startAngle; - } - - public double squish() { - return squish; - } - - public TreeLeafMode mode() { - return mode == null ? TreeLeafMode.TRIMMED : mode; - } - - public double leafDensity() { - return leafDensity; - } - - public double crownStretchX() { - return crownStretchX; - } - - public double crownStretchZ() { - return crownStretchZ; - } - - public List layers() { - return layers == null ? List.of() : Collections.unmodifiableList(layers); - } - - /** Empty where the pack sets none. */ - public Optional branches() { - return Optional.ofNullable(branches); - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java deleted file mode 100644 index 926a23ad6..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecorator.java +++ /dev/null @@ -1,85 +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.modules.objects.tree; - -import com.volmit.block.PaletteSpec; -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -import java.util.Optional; - -@Snippet("iris/objects/tree-decorator") -@Desc("An accent block applied to a generated tree such as fruit on branch tips, vines on the trunk, snow on the crown, or a glowing underside.") -public final class TreeDecorator { - @Desc("Where this decorator is placed on the tree.") - private TreeDecoratorTarget target = TreeDecoratorTarget.BRANCH_TIP; - - @Required - @Desc("The block id to place, e.g. minecraft:magma_block. Ignored when palette is set.") - @Ref(Reference.BLOCK) - private String block = ""; - - @Desc("A noise-driven palette for this decorator. When set this overrides the single block.") - private PaletteSpec palette; - - @MinNumber(0) - @MaxNumber(1) - @Desc("The chance per candidate position for this decorator to place.") - private double chance = 0.5; - - @MinNumber(1) - @Desc("Maximum strand length downward for the CANOPY_HANG target (random 1..length per column).") - private int length = 1; - - @Desc("If true the block's facing is oriented away from the trunk (for trunk-mounted fences/gates/banners).") - private boolean axisAware = false; - - public TreeDecorator() { - } - - public TreeDecoratorTarget target() { - return target == null ? TreeDecoratorTarget.BRANCH_TIP : target; - } - - public String block() { - return block; - } - - /** Empty where the pack sets none. */ - public Optional palette() { - return Optional.ofNullable(palette); - } - - public double chance() { - return chance; - } - - public int length() { - return length; - } - - public boolean axisAware() { - return axisAware; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java deleted file mode 100644 index 87137f3ec..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeDecoratorTarget.java +++ /dev/null @@ -1,45 +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.modules.objects.tree; - -import com.volmit.config.Desc; - -@Desc("Where a tree decorator block is placed.") -public enum TreeDecoratorTarget { - @Desc("At the tip of each generated branch (vines, fruit, lanterns).") - BRANCH_TIP, - @Desc("On air-facing sides of trunk and branch blocks (vines, moss).") - TRUNK_SURFACE, - @Desc("On top of the highest block in each column (snow, sculk).") - CANOPY_TOP, - @Desc("One block below the lowest leaf in each column (glowing underside).") - CANOPY_BOTTOM, - @Desc("Around the y=0 ring at the base of the trunk (roots, mushrooms).") - TRUNK_BASE, - @Desc("On air-facing sides of leaf blocks (berries, lights nestled in the foliage).") - LEAF_SURFACE, - @Desc("Hanging strands of up to 'length' blocks below the lowest leaf in each column (vines, icicles).") - CANOPY_HANG, - @Desc("On the top face of trunk and branch blocks (moss, snow on limbs).") - BRANCH_SURFACE, - @Desc("One block above the very top of the trunk (nest, beehive, beacon).") - TRUNK_TOP, - @Desc("Scattered across the ground footprint around the base, wider than the trunk-base ring.") - GROUND_SCATTER -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java deleted file mode 100644 index 7dd34331a..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeFunction.java +++ /dev/null @@ -1,47 +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.modules.objects.tree; - -import com.volmit.config.Desc; - -@Desc("A shaping function evaluated over normalized height (0 at the base, 1 at the top). Used for trunk width, trunk curve and branch length.") -public enum TreeFunction { - @Desc("Same value at every height.") - CONSTANT, - @Desc("Ramps straight from start to end.") - LINEAR, - @Desc("S-curve transition controlled by steepness.") - SIGMOID, - @Desc("Logarithmic falloff controlled by base.") - LOG, - @Desc("Sine ripple controlled by period and amplitude.") - SINE, - @Desc("Parabolic pinch, narrowest at peakOffset.") - PARABOLIC, - @Desc("Geometric (exponential) interpolation from start to end.") - EXPONENTIAL, - @Desc("Square-root ease: fast change low, slow high.") - SQRT, - @Desc("Hard step that jumps from start to end at the threshold (peakOffset).") - STEP, - @Desc("Bell bulge peaking in the middle of the height range.") - BELL, - @Desc("Smoothstep ease-in-out (3t^2 - 2t^3).") - EASE_IN_OUT -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java deleted file mode 100644 index 0a6e03fdc..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeLayer.java +++ /dev/null @@ -1,45 +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.modules.objects.tree; - -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MinNumber; - -@Snippet("iris/objects/tree-layer") -@Desc("An explicit canopy disc at a given vertical offset and radius. Define a list of these to bypass the profile and sculpt the crown by hand.") -public final class TreeLayer { - @Desc("The vertical offset of this disc, measured in blocks above the trunk base.") - private int yOffset = 0; - - @MinNumber(0.5) - @Desc("The radius of this leaf disc in blocks.") - private double radius = 2; - - public TreeLayer() { - } - - public int yOffset() { - return yOffset; - } - - public double radius() { - return radius; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java deleted file mode 100644 index 40bfebcc8..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeLeafMode.java +++ /dev/null @@ -1,43 +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.modules.objects.tree; - -import com.volmit.config.Desc; - -@Desc("How leaves fill a disc or cluster.") -public enum TreeLeafMode { - @Desc("Corner-trimmed disc/sphere for a rounded silhouette.") - TRIMMED, - @Desc("Completely filled disc/sphere.") - FILLED, - @Desc("Seeded probabilistic falloff toward the edge controlled by leafDensity.") - DENSITY, - @Desc("Seeded value-noise mask controlled by leafDensity.") - NOISE, - @Desc("Only the outer shell is placed, leaving the interior hollow.") - HOLLOW, - @Desc("Quadratic radial gradient: dense at the center, thinning sharply toward the edge.") - GRADIENT, - @Desc("Coarse low-frequency noise that forms clumps and gaps of foliage.") - CLUMPED, - @Desc("Trimmed with heavy random erosion of the outer ring for a ragged, weathered look.") - TATTERED, - @Desc("Very thin scattering of leaves across the volume.") - SPARSE -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java deleted file mode 100644 index d079823ff..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeProfile.java +++ /dev/null @@ -1,53 +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.modules.objects.tree; - -import com.volmit.config.Desc; - -@Desc("Named canopy presets that drive default layer radii and shape, scaled to the tree height.") -public enum TreeProfile { - @Desc("Rounded broadleaf crown.") - OAK, - @Desc("Slim upright broadleaf crown.") - BIRCH, - @Desc("Narrow conifer cone.") - SPRUCE, - @Desc("Tall thin crown concentrated near the very top.") - JUNGLE, - @Desc("Flat shallow umbrella crown.") - ACACIA, - @Desc("Dense rounded broadleaf crown.") - DARK_OAK, - @Desc("Flat wide umbrella crown compressed into the top quarter (vanilla dark oak look).") - DARK_OAK_FLAT, - @Desc("Extra wide flat umbrella that overlaps into a continuous roofed canopy.") - DARK_OAK_FLAT_WIDE, - @Desc("Broad rounded blossom crown.") - CHERRY, - @Desc("Bare trunk with a small tuft of fronds only at the very top.") - PALM, - @Desc("Broad crown with wide drooping radii, ideal with a low startAngle to make a weeping skirt.") - WILLOW, - @Desc("Very narrow tall crown hugging the trunk (cypress / lombardy poplar).") - COLUMNAR, - @Desc("Squat, wide, low crown for shrubs and saplings.") - BUSH, - @Desc("Giant conifer cone for 2x2 mega spruce trunks.") - MEGA_SPRUCE -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java deleted file mode 100644 index a11d7f0f0..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeSecondaryLeaf.java +++ /dev/null @@ -1,50 +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.modules.objects.tree; - -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MinNumber; -import com.volmit.config.Ref; -import com.volmit.config.Reference; -import com.volmit.config.Required; - -@Snippet("iris/objects/tree-secondary-leaf") -@Desc("A weighted accent leaf or foliage block scattered through the canopy (blossoms, shroomlight, berries).") -public final class TreeSecondaryLeaf { - @Required - @Desc("The block id to scatter, e.g. minecraft:shroomlight") - @Ref(Reference.BLOCK) - private String block = ""; - - @MinNumber(0) - @Desc("The relative weight of this block among the secondary leaves.") - private int weight = 1; - - public TreeSecondaryLeaf() { - } - - public String block() { - return block; - } - - public int weight() { - return weight; - } -} diff --git a/src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java b/src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java deleted file mode 100644 index f9471a229..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/tree/TreeSubBranches.java +++ /dev/null @@ -1,93 +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.modules.objects.tree; - -import com.volmit.config.Desc; -import com.volmit.config.Snippet; -import com.volmit.config.MaxNumber; -import com.volmit.config.MinNumber; - -@Snippet("iris/objects/tree-sub-branches") -@Desc("One recursive level of sub-branches sprouting from each primary branch tip.") -public final class TreeSubBranches { - @MinNumber(1) - @Desc("How many sub-branches sprout from each primary branch tip.") - private int count = 1; - - @Desc("Pitch deflection in degrees applied to each sub-branch relative to its parent. Positive bends up, negative droops down. Cumulative pitch past 90 makes sub-branches point downward.") - private double pitchDelta = 0; - - @Desc("Yaw (horizontal) spread in degrees fanned between sub-branches.") - private double yawDelta = 45; - - @MinNumber(0) - @Desc("Sub-branch length as a fraction of its parent branch length.") - private double lengthScale = 0.5; - - @MinNumber(0) - @MaxNumber(1) - @Desc("How much each sub-branch sags/droops along its length (catenary).") - private double sag = 0; - - @MinNumber(0) - @Desc("Leaf ball radius placed at each sub-branch tip.") - private int clusterRadius = 1; - - @Desc("How the sub-branch tip leaf cluster fills.") - private TreeLeafMode clusterMode = TreeLeafMode.TRIMMED; - - @MinNumber(0) - @Desc("Fill density for the sub-branch leaf cluster when clusterMode is density or noise.") - private double clusterDensity = 0.85; - - public TreeSubBranches() { - } - - public int count() { - return count; - } - - public double pitchDelta() { - return pitchDelta; - } - - public double yawDelta() { - return yawDelta; - } - - public double lengthScale() { - return lengthScale; - } - - public double sag() { - return sag; - } - - public int clusterRadius() { - return clusterRadius; - } - - public TreeLeafMode clusterMode() { - return clusterMode == null ? TreeLeafMode.TRIMMED : clusterMode; - } - - public double clusterDensity() { - return clusterDensity; - } -} From f70b8a8abc67ce355ffa37e36d86a3feff3c992a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 01:18:48 +0100 Subject: [PATCH 121/139] Show the pack's objects in the studio iris:objects registers the Objects scene view: every object of the pack, listed under the folders of its file, one scene each. --- .../mantle/components/ObjectModule.java | 5 +- .../modules/objects/PackObjectScenes.java | 73 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index ba70f3bc5..81cbcecfa 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -24,6 +24,7 @@ import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; +import art.arcane.iris.modules.objects.PackObjectScenes; import art.arcane.iris.modules.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; @@ -45,7 +46,8 @@ import com.volmit.world.PackWorld; * procedural objects they place ({@link ProceduralObjectCatalog}) built ahead of generation ({@link #warmUp}). Its * reach is the pack's largest object placement. It tells * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the - * object search and studio tools, and grows the trees of saplings ({@link TreeGrowing}). + * object search and studio tools, grows the trees of saplings ({@link TreeGrowing}), and shows the pack's objects in + * the studio ({@link PackObjectScenes}). */ public final class ObjectModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @@ -69,6 +71,7 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { registry.registerResourceKind(ProceduralObjectCatalog.DEFINITIONS); registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); registry.registerLifecycle(this); + setup.tooling().registerSceneView(new PackObjectScenes()); } @Override diff --git a/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java b/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java new file mode 100644 index 000000000..a6a2c18b2 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java @@ -0,0 +1,73 @@ +/* + * 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.modules.objects; + +import com.volmit.object.GeneratedObject; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneView; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** The studio's Objects view: every object in the pack, one scene each, listed under the folders of its file. */ +public final class PackObjectScenes implements SceneView { + private static final ResourceId ID = ResourceId.parse("iris:objects"); + private static final char FOLDER_SEPARATOR = '/'; + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Objects"; + } + + @Override + public String description() { + return "Every object in the pack in 3D, with the blocks it is made of"; + } + + @Override + public List entries(PackWorld world) { + return world.resources().ids(PackResources.OBJECTS).stream() + .map(id -> entryOf(id.path())) + .toList(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + if (variant != 0) { + return Optional.empty(); + } + PackResources resources = world.resources(); + return resources.objects().object(resources.idOf(key)).map(PlaceableObject::geometry); + } + + private static SceneEntry entryOf(String key) { + int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR); + String folder = lastSeparator < 0 ? "" : key.substring(0, lastSeparator); + return new SceneEntry(key, key.substring(lastSeparator + 1), folder, 1); + } +} From cb3859b40fb03ba138dab839378f8ef364a0d9f8 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 01:28:44 +0100 Subject: [PATCH 122/139] Show every procedural object variant in the studio iris:objects registers the Procedural scene view: each procedural definition with as many variants as it asks for, baked the way the world bakes them. --- .../mantle/components/ObjectModule.java | 4 +- .../engine/procedural/ProceduralVariants.java | 5 ++ .../objects/ProceduralObjectScenes.java | 78 +++++++++++++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 81cbcecfa..b471778b2 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -25,6 +25,7 @@ import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.builtin.objects.RequireSurfaceSupportSettings; import art.arcane.iris.builtin.objects.SurfaceSupportBufferSettings; import art.arcane.iris.modules.objects.PackObjectScenes; +import art.arcane.iris.modules.objects.ProceduralObjectScenes; import art.arcane.iris.modules.objects.TreeGrowthSettings; import art.arcane.iris.builtin.objects.UpperObjectsForceSettings; import art.arcane.iris.builtin.objects.UpperObjectsSettings; @@ -47,7 +48,7 @@ import com.volmit.world.PackWorld; * reach is the pack's largest object placement. It tells * Iris which objects a chunk would get and which biomes and regions place an object ({@link ObjectLocating}), for the * object search and studio tools, grows the trees of saplings ({@link TreeGrowing}), and shows the pack's objects in - * the studio ({@link PackObjectScenes}). + * the studio with every variant of its procedural objects ({@link PackObjectScenes}, {@link ProceduralObjectScenes}). */ public final class ObjectModule implements IrisModule, ModuleLifecycle { private static final String VERSION = "built-in"; @@ -72,6 +73,7 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); registry.registerLifecycle(this); setup.tooling().registerSceneView(new PackObjectScenes()); + setup.tooling().registerSceneView(new ProceduralObjectScenes()); } @Override diff --git a/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java b/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java index 044833df0..bd4332160 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java +++ b/src/main/java/art/arcane/iris/engine/procedural/ProceduralVariants.java @@ -66,6 +66,11 @@ public abstract class ProceduralVariants { return key() + ProceduralObjectCatalog.VARIANT_SEPARATOR + index; } + /** How many variants the definition asks for, known without baking; a variant may still bake no blocks. */ + public int variantCount() { + return variantCount; + } + /** Every variant, baked on first use. */ public List variants() { List known = baked; diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java new file mode 100644 index 000000000..22db5126f --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -0,0 +1,78 @@ +/* + * 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.modules.objects; + +import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.iris.engine.procedural.ProceduralVariants; +import com.volmit.object.GeneratedObject; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.SceneEntry; +import com.volmit.tooling.SceneView; +import com.volmit.world.PackWorld; + +import java.util.List; +import java.util.Optional; + +/** + * The studio's Procedural view: every procedural object of the pack with each of its variants, baked as the world + * bakes them, so what the studio shows is what generation places. + */ +public final class ProceduralObjectScenes implements SceneView { + private static final ResourceId ID = ResourceId.parse("iris:objects/procedural"); + private static final char FOLDER_SEPARATOR = '/'; + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Procedural"; + } + + @Override + public String description() { + return "Trees, rock formations and more that Iris generates from settings, every variant in 3D"; + } + + @Override + public List entries(PackWorld world) { + ProceduralObjectCatalog catalog = ProceduralObjectCatalog.of(world); + return world.resources().ids(ProceduralObjectCatalog.DEFINITIONS).stream() + .flatMap(id -> catalog.variants(ProceduralObjectCatalog.KEY_PREFIX + id.path()).stream()) + .map(ProceduralObjectScenes::entryOf) + .toList(); + } + + @Override + public Optional scene(PackWorld world, String key, int variant) { + return ProceduralObjectCatalog.of(world).variants(ProceduralObjectCatalog.KEY_PREFIX + key) + .flatMap(variants -> variants.variant(variant)) + .map(PlaceableObject::geometry); + } + + private static SceneEntry entryOf(ProceduralVariants variants) { + String path = variants.path(); + int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); + String folder = lastSeparator < 0 ? "" : path.substring(0, lastSeparator); + return new SceneEntry(path, path.substring(lastSeparator + 1), folder, variants.variantCount()); + } +} From 949d2ecac3d5e2507891bc6a9181ecf3c0eab30f Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 02:39:43 +0100 Subject: [PATCH 123/139] Add the Palettes studio view to iris:terrain BiomePalettes lists each biome's surface, sea and cave ceiling layers, its wall and its slab, and lays out the blocks one places at each depth. It picks with each stage's own random (terrain, carve, post) and stacks layers from the top as generation does, so the noise is seeded the same; against a saved world the in-palette picks match (99.7% on Emberbark Woods). Slope conditions are ignored and noted in the entry's facts. --- .../iris/engine/actuator/TerrainModule.java | 2 + .../mantle/components/ObjectModule.java | 4 +- .../iris/modules/terrain/BiomeLayers.java | 51 ++++ .../iris/modules/terrain/BiomePalettes.java | 279 ++++++++++++++++++ 4 files changed, 334 insertions(+), 2 deletions(-) create mode 100644 src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index 43565565f..f5b58baea 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.actuator; import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.builtin.terrain.BedrockSettings; +import art.arcane.iris.modules.terrain.BiomePalettes; import art.arcane.iris.modules.terrain.CaveCeilingLayersSettings; import art.arcane.iris.modules.terrain.ExplodeBiomePaletteSizeSettings; import art.arcane.iris.modules.terrain.ExplodeBiomePalettesSettings; @@ -66,6 +67,7 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { ExplodeBiomePaletteSizeSettings.class); registry.registerService(ProtectedFloor.class, TerrainModule::protectsFloor); registry.registerLifecycle(this); + setup.tooling().registerView(new BiomePalettes()); } /** The bedrock row belongs to the terrain while the dimension has bedrock, as it does unless the pack says otherwise. */ diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index b471778b2..4751a7a98 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -72,8 +72,8 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { registry.registerResourceKind(ProceduralObjectCatalog.DEFINITIONS); registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); registry.registerLifecycle(this); - setup.tooling().registerSceneView(new PackObjectScenes()); - setup.tooling().registerSceneView(new ProceduralObjectScenes()); + setup.tooling().registerView(new PackObjectScenes()); + setup.tooling().registerView(new ProceduralObjectScenes()); } @Override diff --git a/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java b/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java index 949f103a5..73d49d60f 100644 --- a/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java +++ b/src/main/java/art/arcane/iris/modules/terrain/BiomeLayers.java @@ -193,6 +193,57 @@ public final class BiomeLayers { return blocks; } + /** The biome's surface layers, the one default layer when it declares none. */ + public List surfaceLayers(LayeredBiome biome) { + return surfaceSettings(biome).layers(); + } + + public List seaLayers(LayeredBiome biome) { + return biome.seaLayers() == null ? List.of() : biome.seaLayers().layers(); + } + + /** The biome's cave ceiling layers that place blocks: those with a surface layer at their place to borrow its thickness from. */ + public List ceilingLayers(LayeredBiome biome) { + List declared = biome.ceilingLayers() == null ? List.of() : biome.ceilingLayers().layers(); + return declared.subList(0, Math.min(declared.size(), surfaceLayers(biome).size())); + } + + /** + * Surface layer {@code index}'s block {@code depth} blocks below its top at the column, as {@link #generateLayers} picks + * it, leaving its slope condition aside; null where the layer is thinner there. + */ + public BlockState surfaceLayerBlock(LayeredBiome biome, int index, int depth, double wx, double wz, RNG random) { + LayersSettings settings = surfaceSettings(biome); + ResolvedLayer layer = resolve(settings.layers().get(index)); + double thickness = layerThickness(layer, surfaceHeightNoises(settings, random).get(index), wx, wz); + return blockAtDepth(layer, index, depth, thickness, wx, wz, random); + } + + /** Sea layer {@code index}'s block {@code depth} blocks below the water surface, as {@link #generateSeaLayers} picks it. */ + public BlockState seaLayerBlock(LayeredBiome biome, int index, int depth, double wx, double wz, RNG random) { + ResolvedLayer layer = resolve(seaLayers(biome).get(index)); + LayerNoise heightNoise = seaHeightNoises(biome.seaLayers(), random).get(index); + int thickness = heightNoise.fit(layer.minHeight(), layer.maxHeight(), wx / layer.zoom(), wz / layer.zoom()); + return blockAtDepth(layer, index, depth, thickness, wx, wz, random); + } + + /** Cave ceiling layer {@code index}'s block {@code depth} blocks below the ceiling, as {@link #generateCeilingLayers} picks it. */ + public BlockState ceilingLayerBlock(LayeredBiome biome, int index, int depth, double wx, double wz, RNG random) { + ResolvedLayer layer = resolve(ceilingLayers(biome).get(index)); + double thickness = layerThickness(layer, surfaceHeightNoises(surfaceSettings(biome), random).get(index), wx, wz); + return blockAtDepth(layer, index, depth, thickness, wx, wz, random); + } + + // The layer's blocks are stacked from its top, as generation stacks them, so the first pick seeds its noise as the world's did. + private BlockState blockAtDepth(ResolvedLayer layer, int index, int depth, double thickness, double wx, double wz, RNG random) { + if (depth >= thickness) { + return null; + } + KList stacked = new KList<>(); + stackLayer(stacked, layer, index, depth + 1, wx, wz, random, depth + 1); + return stacked.size() > depth ? stacked.get(depth) : null; + } + private KList generateLockedLayers(LayeredBiome biome, double wx, double wz, RNG random, int maxDepthLimit, int height, ColumnSlope slope) { KList stacked = new KList<>(); KList locked = new KList<>(); diff --git a/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java b/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java new file mode 100644 index 000000000..34addefb7 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java @@ -0,0 +1,279 @@ +/* + * 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.modules.terrain; + +import art.arcane.iris.builtin.IrisSeedPurposes; +import art.arcane.iris.builtin.terrain.PaletteLayer; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockSpec; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.BlockPattern; +import com.volmit.tooling.PatternArea; +import com.volmit.tooling.PatternEntry; +import com.volmit.tooling.PatternView; +import com.volmit.world.PackBiome; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +/** + * The studio's Palettes view (v3e's palette explorer): each biome's layers, sea layers, cave ceiling layers, wall and + * slab, from above, the blocks each places at a depth as the world places them. Picks go through the world's own + * {@link BiomeLayers} with the random each stage uses, so asking first seeds a layer's noise as generation would. + */ +public final class BiomePalettes implements PatternView { + private static final ResourceId ID = ResourceId.parse("iris:terrain/palettes"); + private static final char KIND_SEPARATOR = '#'; + private static final char INDEX_SEPARATOR = '/'; + private static final String MINECRAFT_PREFIX = "minecraft:"; + // Walls and slabs are picked one block at a time with noise that changes with height. + private static final int SINGLE_BLOCK_DEPTHS = 1; + private static final int SINGLE_BLOCK_SIGNATURE = 0; + + @Override + public ResourceId id() { + return ID; + } + + @Override + public String label() { + return "Palettes"; + } + + @Override + public String description() { + return "Each biome's layers, wall and slab from above, the blocks they place at each depth"; + } + + @Override + public List entries(PackWorld world) { + Optional running = world.running(); + if (running.isEmpty()) { + return List.of(); + } + BiomeLayers layers = BiomeLayers.of(world); + FeatureSettings settings = running.get().settings(); + List biomes = biomesByName(world.resources()); + Map biomesByShownName = biomes.stream().collect(Collectors.groupingBy(PackBiome::name, Collectors.counting())); + List entries = new ArrayList<>(); + for (PackBiome biome : biomes) { + String group = biomesByShownName.get(biome.name()) > 1 ? biome.name() + " (" + biome.id().path() + ")" : biome.name(); + LayeredBiome layered = layers.biome(biome.id(), settings); + for (Kind kind : Kind.values()) { + List palettes = kind.palettesOf(layers, layered, settings, biome.id()); + for (int index = 0; index < palettes.size(); index++) { + entries.add(entryOf(biome, layered, kind, index, palettes.get(index), group)); + } + } + } + return entries; + } + + @Override + public Optional pattern(PackWorld world, String key, int depth, PatternArea area) { + Optional running = world.running(); + Optional ref = PaletteRef.parse(key, world.resources()); + if (running.isEmpty() || ref.isEmpty()) { + return Optional.empty(); + } + BiomeLayers layers = BiomeLayers.of(world); + FeatureSettings settings = running.get().settings(); + PaletteRef palette = ref.get(); + LayeredBiome biome = layers.biome(palette.biome(), settings); + List palettes = palette.kind().palettesOf(layers, biome, settings, palette.biome()); + if (palette.index() >= palettes.size() || depth < 0) { + return Optional.empty(); + } + ColumnPick pick = palette.kind().picker(world, layers, biome, palettes.get(palette.index()), palette.index(), + running.get().layout().fluidHeight()); + BlockState[] blocks = new BlockState[area.columns() * area.columns()]; + for (int row = 0; row < area.columns(); row++) { + for (int column = 0; column < area.columns(); column++) { + blocks[row * area.columns() + column] = pick.at(area.blockX(column), area.blockZ(row), depth); + } + } + return Optional.of(BlockPattern.of(area.columns(), blocks)); + } + + private static List biomesByName(PackResources resources) { + return resources.ids(PackResources.BIOMES).stream() + .map(id -> resources.find(PackResources.BIOMES, id)) + .flatMap(Optional::stream) + .sorted(Comparator.comparing(PackBiome::name).thenComparing(biome -> biome.id().toString())) + .toList(); + } + + private static PatternEntry entryOf(PackBiome biome, LayeredBiome layered, Kind kind, int index, PaletteLayer palette, String group) { + String key = biome.id() + String.valueOf(KIND_SEPARATOR) + kind.keyName + INDEX_SEPARATOR + index; + String name = kind.numbered ? kind.label + " " + (index + 1) : kind.label; + return new PatternEntry(key, name, group, kind.depthsOf(palette), kind.factsOf(palette, layered)); + } + + private static String blocksOf(PaletteLayer palette) { + Map weights = palette.palette().stream() + .collect(Collectors.groupingBy(spec -> shortName(spec.block()), LinkedHashMap::new, Collectors.summingInt(BlockSpec::weight))); + return weights.entrySet().stream() + .map(entry -> entry.getValue() > 1 ? entry.getKey() + " ×" + entry.getValue() : entry.getKey()) + .collect(Collectors.joining(", ")); + } + + private static String shortName(String block) { + return block.startsWith(MINECRAFT_PREFIX) ? block.substring(MINECRAFT_PREFIX.length()) : block; + } + + private static String thicknessOf(PaletteLayer palette) { + if (palette.minHeight() == palette.maxHeight()) { + return palette.maxHeight() + (palette.maxHeight() == 1 ? " block thick" : " blocks thick"); + } + return palette.minHeight() + " to " + palette.maxHeight() + " blocks thick"; + } + + /** The block a palette places at a column, {@code depth} blocks below its top, or null for none. */ + @FunctionalInterface + private interface ColumnPick { + BlockState at(int x, int z, int depth); + } + + private enum Kind { + LAYER("layer", "Layer", true), + SEA_LAYER("sea-layer", "Sea layer", true), + CEILING_LAYER("ceiling-layer", "Cave ceiling layer", true), + WALL("wall", "Wall", false), + SLAB("slab", "Slab", false); + + private final String keyName; + private final String label; + private final boolean numbered; + + Kind(String keyName, String label, boolean numbered) { + this.keyName = keyName; + this.label = label; + this.numbered = numbered; + } + + static Optional byKeyName(String keyName) { + for (Kind kind : values()) { + if (kind.keyName.equals(keyName)) { + return Optional.of(kind); + } + } + return Optional.empty(); + } + + // A biome without a wall or slab block has those palettes, just empty, so they aren't listed. + List palettesOf(BiomeLayers layers, LayeredBiome biome, FeatureSettings settings, ResourceId id) { + return switch (this) { + case LAYER -> layers.surfaceLayers(biome); + case SEA_LAYER -> layers.seaLayers(biome); + case CEILING_LAYER -> layers.ceilingLayers(biome); + case WALL -> placing(biome.wall() == null ? null : biome.wall().layer()); + case SLAB -> placing(settings.declaredBy(id, SlabSettings.class).map(SlabSettings::layer).orElse(null)); + }; + } + + private static List placing(PaletteLayer layer) { + return layer == null || layer.palette().isEmpty() ? List.of() : List.of(layer); + } + + int depthsOf(PaletteLayer palette) { + return numbered ? Math.max(1, palette.maxHeight()) : SINGLE_BLOCK_DEPTHS; + } + + List factsOf(PaletteLayer palette, LayeredBiome biome) { + List facts = new ArrayList<>(); + facts.add(blocksOf(palette)); + facts.add(numbered ? thicknessOf(palette) : "Picked at the fluid height; changes with height"); + facts.add(palette.style().style().toLowerCase(Locale.ROOT).replace('_', ' ') + " noise, zoom " + palette.zoom()); + if (!palette.slopeCondition().isDefault()) { + facts.add("Only on slopes from " + palette.slopeCondition().minimumSlope() + " to " + palette.slopeCondition().maximumSlope() + + "; shown everywhere here"); + } + if (this == LAYER && biome.layers() == null) { + facts.add("The biome declares no layers, so it gets this default one"); + } + if (this == LAYER && biome.lock() != null && biome.lock().locked()) { + facts.add("The biome locks its layers, which repeats them by height"); + } + return facts; + } + + // Each stage picks with its own random: the terrain's for surface and sea layers, the caves' for ceilings and + // walls, post processing's for slabs. The studio asks with the same one, so it seeds noise as generation does. + ColumnPick picker(PackWorld world, BiomeLayers layers, LayeredBiome biome, PaletteLayer palette, int index, int fluidHeight) { + return switch (this) { + case LAYER -> { + RNG terrain = new RNG(world.seed(IrisSeedPurposes.TERRAIN)); + yield (x, z, depth) -> layers.surfaceLayerBlock(biome, index, depth, x, z, terrain); + } + case SEA_LAYER -> { + RNG terrain = new RNG(world.seed(IrisSeedPurposes.TERRAIN)); + yield (x, z, depth) -> layers.seaLayerBlock(biome, index, depth, x, z, terrain); + } + case CEILING_LAYER -> { + RNG carve = new RNG(world.seed(IrisSeedPurposes.CARVE)); + yield (x, z, depth) -> layers.ceilingLayerBlock(biome, index, depth, x, z, carve); + } + case WALL -> singleBlocks(layers.resolve(palette), new RNG(world.seed(IrisSeedPurposes.CARVE)), fluidHeight); + case SLAB -> singleBlocks(layers.resolve(palette), new RNG(world.seed(IrisSeedPurposes.POST)), fluidHeight); + }; + } + + private static ColumnPick singleBlocks(ResolvedLayer layer, RNG random, int height) { + return (x, z, depth) -> depth == 0 ? layer.get(random, SINGLE_BLOCK_SIGNATURE, x, height, z) : null; + } + } + + private record PaletteRef(ResourceId biome, Kind kind, int index) { + static Optional parse(String key, PackResources resources) { + int kindStart = key.lastIndexOf(KIND_SEPARATOR); + int indexStart = key.lastIndexOf(INDEX_SEPARATOR); + if (kindStart < 1 || indexStart < kindStart) { + return Optional.empty(); + } + Optional kind = Kind.byKeyName(key.substring(kindStart + 1, indexStart)); + Optional index = wholeNumber(key.substring(indexStart + 1)); + Optional biome = resources.ids(PackResources.BIOMES).stream() + .filter(id -> id.toString().equals(key.substring(0, kindStart))) + .findFirst(); + if (kind.isEmpty() || index.isEmpty() || biome.isEmpty()) { + return Optional.empty(); + } + return Optional.of(new PaletteRef(biome.get(), kind.get(), index.get())); + } + + private static Optional wholeNumber(String text) { + try { + return Optional.of(Integer.parseInt(text)).filter(number -> number >= 0); + } catch (NumberFormatException notANumber) { + return Optional.empty(); + } + } + } +} From 2896aeb400d851b9a2e07c6123c4f28eebd88c9a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 05:06:23 +0100 Subject: [PATCH 124/139] Show procedural objects as nodes in the studio editor ProceduralObjectGraph reads a procedural file as a tree: the object, its parts (stem, blob, branches, cluster, group, shared), materials and decorations, each with its settings types and the parts that can be added under it. ProceduralObjectScenes implements EditableSceneView. --- .../objects/ProceduralObjectGraph.java | 241 ++++++++++++++++++ .../objects/ProceduralObjectScenes.java | 26 +- 2 files changed, 264 insertions(+), 3 deletions(-) create mode 100644 src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java new file mode 100644 index 000000000..ac147bb75 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java @@ -0,0 +1,241 @@ +/* + * 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.modules.objects; + +import art.arcane.iris.engine.procedural.part.PartBlob; +import art.arcane.iris.engine.procedural.part.PartBranches; +import art.arcane.iris.engine.procedural.part.PartCluster; +import art.arcane.iris.engine.procedural.part.PartOutline; +import art.arcane.iris.engine.procedural.part.PartStem; +import art.arcane.iris.engine.procedural.part.ProceduralDecoration; +import art.arcane.iris.engine.procedural.part.ProceduralMaterial; +import art.arcane.iris.engine.procedural.part.ProceduralObject; +import art.arcane.iris.engine.procedural.part.ProceduralPart; +import com.volmit.tooling.GraphNode; +import com.volmit.tooling.GraphNode.Addition; +import com.volmit.tooling.GraphNode.Link; +import com.volmit.tooling.GraphNode.NodeSettings; +import com.volmit.tooling.JsonPath; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; + +/** + * A procedural object's file as nodes: the object, the parts growing from it, its materials and its decorations (v3e's + * node editor). Each part node is the part of the baked object it draws, so the studio can pick one from the other. + */ +final class ProceduralObjectGraph { + private static final String PARTS = "parts"; + private static final String CHILDREN = "children"; + private static final String COPIED_PART = "part"; + private static final String MATERIALS = "materials"; + private static final String DECORATIONS = "decorations"; + private static final String ROLE = "role"; + private static final String DECORATED_ROLES = "on"; + private static final String DEFAULT_MATERIAL_ROLE = "main"; + private static final String EACH_COPY = "each copy"; + private static final String GROWS = ""; + private static final Set OBJECT_NODES = Set.of(MATERIALS, PARTS, DECORATIONS); + private static final Set PART_NODES = Set.of(Shape.STEM.key, Shape.BLOB.key, Shape.BRANCHES.key, Shape.CLUSTER.key, CHILDREN); + private static final Set COPY_NODES = Set.of(COPIED_PART); + private static final Set NO_NODES = Set.of(); + + private final JsonText source; + private final PartOutline outline; + + private ProceduralObjectGraph(JsonText source, PartOutline outline) { + this.source = source; + this.outline = outline; + } + + /** + * @param read what the pack read from the file, so its parts line up with the file's; it may be older than + * {@code source}, and parts past what it read get no part id + * @throws IllegalArgumentException when the file does not hold an object + */ + static NodeGraph of(String name, JsonText source, ProceduralObject read) { + if (!(source.root() instanceof JsonText.Obj root)) { + throw new IllegalArgumentException("The file does not hold an object"); + } + return new ProceduralObjectGraph(source, PartOutline.of(read)).graph(name, root, read); + } + + private NodeGraph graph(String name, JsonText.Obj root, ProceduralObject read) { + JsonPath parts = JsonPath.of(PARTS); + GraphNode object = new GraphNode("Object", name, JsonPath.ROOT, GraphNode.NO_PART, List.of(), + List.of(new NodeSettings("Object", JsonPath.ROOT, ProceduralObject.class, OBJECT_NODES)), + parts(parts, root.get(PARTS), read.parts(), read.defaultRole()), Optional.of(parts), false, objectAdditions(parts)); + List roots = new ArrayList<>(); + roots.add(object); + roots.addAll(listed(MATERIALS, root.get(MATERIALS), NodeKind.MATERIAL, ProceduralMaterial.class)); + roots.addAll(listed(DECORATIONS, root.get(DECORATIONS), NodeKind.DECORATION, ProceduralDecoration.class)); + return new NodeGraph(roots); + } + + // The pack read the file's arrays element for element, so the definition's lists line up with them. + private List parts(JsonPath arrayPath, Optional array, List read, String parentRole) { + if (!(array.orElse(null) instanceof JsonText.Arr elements)) { + return List.of(); + } + List links = new ArrayList<>(); + for (int index = 0; index < elements.elements().size(); index++) { + ProceduralPart part = index < read.size() ? read.get(index) : null; + links.add(new Link(GROWS, part(arrayPath.element(index), elements.elements().get(index), part, parentRole, true))); + } + return links; + } + + private GraphNode part(JsonPath path, JsonText.Value json, ProceduralPart read, String parentRole, boolean movable) { + int partId = read == null ? GraphNode.NO_PART : outline.idOf(read); + if (!(json instanceof JsonText.Obj object)) { + return sharedPart(path, json, partId, parentRole, movable); + } + String role = stringAt(object, ROLE).filter(written -> !written.isBlank()).orElse(parentRole); + List settings = new ArrayList<>(); + settings.add(new NodeSettings("Part", path, ProceduralPart.class, PART_NODES)); + List children = new ArrayList<>(); + NodeKind kind = NodeKind.GROUP; + for (Shape shape : Shape.values()) { + if (!(object.get(shape.key).orElse(null) instanceof JsonText.Obj shapeObject)) { + continue; + } + kind = kind == NodeKind.GROUP || shape.copiesAPart() ? shape.kind : kind; + JsonPath shapePath = path.member(shape.key); + settings.add(new NodeSettings(shape.kind.label, shapePath, shape.settings, shape.copiesAPart() ? COPY_NODES : NO_NODES)); + Optional copied = shapeObject.get(COPIED_PART); + if (shape.copiesAPart() && copied.isPresent()) { + children.add(new Link(EACH_COPY, part(shapePath.member(COPIED_PART), copied.get(), copiedPartOf(read, shape), role, false))); + } + } + JsonPath childList = path.member(CHILDREN); + children.addAll(parts(childList, object.get(CHILDREN), read == null ? List.of() : read.children(), role)); + return new GraphNode(kind.label, kind.label, path, partId, List.of(role), settings, children, Optional.of(childList), movable, + partAdditions(childList)); + } + + // A part written as the name of a snippet file, which is edited there. + private GraphNode sharedPart(JsonPath path, JsonText.Value json, int partId, String parentRole, boolean movable) { + String title = json instanceof JsonText.Literal literal && literal.string().isPresent() ? literal.string().get() : source.textOf(json); + return new GraphNode(NodeKind.SHARED_PART.label, title, path, partId, List.of(parentRole), List.of(), List.of(), Optional.empty(), + movable, List.of()); + } + + private static ProceduralPart copiedPartOf(ProceduralPart part, Shape shape) { + if (part == null) { + return null; + } + if (shape == Shape.BRANCHES) { + return part.branches() == null ? null : part.branches().part(); + } + return part.cluster() == null ? null : part.cluster().part(); + } + + private static List listed(String key, Optional array, NodeKind kind, Class settings) { + if (!(array.orElse(null) instanceof JsonText.Arr elements)) { + return List.of(); + } + List nodes = new ArrayList<>(); + for (int index = 0; index < elements.elements().size(); index++) { + if (!(elements.elements().get(index) instanceof JsonText.Obj element)) { + continue; + } + JsonPath path = JsonPath.of(key, index); + nodes.add(new GraphNode(kind.label, kind.label, path, GraphNode.NO_PART, rolesOf(kind, element), + List.of(new NodeSettings(kind.label, path, settings, NO_NODES)), List.of(), Optional.empty(), false, List.of())); + } + return nodes; + } + + private static List rolesOf(NodeKind kind, JsonText.Obj element) { + if (kind == NodeKind.MATERIAL) { + return List.of(stringAt(element, ROLE).orElse(DEFAULT_MATERIAL_ROLE)); + } + if (!(element.get(DECORATED_ROLES).orElse(null) instanceof JsonText.Arr roles)) { + return List.of(); + } + return roles.elements().stream() + .flatMap(role -> role instanceof JsonText.Literal literal ? literal.string().stream() : Stream.empty()) + .toList(); + } + + private static Optional stringAt(JsonText.Obj object, String key) { + return object.get(key).flatMap(value -> value instanceof JsonText.Literal literal ? literal.string() : Optional.empty()); + } + + /** What a new part starts as, so it bakes into something visible at once. */ + private static List partAdditions(JsonPath list) { + return List.of( + new Addition("Stem", list, "{\"stem\": {\"length\": 6}}"), + new Addition("Blob", list, "{\"blob\": {\"radius\": 2}}"), + new Addition("Branches", list, "{\"branches\": {\"count\": 4, \"part\": {\"stem\": {\"length\": 4}}}}"), + new Addition("Cluster", list, "{\"cluster\": {\"count\": 5, \"part\": {\"stem\": {\"length\": 3}}}}"), + new Addition("Group", list, "{}")); + } + + private static List objectAdditions(JsonPath parts) { + List additions = new ArrayList<>(partAdditions(parts)); + additions.add(new Addition("Material", JsonPath.of(MATERIALS), "{\"role\": \"main\", \"block\": \"minecraft:stone\"}")); + additions.add(new Addition("Decoration", JsonPath.of(DECORATIONS), "{\"block\": \"minecraft:vine\"}")); + return additions; + } + + private enum NodeKind { + STEM("Stem"), + BLOB("Blob"), + BRANCHES("Branches"), + CLUSTER("Cluster"), + GROUP("Group"), + SHARED_PART("Shared part"), + MATERIAL("Material"), + DECORATION("Decoration"); + + private final String label; + + NodeKind(String label) { + this.label = label; + } + } + + /** The shapes a part can take, each written as a member of the part holding its settings. */ + private enum Shape { + STEM("stem", NodeKind.STEM, PartStem.class), + BLOB("blob", NodeKind.BLOB, PartBlob.class), + BRANCHES("branches", NodeKind.BRANCHES, PartBranches.class), + CLUSTER("cluster", NodeKind.CLUSTER, PartCluster.class); + + private final String key; + private final NodeKind kind; + private final Class settings; + + Shape(String key, NodeKind kind, Class settings) { + this.key = key; + this.kind = kind; + this.settings = settings; + } + + boolean copiesAPart() { + return this == BRANCHES || this == CLUSTER; + } + } +} diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java index 22db5126f..95e375839 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -20,11 +20,15 @@ package art.arcane.iris.modules.objects; import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; import art.arcane.iris.engine.procedural.ProceduralVariants; +import art.arcane.iris.engine.procedural.part.ProceduralObject; import com.volmit.object.GeneratedObject; import com.volmit.object.PlaceableObject; import com.volmit.resource.ResourceId; +import com.volmit.tooling.EditableSceneView; +import com.volmit.tooling.JsonText; +import com.volmit.tooling.NodeGraph; import com.volmit.tooling.SceneEntry; -import com.volmit.tooling.SceneView; +import com.volmit.tooling.SceneFile; import com.volmit.world.PackWorld; import java.util.List; @@ -32,9 +36,9 @@ import java.util.Optional; /** * The studio's Procedural view: every procedural object of the pack with each of its variants, baked as the world - * bakes them, so what the studio shows is what generation places. + * bakes them, so what the studio shows is what generation places. Each object's file can be edited as nodes. */ -public final class ProceduralObjectScenes implements SceneView { +public final class ProceduralObjectScenes implements EditableSceneView { private static final ResourceId ID = ResourceId.parse("iris:objects/procedural"); private static final char FOLDER_SEPARATOR = '/'; @@ -69,6 +73,22 @@ public final class ProceduralObjectScenes implements SceneView { .map(PlaceableObject::geometry); } + @Override + public Optional fileOf(PackWorld world, String key) { + ResourceId id = world.resources().idOf(key); + return world.resources().ids(ProceduralObjectCatalog.DEFINITIONS).contains(id) + ? Optional.of(new SceneFile(ProceduralObjectCatalog.DEFINITIONS, id)) + : Optional.empty(); + } + + // A file the pack could not read has no parts baked from it, so its nodes are drawn without part ids. + @Override + public NodeGraph graph(PackWorld world, String key, JsonText text) { + ProceduralObject read = world.resources().find(ProceduralObjectCatalog.DEFINITIONS, world.resources().idOf(key)) + .orElseGet(ProceduralObject::new); + return ProceduralObjectGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read); + } + private static SceneEntry entryOf(ProceduralVariants variants) { String path = variants.path(); int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); From 5d0c378f885f0b5d05ca15a1aa9cb599d0880d87 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 05:55:48 +0100 Subject: [PATCH 125/139] Build entity specs without the removed extensions --- .../java/art/arcane/iris/engine/spawn/EntityResolution.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java index 078842843..f8be355bf 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntityResolution.java @@ -87,7 +87,7 @@ final class EntityResolution { return typeOf(entity).map(type -> new EntitySpec(type, appearanceOf(entity), behaviourOf(entity), equipment, attributes, new EntitySpec.Company(passengers, leashHolder), new EntitySpec.Drops(lootTables, lootShuffleSeed), - arrivalOf(entity), entity.applySettingsToCustomMobAnyways(), List.of())); + arrivalOf(entity), entity.applySettingsToCustomMobAnyways())); } /** The provider's mob when the pack names one, otherwise the entity type. */ From 59f24a03afdf14f285e6119c86cbb335decc7715 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 06:09:14 +0100 Subject: [PATCH 126/139] Follow the API's typed tooling values Graph nodes take an optional part and their edits as one record, paths are built from typed steps, and entries without a folder leave their group empty. --- .../modules/objects/PackObjectScenes.java | 2 +- .../objects/ProceduralObjectGraph.java | 41 ++++++++++++------- .../objects/ProceduralObjectScenes.java | 2 +- .../iris/modules/terrain/BiomePalettes.java | 3 +- 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java b/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java index a6a2c18b2..75a26153e 100644 --- a/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java +++ b/src/main/java/art/arcane/iris/modules/objects/PackObjectScenes.java @@ -67,7 +67,7 @@ public final class PackObjectScenes implements SceneView { private static SceneEntry entryOf(String key) { int lastSeparator = key.lastIndexOf(FOLDER_SEPARATOR); - String folder = lastSeparator < 0 ? "" : key.substring(0, lastSeparator); + Optional folder = lastSeparator < 0 ? Optional.empty() : Optional.of(key.substring(0, lastSeparator)); return new SceneEntry(key, key.substring(lastSeparator + 1), folder, 1); } } diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java index ac147bb75..a19dbad91 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectGraph.java @@ -29,6 +29,7 @@ import art.arcane.iris.engine.procedural.part.ProceduralObject; import art.arcane.iris.engine.procedural.part.ProceduralPart; import com.volmit.tooling.GraphNode; import com.volmit.tooling.GraphNode.Addition; +import com.volmit.tooling.GraphNode.Edits; import com.volmit.tooling.GraphNode.Link; import com.volmit.tooling.GraphNode.NodeSettings; import com.volmit.tooling.JsonPath; @@ -38,6 +39,7 @@ import com.volmit.tooling.NodeGraph; import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.OptionalInt; import java.util.Set; import java.util.stream.Stream; @@ -82,10 +84,11 @@ final class ProceduralObjectGraph { } private NodeGraph graph(String name, JsonText.Obj root, ProceduralObject read) { - JsonPath parts = JsonPath.of(PARTS); - GraphNode object = new GraphNode("Object", name, JsonPath.ROOT, GraphNode.NO_PART, List.of(), + JsonPath parts = JsonPath.ROOT.member(PARTS); + GraphNode object = new GraphNode("Object", name, JsonPath.ROOT, OptionalInt.empty(), List.of(), List.of(new NodeSettings("Object", JsonPath.ROOT, ProceduralObject.class, OBJECT_NODES)), - parts(parts, root.get(PARTS), read.parts(), read.defaultRole()), Optional.of(parts), false, objectAdditions(parts)); + parts(parts, root.get(PARTS), read.parts(), read.defaultRole()), + new Edits(Optional.of(parts), false, objectAdditions(parts))); List roots = new ArrayList<>(); roots.add(object); roots.addAll(listed(MATERIALS, root.get(MATERIALS), NodeKind.MATERIAL, ProceduralMaterial.class)); @@ -107,9 +110,9 @@ final class ProceduralObjectGraph { } private GraphNode part(JsonPath path, JsonText.Value json, ProceduralPart read, String parentRole, boolean movable) { - int partId = read == null ? GraphNode.NO_PART : outline.idOf(read); + OptionalInt drawnPart = drawnPartOf(read); if (!(json instanceof JsonText.Obj object)) { - return sharedPart(path, json, partId, parentRole, movable); + return sharedPart(path, json, drawnPart, parentRole, movable); } String role = stringAt(object, ROLE).filter(written -> !written.isBlank()).orElse(parentRole); List settings = new ArrayList<>(); @@ -130,15 +133,23 @@ final class ProceduralObjectGraph { } JsonPath childList = path.member(CHILDREN); children.addAll(parts(childList, object.get(CHILDREN), read == null ? List.of() : read.children(), role)); - return new GraphNode(kind.label, kind.label, path, partId, List.of(role), settings, children, Optional.of(childList), movable, - partAdditions(childList)); + return new GraphNode(kind.label, kind.label, path, drawnPart, List.of(role), settings, children, + new Edits(Optional.of(childList), movable, partAdditions(childList))); } // A part written as the name of a snippet file, which is edited there. - private GraphNode sharedPart(JsonPath path, JsonText.Value json, int partId, String parentRole, boolean movable) { + private GraphNode sharedPart(JsonPath path, JsonText.Value json, OptionalInt drawnPart, String parentRole, boolean movable) { String title = json instanceof JsonText.Literal literal && literal.string().isPresent() ? literal.string().get() : source.textOf(json); - return new GraphNode(NodeKind.SHARED_PART.label, title, path, partId, List.of(parentRole), List.of(), List.of(), Optional.empty(), - movable, List.of()); + return new GraphNode(NodeKind.SHARED_PART.label, title, path, drawnPart, List.of(parentRole), List.of(), List.of(), + new Edits(Optional.empty(), movable, List.of())); + } + + private OptionalInt drawnPartOf(ProceduralPart read) { + if (read == null) { + return OptionalInt.empty(); + } + int id = outline.idOf(read); + return id == PartOutline.NO_PART ? OptionalInt.empty() : OptionalInt.of(id); } private static ProceduralPart copiedPartOf(ProceduralPart part, Shape shape) { @@ -160,9 +171,9 @@ final class ProceduralObjectGraph { if (!(elements.elements().get(index) instanceof JsonText.Obj element)) { continue; } - JsonPath path = JsonPath.of(key, index); - nodes.add(new GraphNode(kind.label, kind.label, path, GraphNode.NO_PART, rolesOf(kind, element), - List.of(new NodeSettings(kind.label, path, settings, NO_NODES)), List.of(), Optional.empty(), false, List.of())); + JsonPath path = JsonPath.ROOT.member(key).element(index); + nodes.add(new GraphNode(kind.label, kind.label, path, OptionalInt.empty(), rolesOf(kind, element), + List.of(new NodeSettings(kind.label, path, settings, NO_NODES)), List.of(), Edits.NONE)); } return nodes; } @@ -195,8 +206,8 @@ final class ProceduralObjectGraph { private static List objectAdditions(JsonPath parts) { List additions = new ArrayList<>(partAdditions(parts)); - additions.add(new Addition("Material", JsonPath.of(MATERIALS), "{\"role\": \"main\", \"block\": \"minecraft:stone\"}")); - additions.add(new Addition("Decoration", JsonPath.of(DECORATIONS), "{\"block\": \"minecraft:vine\"}")); + additions.add(new Addition("Material", JsonPath.ROOT.member(MATERIALS), "{\"role\": \"main\", \"block\": \"minecraft:stone\"}")); + additions.add(new Addition("Decoration", JsonPath.ROOT.member(DECORATIONS), "{\"block\": \"minecraft:vine\"}")); return additions; } diff --git a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java index 95e375839..ea1c2dd29 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java +++ b/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -92,7 +92,7 @@ public final class ProceduralObjectScenes implements EditableSceneView { private static SceneEntry entryOf(ProceduralVariants variants) { String path = variants.path(); int lastSeparator = path.lastIndexOf(FOLDER_SEPARATOR); - String folder = lastSeparator < 0 ? "" : path.substring(0, lastSeparator); + Optional folder = lastSeparator < 0 ? Optional.empty() : Optional.of(path.substring(0, lastSeparator)); return new SceneEntry(path, path.substring(lastSeparator + 1), folder, variants.variantCount()); } } diff --git a/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java b/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java index 34addefb7..b3acc26a7 100644 --- a/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java +++ b/src/main/java/art/arcane/iris/modules/terrain/BiomePalettes.java @@ -133,7 +133,8 @@ public final class BiomePalettes implements PatternView { private static PatternEntry entryOf(PackBiome biome, LayeredBiome layered, Kind kind, int index, PaletteLayer palette, String group) { String key = biome.id() + String.valueOf(KIND_SEPARATOR) + kind.keyName + INDEX_SEPARATOR + index; String name = kind.numbered ? kind.label + " " + (index + 1) : kind.label; - return new PatternEntry(key, name, group, kind.depthsOf(palette), kind.factsOf(palette, layered)); + return new PatternEntry(key, name, Optional.of(group).filter(shown -> !shown.isBlank()), kind.depthsOf(palette), + kind.factsOf(palette, layered)); } private static String blocksOf(PaletteLayer palette) { From 956c33e8dbbb3b070c0c50b4e142e8267ee9c1f6 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 06:18:37 +0100 Subject: [PATCH 127/139] Follow the API's renamed highest, get and withPropertyIfAccepted --- src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java | 2 +- .../arcane/iris/engine/mantle/components/TreeGrowing.java | 2 +- .../art/arcane/iris/engine/procedural/part/Decorator.java | 6 +++--- .../art/arcane/iris/engine/procedural/part/LeafDecay.java | 4 ++-- .../arcane/iris/engine/procedural/part/MaterialPainter.java | 2 +- .../art/arcane/iris/engine/procedural/part/ObjectBaker.java | 2 +- .../java/art/arcane/iris/engine/spawn/EntitySpawning.java | 4 ++-- .../java/art/arcane/iris/modules/objects/ObjectBuilder.java | 6 +++--- 8 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java b/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java index 56b044289..40d1748f8 100644 --- a/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java +++ b/src/main/java/art/arcane/iris/engine/loot/BlockBiomes.java @@ -39,7 +39,7 @@ public final class BlockBiomes { public static ResourceId biomeAt(RunningWorld running, int x, int y, int z) { TerrainSampler layout = running.layout(); ResourceId surface = layout.surfaceBiome(x, z); - if (!layout.bounds().contains(x, y, z) || y > running.highestBlock(x, z, true) - CAVE_DEPTH_BELOW_HIGHEST_BLOCK) { + if (!layout.bounds().contains(x, y, z) || y > running.highest(x, z, true) - CAVE_DEPTH_BELOW_HIGHEST_BLOCK) { return surface; } return layout.caveBiome(x, y, z).orElse(surface); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java index 1be4a3ac0..766fbd70f 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/TreeGrowing.java @@ -207,7 +207,7 @@ public final class TreeGrowing implements SaplingGrowth { @Override public BlockState get(int x, int y, int z) { - return surroundings.blockAt(x, y, z); + return surroundings.get(x, y, z); } @Override diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java b/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java index fc2b5210d..a9c56cb5e 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/Decorator.java @@ -232,13 +232,13 @@ final class Decorator { private BlockState attached(BlockState state, BlockFace support) { String side = support.name().toLowerCase(); if ("false".equals(IrisProceduralBlocks.propertyValue(state, side))) { - return blocks.withProperty(state, side, "true"); + return blocks.withPropertyIfAccepted(state, side, "true"); } if (support == BlockFace.UP && IrisProceduralBlocks.hasProperty(state, "hanging")) { - return blocks.withProperty(state, "hanging", "true"); + return blocks.withPropertyIfAccepted(state, "hanging", "true"); } if (IrisProceduralBlocks.hasProperty(state, "facing")) { - return blocks.withProperty(state, "facing", opposite(support).name().toLowerCase()); + return blocks.withPropertyIfAccepted(state, "facing",opposite(support).name().toLowerCase()); } return state; } diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java b/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java index 1357f3602..dcfda1fff 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/LeafDecay.java @@ -122,8 +122,8 @@ final class LeafDecay { private void setLeafState(long leaf, boolean persistent, int distance) { BlockState state = blocks.get(leaf); - state = builder.withProperty(state, "persistent", String.valueOf(persistent)); - blocks.put(leaf, builder.withProperty(state, "distance", String.valueOf(distance))); + state = builder.withPropertyIfAccepted(state, "persistent", String.valueOf(persistent)); + blocks.put(leaf, builder.withPropertyIfAccepted(state, "distance", String.valueOf(distance))); } private static boolean isLeaf(BlockState state) { diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java b/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java index 994c0f759..b3be334d5 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/MaterialPainter.java @@ -130,6 +130,6 @@ final class MaterialPainter { if (axis == PartCanvas.Axis.NONE || !IrisProceduralBlocks.hasProperty(state, "axis")) { return state; } - return blocks.withProperty(state, "axis", axis.name().toLowerCase()); + return blocks.withPropertyIfAccepted(state, "axis",axis.name().toLowerCase()); } } diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java b/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java index c417bd9d0..b036ccefb 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ObjectBaker.java @@ -91,7 +91,7 @@ final class ObjectBaker { private static void waterlog(Map painted, ObjectBuilder blocks) { painted.replaceAll((key, state) -> "false".equals(IrisProceduralBlocks.propertyValue(state, "waterlogged")) - ? blocks.withProperty(state, "waterlogged", "true") : state); + ? blocks.withPropertyIfAccepted(state, "waterlogged", "true") : state); } /** How far the object sinks: a fraction of its height. Heights below it end up underground. */ diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index e9efe4bb0..6048e541c 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -172,8 +172,8 @@ public final class EntitySpawning implements EntitySpawns { /** Where a spawner of its group puts an entity at the column; null when it has no place for one. */ private static BlockPosition spawnPosition(RunningWorld running, Spawner spawner, int chunkX, int chunkZ, int x, int z) { - int height = running.highestBlock(x, z, true); - int heightWithFluid = running.highestBlock(x, z, false); + int height = running.highest(x, z, true); + int heightWithFluid = running.highest(x, z, false); return switch (spawner.group()) { case NORMAL -> new BlockPosition(x, heightWithFluid + 1, z); case CAVE -> caveSpawnPosition(running, chunkX, chunkZ); diff --git a/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java b/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java index dc0cb9cc7..f110747f8 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectBuilder.java @@ -57,9 +57,9 @@ public final class ObjectBuilder { return blocks.hasTrait(state, trait); } - /** {@code state} with the property set, as the platform sets it. */ - public BlockState withProperty(BlockState state, String name, String value) { - return blocks.withProperty(state, name, value); + /** {@code state} with the property set, as the platform sets it; {@code state} itself when the block does not accept it. */ + public BlockState withPropertyIfAccepted(BlockState state, String name, String value) { + return blocks.withPropertyIfAccepted(state, name, value); } /** The object of {@code blocks}, put in their order, {@code width} by {@code height} by {@code depth}, placeable like the pack's objects. */ From f466979679c94cd7357e42b5d70abb9f6117d261 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 06:30:49 +0100 Subject: [PATCH 128/139] Register settings one type per call; drop core stages from IrisStages iris:biome and iris:custom are core modules, so their stage constants now live in BiomeModule and CustomModule instead of the built-ins jar. --- .../art/arcane/iris/builtin/IrisStages.java | 18 ------------------ .../iris/engine/actuator/DecorantModule.java | 3 ++- .../iris/engine/actuator/TerrainModule.java | 6 ++++-- .../arcane/iris/engine/loot/LootModule.java | 3 ++- .../engine/mantle/components/ObjectModule.java | 7 +++++-- .../mantle/components/StructureModule.java | 3 ++- .../iris/engine/modifier/CarveModule.java | 6 ++++-- .../iris/engine/modifier/DepositModule.java | 4 +++- .../iris/engine/modifier/FloatingModule.java | 3 ++- .../iris/engine/modifier/PostModule.java | 4 +++- .../arcane/iris/engine/spawn/SpawnModule.java | 3 ++- 11 files changed, 29 insertions(+), 31 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/IrisStages.java b/src/main/java/art/arcane/iris/builtin/IrisStages.java index 725fbb028..2eec153ca 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisStages.java +++ b/src/main/java/art/arcane/iris/builtin/IrisStages.java @@ -73,15 +73,6 @@ public final class IrisStages { } } - /** Module {@code iris:biome}: the biomes a chunk reports to the server. */ - public static final class Biome { - /** Writes every column's biome, sky biome or custom biome, into the chunk. */ - public static final ChunkStage WRITE = Stage.chunk("iris:biome/write"); - - private Biome() { - } - } - /** Module {@code iris:terrain}: the solid ground, fluids and biome layers of a chunk. */ public static final class Terrain { /** Fills each column from bedrock up to its height and the fluid height, with its biome's layers. */ @@ -138,13 +129,4 @@ public final class IrisStages { private Perfection() { } } - - /** Module {@code iris:custom}: blocks of content plugins, which the server places after generation. */ - public static final class Custom { - /** Records the chunk's custom blocks so the server can place them once the chunk exists. */ - public static final ChunkStage BLOCKS = Stage.chunk("iris:custom/blocks"); - - private Custom() { - } - } } diff --git a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java index 73bc33b72..bbf21ced0 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/DecorantModule.java @@ -58,7 +58,8 @@ public final class DecorantModule implements IrisModule, ModuleLifecycle { // Ordering only: iris:matter ships in the built-ins jar, which a pack may not have. setup.stages().define(IrisStages.Decorant.DECORATE).softAfter(IrisStages.Matter.INSERT).run(DecorantModule::decorate); var registry = setup.registry(); - registry.registerSettings(DecorantSettings.class, DecorateSettings.class); + registry.registerSettings(DecorantSettings.class); + registry.registerSettings(DecorateSettings.class); registry.registerLifecycle(this); } diff --git a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java index f5b58baea..41ac61347 100644 --- a/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java +++ b/src/main/java/art/arcane/iris/engine/actuator/TerrainModule.java @@ -43,6 +43,8 @@ import com.volmit.world.PackWorld; import art.arcane.iris.modules.terrain.TerrainPalettes; +import java.util.List; + /** * Module {@code iris:terrain}: the chunk's ground, fluids and biome layers. Each column is filled from bedrock up * to its height and the fluid height with its biome's layers, with ore generators of the dimension, region and @@ -61,10 +63,10 @@ public final class TerrainModule implements IrisModule, ModuleLifecycle { public void setup(ModuleSetup setup) { setup.stages().define(IrisStages.Terrain.SHAPE).run(TerrainModule::shape); var registry = setup.registry(); - registry.registerSettings(LayersSettings.class, SeaLayersSettings.class, CaveCeilingLayersSettings.class, SlabSettings.class, + List.of(LayersSettings.class, SeaLayersSettings.class, CaveCeilingLayersSettings.class, SlabSettings.class, WallSettings.class, LockLayersSettings.class, LockLayersMaxSettings.class, RockPaletteSettings.class, FluidPaletteSettings.class, OreSettings.class, HideOresSettings.class, BedrockSettings.class, ExplodeBiomePalettesSettings.class, - ExplodeBiomePaletteSizeSettings.class); + ExplodeBiomePaletteSizeSettings.class).forEach(registry::registerSettings); registry.registerService(ProtectedFloor.class, TerrainModule::protectsFloor); registry.registerLifecycle(this); setup.tooling().registerView(new BiomePalettes()); diff --git a/src/main/java/art/arcane/iris/engine/loot/LootModule.java b/src/main/java/art/arcane/iris/engine/loot/LootModule.java index 4e4b10285..4ede6484f 100644 --- a/src/main/java/art/arcane/iris/engine/loot/LootModule.java +++ b/src/main/java/art/arcane/iris/engine/loot/LootModule.java @@ -43,7 +43,8 @@ public final class LootModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(LootSettings.class, BlockDropSettings.class); + registry.registerSettings(LootSettings.class); + registry.registerSettings(BlockDropSettings.class); LootResources.kinds().forEach(registry::registerResourceKind); registry.registerValidator(new LootValidator()); registry.registerService(Loot.class, new LootGiving()); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java index 4751a7a98..7617a8129 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectModule.java @@ -40,6 +40,8 @@ import com.volmit.service.SaplingGrowth; import com.volmit.stage.MantleStageContext; import com.volmit.world.PackWorld; +import java.util.List; + /** * Module {@code iris:objects}: the objects the dimension's regions and biomes place, written into the mantle * once the caves they may anchor in are planned. A port of what was Iris's object mantle component, its work @@ -67,8 +69,9 @@ public final class ObjectModule implements IrisModule, ModuleLifecycle { var registry = setup.registry(); registry.registerService(ObjectsAt.class, new ObjectLocating()); registry.registerService(SaplingGrowth.class, new TreeGrowing()); - registry.registerSettings(ObjectSettings.class, TreeGrowthSettings.class, RequireSurfaceSupportSettings.class, - SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, UpperObjectsForceSettings.class); + List.of(ObjectSettings.class, TreeGrowthSettings.class, RequireSurfaceSupportSettings.class, + SurfaceSupportBufferSettings.class, UpperObjectsSettings.class, UpperObjectsForceSettings.class) + .forEach(registry::registerSettings); registry.registerResourceKind(ProceduralObjectCatalog.DEFINITIONS); registry.registerPlacementType(ObjectPlacement.class, ObjectPlacement.jsonFields()); registry.registerLifecycle(this); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 55c1fcc37..17d8d5eae 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -52,7 +52,8 @@ public final class StructureModule implements IrisModule { .reach(StructureModule::reach).run(StructureModule::place); var registry = setup.registry(); StructureResources.kinds().forEach(registry::registerResourceKind); - registry.registerSettings(StructureSettings.class, StructurePlacementSettings.class); + registry.registerSettings(StructureSettings.class); + registry.registerSettings(StructurePlacementSettings.class); } private static void place(MantleStageContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index a8033e0a7..71f50bec1 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -46,6 +46,7 @@ import com.volmit.stage.MantleStageContext; import com.volmit.world.PackWorld; import com.volmit.world.TerrainSampler; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -68,8 +69,9 @@ public final class CarveModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(CaveProfile.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class, - CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class); + List.of(CaveProfile.class, CarvingSettings.class, CarvingEnabledSettings.class, CarvingBiomeSettings.class, + CaveDepthSettings.class, CaveLavaHeightSettings.class, UpperDimensionCarvingSettings.class) + .forEach(registry::registerSettings); registry.registerService(CaveBiomes.class, new CaveBiomeBands()); var graph = setup.stages(); diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java index 5805b67de..c0634082b 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositModule.java @@ -50,7 +50,9 @@ public final class DepositModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(DepositVariantSettings.class, OreFrequencySettings.class, OreSizeSettings.class); + registry.registerSettings(DepositVariantSettings.class); + registry.registerSettings(OreFrequencySettings.class); + registry.registerSettings(OreSizeSettings.class); setup.stages().define(IrisStages.Deposit.ORES) .when(DepositSettings.class) diff --git a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java index 8e3ef5fa9..2e4eea9cf 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/FloatingModule.java @@ -50,7 +50,8 @@ public final class FloatingModule implements IrisModule { public void setup(ModuleSetup setup) { log = setup.log(); var registry = setup.registry(); - registry.registerSettings(FloatingChildSettings.class, MergeFloatingChildrenSettings.class); + registry.registerSettings(FloatingChildSettings.class); + registry.registerSettings(MergeFloatingChildrenSettings.class); var graph = setup.stages(); graph.define(IrisStages.Floating.OBJECTS).softAfter(IrisStages.Objects.PLACE).reach(this::objectReach) diff --git a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java index 936b968f6..18b3dea79 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/PostModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/PostModule.java @@ -38,7 +38,9 @@ public final class PostModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(PostProcessingSettings.class, PostProcessingSlabsSettings.class, PostProcessingWallsSettings.class); + registry.registerSettings(PostProcessingSettings.class); + registry.registerSettings(PostProcessingSlabsSettings.class); + registry.registerSettings(PostProcessingWallsSettings.class); // Ordering only: iris:carve ships in the built-ins jar, which a pack may not have. setup.stages().define(IrisStages.Post.SMOOTH).softAfter(IrisStages.Carve.APPLY).run(SurfaceSmoothing::smooth); } diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index 791a3ae65..dc9174b3a 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -44,7 +44,8 @@ public final class SpawnModule implements IrisModule { @Override public void setup(ModuleSetup setup) { var registry = setup.registry(); - registry.registerSettings(SpawnerSettings.class, EffectSettings.class); + registry.registerSettings(SpawnerSettings.class); + registry.registerSettings(EffectSettings.class); SpawnResources.kinds().forEach(registry::registerResourceKind); registry.registerService(EntitySpawns.class, new EntitySpawning()); registry.registerService(AmbientEffects.class, new AmbientEffecting()); From 6c4bbb1df54c80c9dcbf836796b8ff21acca2517 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 06:37:33 +0100 Subject: [PATCH 129/139] Place typed markers; drop ObjectMarkers --- .../iris/builtin/blocks/ObjectMarkers.java | 65 ------------------- .../engine/mantle/components/ObjectChunk.java | 6 +- .../engine/object/placement/BlocksModule.java | 4 +- 3 files changed, 5 insertions(+), 70 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java deleted file mode 100644 index 7abc74a7a..000000000 --- a/src/main/java/art/arcane/iris/builtin/blocks/ObjectMarkers.java +++ /dev/null @@ -1,65 +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.builtin.blocks; - -import com.volmit.placement.PlacedMarker; -import com.volmit.resource.ResourceId; -import com.volmit.geometry.BlockPosition; - -import java.util.Map; - -/** - * The placement markers Iris keeps: a pack marker, type {@code iris:marker}, naming the pack's marker under the - * {@code marker} attribute; a placed object's block that is a tree's ({@code iris:tree_material}), which Iris keeps - * as the block's tree material for felling and growth; and a buried treasure chest ({@code iris:buried_treasure}). - */ -public final class ObjectMarkers { - public static final ResourceId TYPE = ResourceId.parse("iris:marker"); - public static final ResourceId TREE_MATERIAL = ResourceId.parse("iris:tree_material"); - public static final ResourceId BURIED_TREASURE = ResourceId.parse("iris:buried_treasure"); - public static final String MARKER_ATTRIBUTE = "marker"; - - private ObjectMarkers() { - } - - public static PlacedMarker treeMaterial(BlockPosition position) { - return new PlacedMarker(position, TREE_MATERIAL, Map.of()); - } - - public static PlacedMarker buriedTreasure(BlockPosition position) { - return new PlacedMarker(position, BURIED_TREASURE, Map.of()); - } - - /** {@code markerKey} is the pack's marker, such as {@code spawn/zombie}. */ - public static PlacedMarker of(BlockPosition position, String markerKey) { - return new PlacedMarker(position, TYPE, Map.of(MARKER_ATTRIBUTE, markerKey)); - } - - public static String markerKey(PlacedMarker marker) { - requireIrisMarker(marker); - return marker.attributes().get(MARKER_ATTRIBUTE); - } - - public static void requireIrisMarker(PlacedMarker marker) { - if (!marker.type().equals(TYPE) || !marker.attributes().containsKey(MARKER_ATTRIBUTE)) { - throw new IllegalArgumentException("Iris stores markers of type " + TYPE + " with a \"" + MARKER_ATTRIBUTE - + "\" attribute only, not " + marker.type() + " " + marker.attributes()); - } - } -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java index deac96b27..09eb22f83 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.modules.objects.CarvedSpace; @@ -37,6 +36,7 @@ import com.volmit.block.BlockRegistry; import com.volmit.block.BlockTrait; import com.volmit.geometry.BlockPosition; import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacedMarker; import com.volmit.placement.PlacementOutcome; import com.volmit.placement.PlacementTerrain; import com.volmit.stage.MantleStageContext; @@ -145,11 +145,11 @@ final class ObjectChunk { if (tags.marker() != null) { placer.recordPlacement(position.x(), position.y(), position.z(), tags.marker()); if (tags.treeMaterial()) { - placer.mark(ObjectMarkers.treeMaterial(position)); + placer.mark(new PlacedMarker.TreeMaterial(position)); } } if (tags.buriedTreasure() && blocks.hasTrait(placer.get(position.x(), position.y(), position.z()), BlockTrait.STORAGE)) { - placer.mark(ObjectMarkers.buriedTreasure(position)); + placer.mark(new PlacedMarker.BuriedTreasure(position)); } } } diff --git a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java index c1707ab17..d9d4b36a3 100644 --- a/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java +++ b/src/main/java/art/arcane/iris/engine/object/placement/BlocksModule.java @@ -19,7 +19,6 @@ package art.arcane.iris.engine.object.placement; import art.arcane.iris.builtin.anchor.PlaceTrait; -import art.arcane.iris.builtin.blocks.ObjectMarkers; import art.arcane.iris.builtin.blocks.WrittenBlocks; import art.arcane.iris.builtin.carve.CarvingMode; import art.arcane.iris.builtin.spawn.SpawnMarker; @@ -40,6 +39,7 @@ import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.object.BlockEntityData; import com.volmit.object.ObjectBlock; +import com.volmit.placement.PlacedMarker; import com.volmit.stage.BlockStageContext; import com.volmit.stage.PlacementStageContext; import com.volmit.geometry.BlockPosition; @@ -231,7 +231,7 @@ public final class BlocksModule implements IrisModule { break; } if (!marker.get().emptyAbove() || hasAirAbove(world, position)) { - context.access().marker(ObjectMarkers.of(position, rule.marker())); + context.access().marker(new PlacedMarker.PackMarker(position, rule.marker())); remaining--; } } From 6e2d94a4c8af8bcc4a5b219d16d4719e8fd3e9bb Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 07:16:26 +0100 Subject: [PATCH 130/139] Name pack resources with @ResourceRef --- .../java/art/arcane/iris/builtin/loot/LootSettings.java | 4 ++-- .../java/art/arcane/iris/builtin/loot/ObjectLoot.java | 4 ++-- .../art/arcane/iris/builtin/objects/ObjectPlacement.java | 8 ++++---- .../java/art/arcane/iris/builtin/spawn/EntitySpawn.java | 4 ++-- .../art/arcane/iris/builtin/spawn/PlacementMarker.java | 4 ++-- .../java/art/arcane/iris/builtin/spawn/SpawnMarker.java | 4 ++-- .../arcane/iris/builtin/structure/IrisStructureRef.java | 2 +- .../arcane/iris/builtin/structure/StructurePlacement.java | 4 ++-- .../arcane/iris/modules/carve/CarvingBiomeSettings.java | 4 ++-- .../java/art/arcane/iris/modules/carve/CarvingEntry.java | 4 ++-- .../arcane/iris/modules/floating/FloatingChildBiome.java | 3 ++- .../art/arcane/iris/modules/spawn/SpawnerSettings.java | 4 ++-- 12 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java index 64cc01d93..5fa19fdf4 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootSettings.java @@ -24,7 +24,7 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; import java.util.Collections; @@ -44,7 +44,7 @@ public final class LootSettings implements IrisFeature { @Desc("ADD = add on top of parent tables. REPLACE = clear parent tables, then add these. CLEAR = clear parent tables and add nothing, even if tables are listed. FALLBACK = only used when nothing else defined a table.") private LootMode mode = LootMode.ADD; - @Ref(kind = LootTable.class) + @ResourceRef(LootTable.class) @Desc("Add loot table registries here") private List tables = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java index 1a185f10f..25461bbf4 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -23,7 +23,7 @@ import com.volmit.config.Desc; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; import java.util.Collections; @@ -39,7 +39,7 @@ public final class ObjectLoot implements ObjectLootEntry { private boolean exact = false; @Desc("The loot table name") @Required - @Ref(kind = LootTable.class) + @ResourceRef(LootTable.class) private String name; @Desc("The weight of this loot table being chosen") @MinNumber(1) diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index bd2588322..44ac1c362 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -44,8 +44,8 @@ import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; -import com.volmit.config.Ref; import com.volmit.config.Required; +import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; import com.volmit.noise.NoiseStyle; import com.volmit.noise.StyledRange; @@ -76,7 +76,7 @@ public final class ObjectPlacement { @Required @MinItems(1) - @Ref(kind = GeneratedObject.class) + @ResourceRef(GeneratedObject.class) @Desc("List of objects to place") private List place = List.of(); @Desc("Rotate this objects placement") @@ -178,11 +178,11 @@ public final class ObjectPlacement { @Desc("This object / these objects override the following trees when they grow...") private List trees = List.of(); @MinItems(1) - @Ref(kind = GeneratedObject.class) + @ResourceRef(GeneratedObject.class) @Desc("List of objects to this object is allowed to collied with") private List allowedCollisions = List.of(); @MinItems(1) - @Ref(kind = GeneratedObject.class) + @ResourceRef(GeneratedObject.class) @Desc("List of objects to this object is forbidden to collied with") private List forbiddenCollisions = List.of(); @Desc("Ignore any placement restrictions for this object") diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java index 6ab4badac..371c3122e 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EntitySpawn.java @@ -21,13 +21,13 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.MinNumber; import com.volmit.config.Required; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; @Snippet("iris/spawn/entity-spawn") @Desc("Represents an entity spawn during initial chunk generation") public final class EntitySpawn { - @Ref(kind = EntityDefinition.class) + @ResourceRef(EntityDefinition.class) @Required @Desc("The entity") private String entity = ""; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java index 3ba8d4eda..ce9906674 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -24,7 +24,7 @@ import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; import java.util.Collections; @@ -45,7 +45,7 @@ public final class PlacementMarker { @Desc("If true, markers will only be placed if the block matches the mark list perfectly.") private boolean exact = false; @Required - @Ref(kind = SpawnMarker.class) + @ResourceRef(SpawnMarker.class) @Desc("The marker to add") private String marker; diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java index c8ebf044a..249b8fb5a 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java @@ -20,7 +20,7 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.MinItems; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import java.util.Collections; import java.util.List; @@ -29,7 +29,7 @@ import java.util.List; @Desc("Represents a marker") public final class SpawnMarker { @Desc("A list of spawners to add to anywhere this marker is.") - @Ref(kind = Spawner.class) + @ResourceRef(Spawner.class) @MinItems(1) private List spawners = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java b/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java index c7b3164d4..ef2bcfc55 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java +++ b/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java @@ -26,7 +26,7 @@ import java.lang.annotation.Target; /** * Iris extension: says that a text option names structures of Iris's structure model by key, which Iris completes in * studio and carries along when it exports the pack. The structure model is Iris's own resource kind, whose class a - * module cannot see, so {@code @Ref(kind = ...)} cannot name it; to another host the option is plain text. + * module cannot see, so {@code @ResourceRef} cannot name it; to another host the option is plain text. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java index 11c2d13e2..88678e308 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java @@ -22,7 +22,7 @@ import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinItems; import com.volmit.config.MinNumber; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.world.PackBiome; import java.util.Collections; @@ -96,7 +96,7 @@ public final class StructurePlacement { private StructureAnchorMode anchor = StructureAnchorMode.LEGACY; @MinItems(1) - @Ref(kind = PackBiome.class) + @ResourceRef(PackBiome.class) @Desc("Optional cave-biome allowlist for cave anchor modes. Empty accepts the cave biome resolved at the selected anchor. Entries match by load key, including prefix matches.") private List caveBiomes = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java b/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java index 964676cd3..391208a09 100644 --- a/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingBiomeSettings.java @@ -22,7 +22,7 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.world.LinkedBiomes; import com.volmit.world.PackBiome; import com.volmit.resource.PackResources; @@ -34,7 +34,7 @@ import java.util.Set; @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") @Feature(id = "iris:carve/biome", name = "Carving biome", key = "carvingBiome", root = "biome", targets = Level.BIOME) public final class CarvingBiomeSettings implements IrisFeature, LinkedBiomes { - @Ref(kind = PackBiome.class) + @ResourceRef(PackBiome.class) @Desc("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.") private String biome = ""; diff --git a/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java b/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java index d630acba4..bcca11714 100644 --- a/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingEntry.java @@ -20,7 +20,7 @@ package art.arcane.iris.modules.carve; import com.volmit.config.Desc; import com.volmit.config.Range; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import com.volmit.world.PackBiome; import com.volmit.config.Snippet; import com.volmit.noise.NoiseStyle; @@ -47,7 +47,7 @@ public final class CarvingEntry { @Desc("Enable or disable this carving entry") private boolean enabled = true; - @Ref(kind = PackBiome.class) + @ResourceRef(PackBiome.class) @Desc("Cave biome to apply when world Y falls within worldYRange") private String biome = ""; diff --git a/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java b/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java index 2970eec26..15c1e0717 100644 --- a/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java @@ -26,6 +26,7 @@ import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; +import com.volmit.config.ResourceRef; import com.volmit.config.Snippet; import com.volmit.world.PackBiome; import com.volmit.noise.NoiseStyle; @@ -52,7 +53,7 @@ public final class FloatingChildBiome { private static final NoiseStyle DEFAULT_EDGE_TAPER_VARIATION_STYLE = NoiseStyle.of("SIMPLEX").withZoom(0.18D); private static final NoiseStyle DEFAULT_FOOTPRINT_STYLE = NoiseStyle.of("SIMPLEX"); - @Ref(kind = PackBiome.class) + @ResourceRef(PackBiome.class) @Desc("The target biome whose visual design (layers, palette, decorators, surface objects, derivative, and — when topShapeMode=BIOME — generator profile) drives the floating island. Leave empty to reuse the parent biome (self).") private String biome = ""; diff --git a/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java b/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java index 7162227e2..c33a32c7d 100644 --- a/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java +++ b/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java @@ -24,7 +24,7 @@ import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MinItems; -import com.volmit.config.Ref; +import com.volmit.config.ResourceRef; import java.util.Collections; import java.util.List; @@ -37,7 +37,7 @@ import java.util.List; @Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class SpawnerSettings implements IrisFeature { @MinItems(1) - @Ref(kind = Spawner.class) + @ResourceRef(Spawner.class) @Desc("Entity spawners to add to this area") private List spawners = List.of(); From 672f781132a64c0795cf82ce46b985c42e5c69b9 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 07:31:09 +0100 Subject: [PATCH 131/139] Document the stage-id disabledComponents and rule-based seeds --- README.md | 6 +++--- src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java | 4 +--- .../java/art/arcane/iris/engine/modifier/CarveModule.java | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8d9f8b9ba..b97b0d1e2 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ per target across all modules and Iris's own fields, so a new built-in or pack m Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages 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. +by its stage id, such as `iris:carve/caves`; a name that matches no stage fails the world. ## Building @@ -206,8 +206,8 @@ through the thread or a cast: a module asks `world.extension(X.class)` for what `StructureHost`, `spawn.SpawnCooldowns`), `context.extension(X.class)` for what belongs to one invocation (`MatterMantle` in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are -IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), which Iris answers with the seeds its worlds always -had, so existing worlds generate the same; `spawn.SpawnCooldowns` (the spawner cooldowns +IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), by the API's rule like any module's; +`spawn.SpawnCooldowns` (the spawner cooldowns Iris saves with the world's data, so they survive a restart), `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`). The placement stages need more of the object being diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java index 11ec40496..22f61d389 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java @@ -22,9 +22,7 @@ import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; /** - * The purposes Iris's built-in modules ask {@link PackWorld#seed(ResourceId)} for. Iris answers each with the seed its - * worlds always used for that feature, derived one after another from a shared random rather than by the API's rule, - * so worlds generated before the features were modules generate the same. + * The purposes Iris's built-in modules ask {@link PackWorld#seed(ResourceId)} for, one per feature. */ public final class IrisSeedPurposes { public static final ResourceId BIOME = purpose("biome"); diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index 71f50bec1..d1db8d7de 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -126,7 +126,7 @@ public final class CarveModule implements IrisModule { } /** - * A dimension turns carving off with {@code carvingEnabled}. Listing {@code CARVED} in {@code disabledComponents} + * A dimension turns carving off with {@code carvingEnabled}. Listing {@code iris:carve/caves} in {@code disabledComponents} * also does: Iris then skips this stage's mantle pass like any disabled component. */ private static boolean carves(ChunkContext context) { From 1e0a8d2bd6a7de69b0023060a4a0389f7c29cf96 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 11:39:35 +0100 Subject: [PATCH 132/139] Keep spawner cooldowns in the module, on RunningWorld.saved SpawnCooldownBook holds when each spawner last fired in the world and in each chunk and is saved with the world through a SavedKey. The SpawnCooldowns facade, which only existed because API state was memory only, is gone. --- .../iris/builtin/spawn/SpawnCooldowns.java | 47 ----- .../iris/engine/spawn/EntitySpawning.java | 5 +- .../iris/engine/spawn/SpawnCooldownBook.java | 174 ++++++++++++++++++ .../arcane/iris/engine/spawn/SpawnerGate.java | 8 +- 4 files changed, 180 insertions(+), 54 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java create mode 100644 src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java deleted file mode 100644 index 8bfb4f624..000000000 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCooldowns.java +++ /dev/null @@ -1,47 +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.builtin.spawn; - -import java.util.function.ToLongFunction; - -/** - * When spawners last fired, which Iris keeps with the world's data so that a spawner's rates hold across restarts. Rates - * count per spawner, by the key the pack names it by, in the world and in each chunk. Iris offers it as an extension of - * its worlds: {@code world.extension(SpawnCooldowns.class)}. - */ -public interface SpawnCooldowns { - /** Whether the spawner may fire in the world again, {@code intervalMilliseconds} after it last did. */ - boolean canSpawn(String spawner, long intervalMilliseconds); - - /** Notes that the spawner fired in the world now. */ - void spawned(String spawner); - - /** Whether the spawner may fire in the chunk again, {@code intervalMilliseconds} after it last did there. */ - boolean canSpawnInChunk(int chunkX, int chunkZ, String spawner, long intervalMilliseconds); - - /** Notes that the spawner fired in the chunk now. */ - void spawnedInChunk(int chunkX, int chunkZ, String spawner); - - /** - * Forgets the cooldowns that ran out and those of spawners the pack no longer has, so the world's data does not grow. - * - * @param intervalMilliseconds the interval of the world rate of a spawner by its key, or a negative number for a spawner the pack lacks - */ - void forgetExpired(ToLongFunction intervalMilliseconds); -} diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 6048e541c..805a80fde 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -22,7 +22,6 @@ import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.loot.LootResolver; import art.arcane.iris.builtin.spawn.EntityDefinition; import art.arcane.iris.builtin.spawn.EntitySpawn; -import art.arcane.iris.builtin.spawn.SpawnCooldowns; import art.arcane.iris.builtin.spawn.SpawnMarker; import art.arcane.iris.builtin.spawn.SpawnSurface; import art.arcane.iris.builtin.spawn.Spawner; @@ -116,14 +115,14 @@ public final class EntitySpawning implements EntitySpawns { return Optional.of(new MarkerRule(spawners, marker.emptyAbove(), marker.removeOnChange())); } - /** Drops the cooldowns that ran out, now and then: the world's data keeps them across restarts. */ + /** Drops the cooldowns that ran out, now and then: the world saves them across restarts. */ private static void forgetExpiredCooldowns(PackWorld world) { CooldownCleanup cleanup = world.state(CooldownCleanup.class, ignored -> new CooldownCleanup()); if (!cleanup.due()) { return; } PackResources resources = world.resources(); - world.extension(SpawnCooldowns.class).orElseThrow().forgetExpired(key -> { + SpawnCooldownBook.of(world).forgetExpired(key -> { Spawner spawner = SpawnResources.spawner(resources, key); return spawner == null ? -1L : spawner.maximumRate().interval(); }); diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java new file mode 100644 index 000000000..081b4f1bc --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java @@ -0,0 +1,174 @@ +/* + * 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.spawn; + +import art.arcane.volmlib.util.cache.CacheKey; +import com.volmit.data.Codec; +import com.volmit.world.PackWorld; +import com.volmit.world.SavedKey; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.LongSupplier; +import java.util.function.ToLongFunction; + +/** + * When spawners last fired, in the world and in each chunk, which the host saves with the world so that a spawner's + * rates hold across restarts. Spawners count by the key the pack names them by. Safe for concurrent use. + */ +final class SpawnCooldownBook { + static final SavedKey SAVED = new SavedKey<>("iris:spawn/cooldowns", SpawnCooldownBook.class, + codec(System::currentTimeMillis), () -> new SpawnCooldownBook(System::currentTimeMillis)); + + private static final int FORMAT_VERSION = 1; + + private final LongSupplier clockMilliseconds; + private final Map worldFiredAt = new ConcurrentHashMap<>(); + private final Map> chunkFiredAt = new ConcurrentHashMap<>(); + + SpawnCooldownBook(LongSupplier clockMilliseconds) { + this.clockMilliseconds = clockMilliseconds; + } + + /** The book the world keeps. */ + static SpawnCooldownBook of(PackWorld world) { + return world.running().orElseThrow().saved(SAVED); + } + + /** How {@link #SAVED} is stored: the books read by this codec count time with {@code clockMilliseconds}. */ + static Codec codec(LongSupplier clockMilliseconds) { + return new BookCodec(clockMilliseconds); + } + + /** Whether the spawner may fire in the world again, {@code intervalMilliseconds} after it last did. */ + boolean canSpawn(String spawner, long intervalMilliseconds) { + return hasElapsed(worldFiredAt.get(spawner), intervalMilliseconds); + } + + /** Notes that the spawner fired in the world now. */ + void spawned(String spawner) { + worldFiredAt.put(spawner, clockMilliseconds.getAsLong()); + } + + /** Whether the spawner may fire in the chunk again, {@code intervalMilliseconds} after it last did there. */ + boolean canSpawnInChunk(int chunkX, int chunkZ, String spawner, long intervalMilliseconds) { + Map spawnersOfChunk = chunkFiredAt.get(CacheKey.key(chunkX, chunkZ)); + return hasElapsed(spawnersOfChunk == null ? null : spawnersOfChunk.get(spawner), intervalMilliseconds); + } + + /** Notes that the spawner fired in the chunk now. */ + void spawnedInChunk(int chunkX, int chunkZ, String spawner) { + long firedAt = clockMilliseconds.getAsLong(); + chunkFiredAt.compute(CacheKey.key(chunkX, chunkZ), (chunk, spawnersOfChunk) -> { + Map kept = spawnersOfChunk == null ? new ConcurrentHashMap<>() : spawnersOfChunk; + kept.put(spawner, firedAt); + return kept; + }); + } + + /** + * Forgets the cooldowns that ran out and those of spawners the pack no longer has, so the saved data does not grow. + * + * @param intervalMilliseconds the interval of the world rate of a spawner by its key, or a negative number for a spawner the pack lacks + */ + void forgetExpired(ToLongFunction intervalMilliseconds) { + worldFiredAt.entrySet().removeIf(fired -> isForgotten(fired.getKey(), fired.getValue(), intervalMilliseconds)); + for (Long chunk : List.copyOf(chunkFiredAt.keySet())) { + chunkFiredAt.computeIfPresent(chunk, (key, spawnersOfChunk) -> { + spawnersOfChunk.entrySet().removeIf(fired -> isForgotten(fired.getKey(), fired.getValue(), intervalMilliseconds)); + return spawnersOfChunk.isEmpty() ? null : spawnersOfChunk; + }); + } + } + + private boolean isForgotten(String spawner, long firedAt, ToLongFunction intervalMilliseconds) { + long interval = intervalMilliseconds.applyAsLong(spawner); + return interval < 0 || hasElapsed(firedAt, interval); + } + + private boolean hasElapsed(Long firedAt, long intervalMilliseconds) { + return firedAt == null || clockMilliseconds.getAsLong() - firedAt > intervalMilliseconds; + } + + private record BookCodec(LongSupplier clockMilliseconds) implements Codec { + @Override + public int version() { + return FORMAT_VERSION; + } + + @Override + public void write(DataOutput output, SpawnCooldownBook book) throws IOException { + writeFired(output, book.worldFiredAt); + List>> chunks = new ArrayList<>(book.chunkFiredAt.entrySet()); + output.writeInt(chunks.size()); + for (Map.Entry> chunk : chunks) { + output.writeLong(chunk.getKey()); + writeFired(output, chunk.getValue()); + } + } + + @Override + public SpawnCooldownBook read(DataInput input, int storedVersion) throws IOException { + if (storedVersion != FORMAT_VERSION) { + throw new IOException("Unsupported spawn cooldown format version " + storedVersion); + } + SpawnCooldownBook book = new SpawnCooldownBook(clockMilliseconds); + readFired(input, book.worldFiredAt); + int chunks = readCount(input); + for (int chunk = 0; chunk < chunks; chunk++) { + Map spawnersOfChunk = new ConcurrentHashMap<>(); + long key = input.readLong(); + readFired(input, spawnersOfChunk); + if (!spawnersOfChunk.isEmpty()) { + book.chunkFiredAt.put(key, spawnersOfChunk); + } + } + return book; + } + + private static void writeFired(DataOutput output, Map firedAt) throws IOException { + List> snapshot = new ArrayList<>(firedAt.entrySet()); + output.writeInt(snapshot.size()); + for (Map.Entry fired : snapshot) { + output.writeUTF(fired.getKey()); + output.writeLong(fired.getValue()); + } + } + + private static void readFired(DataInput input, Map firedAt) throws IOException { + int count = readCount(input); + for (int index = 0; index < count; index++) { + firedAt.put(input.readUTF(), input.readLong()); + } + } + + private static int readCount(DataInput input) throws IOException { + int count = input.readInt(); + if (count < 0) { + throw new IOException("Negative entry count " + count); + } + return count; + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java index 3cdfb770f..6fa594297 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnerGate.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.spawn; -import art.arcane.iris.builtin.spawn.SpawnCooldowns; import art.arcane.iris.builtin.spawn.SpawnRate; import art.arcane.iris.builtin.spawn.Spawner; import com.volmit.world.BiomeKind; @@ -29,15 +28,16 @@ import java.util.Optional; /** * Whether a spawner may fire: in a biome of the kind its group wants, in the time and weather it asks for, and not - * more often than its rates allow. The rates count in the world's data, by the key the pack names the spawner by. + * more often than its rates allow. The rates count in the world's saved cooldowns, by the key the pack names the + * spawner by. * * @param sky the world's time and weather when the gate was made; empty while the platform has not loaded the world * @param cooldowns when the world's spawners last fired */ -record SpawnerGate(Optional sky, SpawnCooldowns cooldowns) { +record SpawnerGate(Optional sky, SpawnCooldownBook cooldowns) { /** The gate of the running world, with its time and weather now. */ static SpawnerGate of(PackWorld world) { - return new SpawnerGate(world.running().orElseThrow().sky(), world.extension(SpawnCooldowns.class).orElseThrow()); + return new SpawnerGate(world.running().orElseThrow().sky(), SpawnCooldownBook.of(world)); } /** Whether a spawner of this group fires in a biome of {@code kind}. */ From fa7c3a0abfdce2ea131697264fc9917b4961c6c4 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 11:39:35 +0100 Subject: [PATCH 133/139] Draw object chunk random, density and heightmap from API types The chunk random is seeded from a purpose seed and the chunk, the density from StyledRange over the API noise factory, and VirtualHeightmap builds the virtual heightmap from NoiseSampler. LegacyStreams and ObjectPlacement.hostForm, which only served Iris's placement form, are removed. The chunk random and density noise now differ from the old streams; heightmaps are unchanged. --- README.md | 17 ++- .../arcane/iris/builtin/IrisSeedPurposes.java | 4 + .../arcane/iris/builtin/LegacyStreams.java | 38 ------ .../iris/builtin/objects/ObjectPlacement.java | 17 --- .../art/arcane/iris/builtin/package-info.java | 5 +- .../mantle/components/ChunkObjectPlacing.java | 6 +- .../components/FloatingObjectPlacing.java | 6 +- .../mantle/components/ObjectPlacing.java | 2 +- .../mantle/components/ObjectWarmUp.java | 12 +- .../iris/modules/objects/ObjectPool.java | 36 ++++-- .../modules/placement/RunningPlacement.java | 10 +- .../modules/placement/VirtualHeightmap.java | 111 ++++++++++++++++++ 12 files changed, 163 insertions(+), 101 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/LegacyStreams.java create mode 100644 src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java diff --git a/README.md b/README.md index b97b0d1e2..7cb99f033 100644 --- a/README.md +++ b/README.md @@ -97,9 +97,8 @@ An object placement is `iris:objects` settings (`objects.ObjectPlacement`, under settings inside it, such as its clamp, stilt, vacuum and edit settings, its slope condition or a procedural coral, are module-owned classes too (`art.arcane.iris.builtin.validate`, `.stilt`, `.vacuum`, `.blocks`, `.prepare`, `.carve`, `.floating`, `.objects.*`), so studio describes them from the module's own annotations. Iris reads a placement's module -settings (the keys pack modules add at `Level.PLACEMENT`) from the JSON the placement was written as (`json()`), and keeps -what it makes of the placement in `hostForm()`; a placement made in code uses `ObjectPlacement.builder()` or -`toBuilder()`. Packs write the same JSON as before. Behaviour +settings (the keys pack modules add at `Level.PLACEMENT`) from the JSON the placement was written as (`json()`); a +placement made in code uses `ObjectPlacement.builder()` or `toBuilder()`. Packs write the same JSON as before. Behaviour that needs Iris (noise built from the styles, blocks resolved through the pack, baked object variants) lives in `Resolved*` classes beside the worker (`ResolvedReplace`, `ResolvedCaveProfile`, `ResolvedFloatingChild`, `ResolvedProceduralPlacement`). @@ -202,14 +201,14 @@ none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps e `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never -through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`LegacyStreams`, -`StructureHost`, `spawn.SpawnCooldowns`), `context.extension(X.class)` for what belongs to one invocation (`MatterMantle` +through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`StructureHost`), +`context.extension(X.class)` for what belongs to one invocation (`MatterMantle` in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are -IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), by the API's rule like any module's; -`spawn.SpawnCooldowns` (the spawner cooldowns -Iris saves with the world's data, so they survive a restart), -`loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and +IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), by the API's rule like any module's. What the +built-ins keep with a world across restarts, such as the spawner cooldowns (`SpawnCooldownBook`), they save through +`RunningWorld.saved`; object placing seeds its chunk random, density noise and virtual heightmaps from purpose seeds and IrisApi noise. +The package also holds `loot.LootResolver` (the random streams loot is drawn from, shared with the hosts that fill containers) and the loot and marker lists of an object placement (`loot.ObjectLoot`, `loot.ObjectVanillaLoot`, `spawn.PlacementMarker`). The placement stages need more of the object being placed than IrisApi describes, so `placement.ObjectPlacement` is the facade Iris implements for each placement and offers with its invocation (`context.extension(ObjectPlacement.class)`): the object's size (`ObjectShape`), the placement's settings (`PlacementSettings`, read from diff --git a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java index 22f61d389..f05347f18 100644 --- a/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java +++ b/src/main/java/art/arcane/iris/builtin/IrisSeedPurposes.java @@ -34,6 +34,10 @@ public final class IrisSeedPurposes { public static final ResourceId ENTITY = purpose("entity"); public static final ResourceId LOOT = purpose("loot"); public static final ResourceId MANTLE = purpose("mantle"); + /** The random each chunk's objects are placed with, before the chunk's coordinates are mixed in. */ + public static final ResourceId OBJECT_CHUNK = purpose("object-chunk"); + /** The noise that picks the count of a placement with a density style. */ + public static final ResourceId OBJECT_DENSITY = purpose("object-density"); /** The noise that warps the columns of object placements with a surface warp. */ public static final ResourceId OBJECT_WARP = purpose("object-warp"); /** The candidate spots, ranks and chance noise of separated object placements. */ diff --git a/src/main/java/art/arcane/iris/builtin/LegacyStreams.java b/src/main/java/art/arcane/iris/builtin/LegacyStreams.java deleted file mode 100644 index e00716157..000000000 --- a/src/main/java/art/arcane/iris/builtin/LegacyStreams.java +++ /dev/null @@ -1,38 +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.builtin; - -import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.volmlib.util.math.RNG; - -/** - * The random streams and noise of Iris's own generators that decide where existing worlds have their objects, which no - * API noise reproduces: Iris's chunk random, and the noise of a placement's density style and virtual heightmap. Iris - * offers it as an extension of its worlds: {@code world.extension(LegacyStreams.class)}. - */ -public interface LegacyStreams { - /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ - RNG objectChunkRandom(int chunkX, int chunkZ); - - /** How many objects the placement places at the column: its fixed density, or what its density style gives there for {@code rng}. */ - int density(ObjectPlacement placement, RNG rng, double x, double z); - - /** The height the placement's virtual heightmap gives the column, its noise seeded with {@code seed}; for a placement with a heightmap. */ - int heightmapSurface(ObjectPlacement placement, long seed, int x, int z); -} diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index 44ac1c362..4ffb1f5cc 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -190,7 +190,6 @@ public final class ObjectPlacement { private boolean forcePlace = false; private transient volatile String json; - private transient volatile Object hostForm; public ObjectPlacement() { } @@ -240,7 +239,6 @@ public final class ObjectPlacement { forbiddenCollisions = source.forbiddenCollisions; forcePlace = source.forcePlace; json = source.json; - hostForm = source.hostForm; } /** A builder of a placement made in code, starting from the defaults a pack's placement starts from. */ @@ -478,18 +476,6 @@ public final class ObjectPlacement { return names; } - /** - * What Iris made of this placement the last time it asked, kept here so it asks once. Only Iris sets or reads it, - * and it is its own type. - */ - public Object hostForm() { - return hostForm; - } - - public void hostForm(Object form) { - this.hostForm = form; - } - private static List listOf(List values) { return values == null ? List.of() : Collections.unmodifiableList(values); } @@ -544,7 +530,6 @@ public final class ObjectPlacement { public Builder densityStyle(StyledRange densityStyle) { placement.densityStyle = densityStyle; - placement.hostForm = null; return this; } @@ -605,7 +590,6 @@ public final class ObjectPlacement { public Builder heightmap(HeightmapNoise heightmap) { placement.heightmap = heightmap; - placement.hostForm = null; return this; } @@ -646,7 +630,6 @@ public final class ObjectPlacement { public Builder warp(NoiseStyle warp) { placement.warp = warp; - placement.hostForm = null; return this; } diff --git a/src/main/java/art/arcane/iris/builtin/package-info.java b/src/main/java/art/arcane/iris/builtin/package-info.java index 5a6a97740..8d084d393 100644 --- a/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/src/main/java/art/arcane/iris/builtin/package-info.java @@ -30,9 +30,8 @@ *

* Besides those, it holds what Iris and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.spawn.SpawnCooldowns}, {@link art.arcane.iris.builtin.LegacyStreams}), and the seed purposes Iris - * answers with its legacy seeds ({@link art.arcane.iris.builtin.IrisSeedPurposes}). Keep them few: each is - * a promise. + * ({@link art.arcane.iris.builtin.structure.StructureHost}), and the seed purposes of the built-in features + * ({@link art.arcane.iris.builtin.IrisSeedPurposes}). Keep them few: each is a promise. *

* The placement stages ({@code iris:prepare} to {@code iris:snow}) run in the pack's placement graph, which * {@code PackWorld.placements()} runs. They read the object and its settings from the run's input, diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java index fae8e63b0..d54dcc9aa 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ChunkObjectPlacing.java @@ -302,7 +302,7 @@ final class ChunkObjectPlacing { private void placeObject(Tally tally, ObjectPlacement placement, String scope) { int blockX = context.originX(); int blockZ = context.originZ(); - int density = objects.density(placement, rng, blockX, blockZ); + int density = objects.density(placement, blockX, blockZ); for (int i = 0; i < density; i++) { tally.attempts++; Optional picked = objects.pickScaled(placement, rng); @@ -347,7 +347,7 @@ final class ChunkObjectPlacing { ResourceId expectedCaveBiome, CaveAnchors anchors) { int minX = context.originX(); int minZ = context.originZ(); - int density = objects.density(placement, rng, minX, minZ); + int density = objects.density(placement, minX, minZ); CaveAnchors.Search search = caves.searchFor(placement, profile); for (int i = 0; i < density; i++) { tally.attempts++; @@ -439,7 +439,7 @@ final class ChunkObjectPlacing { private void placeUpperObject(ObjectPlacement placement, boolean forcePlace, String scope) { int minX = context.originX(); int minZ = context.originZ(); - int density = objects.density(placement, rng, minX, minZ); + int density = objects.density(placement, minX, minZ); for (int i = 0; i < density; i++) { Optional picked = objects.pickScaled(placement, rng); if (picked.isEmpty()) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java index 0d7964d2e..648ebe491 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/FloatingObjectPlacing.java @@ -200,7 +200,7 @@ public final class FloatingObjectPlacing { private void placeFloating(Chunk chunk, ObjectPlacement placement, KList columns, ResolvedFloatingChild entry) { RNG rng = chunk.rng; - int density = objects.density(placement, rng, chunk.minX, chunk.minZ); + int density = objects.density(placement, chunk.minX, chunk.minZ); for (int i = 0; i < density; i++) { Optional picked = pick(placement, entry, rng); if (picked.isEmpty()) { @@ -214,7 +214,7 @@ public final class FloatingObjectPlacing { private void placeAnchored(Chunk chunk, ObjectPlacement placement, KList columns, KList interior, ResolvedFloatingChild entry) { RNG rng = chunk.rng; - int density = objects.density(placement, rng, chunk.minX, chunk.minZ); + int density = objects.density(placement, chunk.minX, chunk.minZ); for (int i = 0; i < density; i++) { Optional picked = pick(placement, entry, rng); if (picked.isEmpty()) { @@ -249,7 +249,7 @@ public final class FloatingObjectPlacing { private void placeInverted(Chunk chunk, ObjectPlacement placement, KList columns, KList interior, ResolvedFloatingChild entry) { RNG rng = chunk.rng; - int density = objects.density(placement, rng, chunk.minX, chunk.minZ); + int density = objects.density(placement, chunk.minX, chunk.minZ); for (int i = 0; i < density; i++) { Optional picked = pick(placement, entry, rng); if (picked.isEmpty()) { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java index 7a2770d64..6ad7a402a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectPlacing.java @@ -105,7 +105,7 @@ public final class ObjectPlacing { private Set guessPlacedKeys(RNG rng, int x, int z, ObjectPlacement placement) { Set keys = new HashSet<>(); - for (int i = 0; i < objects.density(placement, rng, x, z); i++) { + for (int i = 0; i < objects.density(placement, x, z); i++) { Optional picked = objects.pickScaled(placement, rng); picked.ifPresent(object -> keys.add(object.name())); } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java index f48ddb42c..8e60aeaa1 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectWarmUp.java @@ -18,12 +18,10 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; import art.arcane.iris.modules.objects.Declaration; import art.arcane.iris.modules.objects.ObjectPool; -import art.arcane.volmlib.util.math.RNG; import com.volmit.config.Level; import com.volmit.world.PackWorld; @@ -32,22 +30,18 @@ import java.util.List; /** * Builds what object placing would build on first use, for every object placement and procedural object the world's - * biomes and regions declare: the placement's density noise, and a procedural object's variants. None of it depends on - * the random it is warmed with; the density noise is cached per seed and the variants are baked whatever picks one. + * biomes and regions declare: the placement's density noise, and a procedural object's variants. The density noise is + * cached per seed and the variants are baked whatever picks one. */ final class ObjectWarmUp { - private static final long ROOT_SEED_SALT = 7777L; private static final Level[] WARMED_LEVELS = {Level.BIOME, Level.REGION}; private final PackWorld world; private final ObjectPool objects; - private final RNG root; - private int warmed; ObjectWarmUp(PackWorld world) { this.world = world; this.objects = ObjectPool.of(world); - this.root = new RNG(world.seed(IrisSeedPurposes.COMPONENT) + ROOT_SEED_SALT); } void warm() { @@ -68,7 +62,7 @@ final class ObjectWarmUp { private void warmPlacements(List placements) { for (ObjectPlacement placement : placements) { if (placement != null) { - objects.warm(placement, root.nextParallelRNG(warmed++)); + objects.warm(placement); } } } diff --git a/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java b/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java index 014b5ef01..36cd79883 100644 --- a/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java +++ b/src/main/java/art/arcane/iris/modules/objects/ObjectPool.java @@ -18,15 +18,18 @@ package art.arcane.iris.modules.objects; -import art.arcane.iris.builtin.LegacyStreams; +import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectScale; import art.arcane.iris.builtin.objects.ScaleInterpolation; import art.arcane.iris.engine.procedural.ProceduralObjectCatalog; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.math.RNG; +import com.volmit.noise.StyledRange; import com.volmit.object.PackObjects; import com.volmit.object.PlaceableObject; import com.volmit.object.ScaleMethod; +import com.volmit.random.WorldRandom; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; @@ -35,30 +38,33 @@ import java.util.Optional; /** * The pack's objects as object placements pick them: by key, scaled the way a placement scales them, and as many at a - * column as its density says, drawn from Iris's own streams so existing worlds keep their objects. + * column as its density says, drawn from random streams and noise seeded by the world. */ public final class ObjectPool { private static final double NO_SCALE = 1D; private static final int MAX_SCALE_VARIANTS = 32; private final PackResources resources; - private final LegacyStreams streams; + private final long chunkSeed; + private final long densitySeed; private final ProceduralObjectCatalog procedural; - private ObjectPool(PackResources resources, LegacyStreams streams, ProceduralObjectCatalog procedural) { + private ObjectPool(PackResources resources, long chunkSeed, long densitySeed, ProceduralObjectCatalog procedural) { this.resources = resources; - this.streams = streams; + this.chunkSeed = chunkSeed; + this.densitySeed = densitySeed; this.procedural = procedural; } /** The objects of {@code world}'s pack, its procedural objects among them. */ public static ObjectPool of(PackWorld world) { - return new ObjectPool(world.resources(), world.extension(LegacyStreams.class).orElseThrow(), ProceduralObjectCatalog.of(world)); + return new ObjectPool(world.resources(), world.seed(IrisSeedPurposes.OBJECT_CHUNK), + world.seed(IrisSeedPurposes.OBJECT_DENSITY), ProceduralObjectCatalog.of(world)); } - /** The random a chunk's objects are placed with. */ + /** The random a chunk's objects are placed with: the same for the same chunk of the same world. */ public RNG chunkRandom(int chunkX, int chunkZ) { - return streams.objectChunkRandom(chunkX, chunkZ); + return new RNG(new WorldRandom(chunkSeed + CacheKey.key(chunkX, chunkZ)).nextLong()); } /** The pack object {@code key} names; for a procedural pool, the variant {@code rng} picks. */ @@ -83,14 +89,18 @@ public final class ObjectPool { return factor == NO_SCALE ? origin : objects().scaled(origin, factor, ScaleMethod.NONE); } - /** How many objects the placement places at the column, when its chance check passes. */ - public int density(ObjectPlacement placement, RNG rng, double x, double z) { - return streams.density(placement, rng, x, z); + /** How many objects the placement places at the column, when its chance check passes: its fixed density, or what its density style gives there. */ + public int density(ObjectPlacement placement, double x, double z) { + Optional densityStyle = placement.densityStyle(); + if (densityStyle.isEmpty()) { + return placement.density(); + } + return (int) Math.round(densityStyle.get().at(resources.noise(), densitySeed, x, z)); } /** Builds the noise the placement draws its density from and bakes its procedural objects, so the first chunk to place it does not wait. */ - public void warm(ObjectPlacement placement, RNG rng) { - streams.density(placement, rng, 0, 0); + public void warm(ObjectPlacement placement) { + density(placement, 0, 0); placement.place().stream().filter(ProceduralObjectCatalog::isProceduralKey).forEach(procedural::placeable); } diff --git a/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java b/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java index 6f14cbc36..d37650b2a 100644 --- a/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java +++ b/src/main/java/art/arcane/iris/modules/placement/RunningPlacement.java @@ -19,7 +19,7 @@ package art.arcane.iris.modules.placement; import art.arcane.iris.builtin.IrisSeedPurposes; -import art.arcane.iris.builtin.LegacyStreams; +import art.arcane.iris.builtin.objects.HeightmapNoise; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; import art.arcane.iris.builtin.prepare.ObjectRotation; @@ -103,13 +103,13 @@ public final class RunningPlacement { * terrain with its heights from the heightmap's noise, seeded from {@code rng}. */ public StageTerrain terrainFor(RNG rng) { - ObjectPlacement config = run.settings(); - if (config.heightmap().isEmpty()) { + Optional heightmapSettings = run.settings().heightmap(); + if (heightmapSettings.isEmpty()) { return terrain; } long heightmapSeed = rng.nextLong() + run.requestedY() + run.z() - run.x(); - LegacyStreams streams = world().extension(LegacyStreams.class).orElseThrow(); - return terrain.withHeights((x, z) -> streams.heightmapSurface(config, heightmapSeed, x, z)); + VirtualHeightmap heightmap = VirtualHeightmap.of(heightmapSettings.get(), world().resources().noise(), heightmapSeed); + return terrain.withHeights(heightmap::surface); } /** diff --git a/src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java b/src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java new file mode 100644 index 000000000..8a240f510 --- /dev/null +++ b/src/main/java/art/arcane/iris/modules/placement/VirtualHeightmap.java @@ -0,0 +1,111 @@ +/* + * 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.modules.placement; + +import art.arcane.iris.builtin.objects.HeightmapNoise; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; + +import java.util.ArrayList; +import java.util.List; + +/** + * The heights of an object placement's virtual heightmap: the noise of a {@link HeightmapNoise} and of the + * generators that fracture its coordinates, built once from API noise and seeded from one number. The setting + * {@code octaves} never changed Iris's values, so it is not read. + */ +public final class VirtualHeightmap { + private static final long GENERATOR_SEED_SALT = 33_955_677L; + private static final long FIRST_FRACTURE_SEED_OFFSET = 33L; + private static final long FRACTURE_SEED_STEP = 819L; + + private final HeightmapNoise settings; + private final NoiseSampler sampler; + private final List fractures; + + private VirtualHeightmap(HeightmapNoise settings, NoiseFactory noise, long seed) { + this.settings = settings; + this.sampler = settings.enabled() ? noise.sampler(settings.style(), seed + GENERATOR_SEED_SALT - settings.seed()) : null; + this.fractures = fracturesOf(settings, noise, seed); + } + + /** The heightmap {@code settings} describe, its noise seeded with {@code seed}. */ + public static VirtualHeightmap of(HeightmapNoise settings, NoiseFactory noise, long seed) { + return new VirtualHeightmap(settings, noise, seed); + } + + /** The height at the column, rounded to a whole block. */ + public int surface(int x, int z) { + return (int) Math.round(valueAt(x, z)); + } + + private static List fracturesOf(HeightmapNoise settings, NoiseFactory noise, long seed) { + List built = new ArrayList<>(); + long fractureOffset = FIRST_FRACTURE_SEED_OFFSET; + for (HeightmapNoise fracture : settings.fracture()) { + if (fracture.enabled()) { + built.add(new VirtualHeightmap(fracture, noise, seed + settings.seed() + fractureOffset)); + } + fractureOffset += FRACTURE_SEED_STEP; + } + return List.copyOf(built); + } + + private double valueAt(double columnX, double columnZ) { + if (!settings.enabled()) { + return settings.offsetY(); + } + double x = columnX; + double z = columnZ; + for (VirtualHeightmap fracture : fractures) { + double centre = fracture.settings.opacity() / 2D; + x += fracture.valueAt(columnX, columnZ) - centre; + z += fracture.valueAt(columnZ, columnX) - centre; + } + double sampleX = (x / settings.zoom()) + settings.offsetX(); + double sampleZ = (z / settings.zoom()) + settings.offsetZ(); + return shaped(sampler.sample(sampleX, sampleZ) * settings.opacity()); + } + + private double shaped(double sampled) { + double value = settings.negative() ? (-sampled + settings.opacity()) : sampled; + value = raised(value) + settings.offsetY(); + if (settings.parametric()) { + value = parametric(value); + } + if (settings.bezier()) { + value = value * value * (3D - 2D * value); + } + return settings.sinCentered() ? Math.sin(value * Math.PI) : value; + } + + private double raised(double value) { + double exponent = settings.exponent(); + if (exponent == 1D) { + return value; + } + return value < 0 ? -Math.pow(-value, exponent) : Math.pow(value, exponent); + } + + /** The parametric curve of alpha 1, which is what the setting has always applied. */ + private static double parametric(double value) { + double raised = Math.pow(value, 1D); + return raised / ((raised - Math.pow(value, 0D)) + 1D); + } +} From 62e33edfe33cef9cfb0ae1bd5bf409a1d51f36ee Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 12:22:59 +0100 Subject: [PATCH 134/139] Plan caves in Mantle.carved, drop MatterMantle The carver, its fluid-support and orphan passes, CaveApplying and CarvedSpace read and write IrisApi's carved-void layer instead of VolmLib matter slices. Cave floors for the spawners are marked by the carve mantle stage through PlacementTerrain.mark, from the planned voids; cave ceiling markers, which nothing read, are gone. CaveApplying reads the 16 blocks around its chunk through the chunk stage's mantle view, not only the neighbours already in memory. MatterMantle and the module's Cavern are deleted. --- README.md | 12 +- builtin-modules.txt | 1 + .../art/arcane/iris/builtin/MatterMantle.java | 45 ---- .../mantle/components/CarveOrphanSweep.java | 81 ++---- .../engine/mantle/components/CaveAnchors.java | 12 +- .../mantle/components/CaveCarveScratch.java | 8 +- .../engine/mantle/components/CaveCarving.java | 25 +- .../mantle/components/CaveFloorMarking.java | 120 +++++++++ .../components/CaveFluidSupportPlan.java | 108 +++----- .../mantle/components/IrisCaveCarver3D.java | 198 +++++---------- .../engine/mantle/components/ObjectChunk.java | 3 +- .../iris/engine/modifier/CarveModule.java | 17 +- .../iris/engine/modifier/CarveWallBuffer.java | 26 +- .../iris/engine/modifier/CaveApplying.java | 233 +++++++----------- .../engine/modifier/IrisCarveScratch.java | 2 +- .../iris/modules/objects/CarvedSpace.java | 82 ++---- .../arcane/iris/modules/objects/Cavern.java | 29 --- 17 files changed, 398 insertions(+), 604 deletions(-) delete mode 100644 src/main/java/art/arcane/iris/builtin/MatterMantle.java create mode 100644 src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java delete mode 100644 src/main/java/art/arcane/iris/modules/objects/Cavern.java diff --git a/README.md b/README.md index 7cb99f033..b33160710 100644 --- a/README.md +++ b/README.md @@ -202,8 +202,8 @@ none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps e `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`StructureHost`), -`context.extension(X.class)` for what belongs to one invocation (`MatterMantle` -in a chunk or mantle stage) and `settings.extension(X.class)` for a reach worked out +`context.extension(X.class)` for what belongs to one invocation (`IrisChunk` in a chunk stage, `IrisMantleChunk` in a mantle stage) and +`settings.extension(X.class)` for a reach worked out before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are IrisApi purpose seeds: `world.seed(IrisSeedPurposes.CARVE)` (`iris:seed/carve`), by the API's rule like any module's. What the built-ins keep with a world across restarts, such as the spawner cooldowns (`SpawnCooldownBook`), they save through @@ -218,10 +218,10 @@ placement's own states). Its types answer with IrisApi, VolmLib and built-in val `iris:prepare/transforms`, lives in the exposed package too, because `IrisStages` names it. `iris:post` reads its switches (`postProcessingWalls`, `postProcessingSlabs`) and the biome's `wall` and `slab` as module settings through its context. -`iris:carve` also reads the mantle's matter slices through `MatterMantle` (the chunk of `MatterCavern`s and markers it plans and -applies, which the platform and the rest of Iris read as slices, not as module layers). A mantle stage gets the whole mantle; a -chunk stage gets its own chunk and the neighbors the world already holds in memory, which is all the cave apply stage ever read, -so it writes nothing outside its chunk. What a +`iris:carve` plans its caves in IrisApi's host-owned `Mantle.carved()` layer (`CarvedVoid`: open, fluid, lava or air, and optionally a +biome), which Iris keeps in its own form for the platform and the rest of Iris to read. The mantle stage writes it; the apply stage +reads it, and one block beyond its chunk to wall the caves that cross the border. The cave floors the spawners use are marked by the mantle +stage with `PlacementTerrain.mark(PackMarker("cave_floor"))`. What a cave's walls, floor and ceiling get comes from the terrain and decorant built-ins of the same jar (`modules.terrain.BiomeLayers`, `modules.terrain.TerrainPalettes`, the biome decorators), through carve's own `CaveDressing`, which tests replace with fixed blocks. A cave's dimension, region and biome settings are found by the id the layout's biome samples carry (`DeclaredByLevel`), its diff --git a/builtin-modules.txt b/builtin-modules.txt index 2be9067bf..9b89e2c4c 100644 --- a/builtin-modules.txt +++ b/builtin-modules.txt @@ -57,6 +57,7 @@ include art/arcane/iris/engine/mantle/components/CarveWorld.class include art/arcane/iris/engine/mantle/components/CaveCarveScratch*.class include art/arcane/iris/engine/mantle/components/CaveCarving*.class include art/arcane/iris/engine/mantle/components/CaveFieldModuleState.class +include art/arcane/iris/engine/mantle/components/CaveFloorMarking*.class include art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan*.class include art/arcane/iris/engine/mantle/components/IrisCaveCarver3D*.class include art/arcane/iris/engine/mantle/components/SurfaceFluidBoundaryPlan*.class diff --git a/src/main/java/art/arcane/iris/builtin/MatterMantle.java b/src/main/java/art/arcane/iris/builtin/MatterMantle.java deleted file mode 100644 index 4797970ea..000000000 --- a/src/main/java/art/arcane/iris/builtin/MatterMantle.java +++ /dev/null @@ -1,45 +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.builtin; - -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; - -/** - * Iris's mantle as the matter slices it stores, for the built-ins whose data the platform and the rest of Iris read as - * slices rather than through a {@link com.volmit.mantle.MantleLayer}: caves ({@code MatterCavern}) and markers. The - * slices are VolmLib's own types, which a pack module may use as well. Iris offers it as an extension of its mantle and - * chunk invocations: {@code context.extension(MatterMantle.class)}. - * - *

A chunk invocation's matter mantle holds its own chunk only, which the stage may write, as a chunk stage writes the - * mantle of its own chunk; it reads its neighbours through {@link #loadedChunk} alone. - * - *

Heights are as the mantle stores them: above the dimension's bottom. A chunk the invocation reaches is pinned for - * as long as the invocation runs; callers neither release it nor keep it afterwards. - */ -public interface MatterMantle { - /** The mantle chunk at chunk coordinates {@code chunkX}, {@code chunkZ}, or null outside what the invocation reaches. */ - MantleChunk chunk(int chunkX, int chunkZ); - - /** - * The mantle chunk at those coordinates if the world holds it in memory, wherever it is, or null. It is never loaded - * or created for the call and not pinned, so read it at once and do not keep it. - */ - MantleChunk loadedChunk(int chunkX, int chunkZ); -} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java b/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java index a9e964f2e..82a1468f9 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CarveOrphanSweep.java @@ -18,11 +18,9 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import java.util.Arrays; @@ -31,7 +29,6 @@ public final class CarveOrphanSweep { private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; private static final int BAND_FLOOR_MARGIN = 4; private static final int MAX_ORPHAN_CELLS = 16; - private static final MatterCavern ORPHAN_CAVERN = new MatterCavern(true, "", (byte) 0); private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(SweepScratch::new); public interface CarveAccess { @@ -42,34 +39,24 @@ public final class CarveOrphanSweep { default boolean isProtected(int localX, int y, int localZ) { return false; } - - /** - * Cheap pre-check: may any block in [minY, maxY] be carved at all? Default true keeps - * every implementor correct; the mantle-backed access answers from section slice - * presence so an uncarved chunk skips the full band fill + scan. - */ - default boolean mayContainCarvedCells(int minY, int maxY) { - return true; - } } private CarveOrphanSweep() { } + /** Sweeps the chunk whose first block is {@code originX}, {@code originZ}. */ static int sweepChunk( - MantleChunk chunk, + MantleLayer voids, + int originX, + int originZ, int[] surfaceHeights, int maxSurfaceBreakDepth, int worldCeilingY, int[] surfaceFluidBoundaryStartY, int fluidHeight ) { - if (chunk == null) { - return 0; - } - return sweep(surfaceHeights, maxSurfaceBreakDepth, 0, worldCeilingY, - new MantleCarveAccess(chunk, surfaceFluidBoundaryStartY, fluidHeight)); + new MantleCarveAccess(voids, originX, originZ, surfaceFluidBoundaryStartY, fluidHeight)); } public static int sweep(int[] surfaceHeights, int maxSurfaceBreakDepth, int worldFloorY, int worldCeilingY, CarveAccess access) { @@ -95,12 +82,6 @@ public final class CarveOrphanSweep { return 0; } - if (!access.mayContainCarvedCells(bandFloor, bandTop)) { - // Same early return the carvedPresent check reaches, without zero-filling and - // scanning the whole band first. - return 0; - } - int bandHeight = bandTop - bandFloor + 1; int cellCount = bandHeight * CHUNK_AREA; SweepScratch scratch = SCRATCH.get(); @@ -228,34 +209,28 @@ public final class CarveOrphanSweep { } private static final class MantleCarveAccess implements CarveAccess { - private final MantleChunk chunk; + private final MantleLayer voids; + private final int originX; + private final int originZ; private final int[] surfaceFluidBoundaryStartY; private final int fluidHeight; - private MatterSlice cachedSlice; - private int cachedSectionIndex = -1; - private MantleCarveAccess(MantleChunk chunk, int[] surfaceFluidBoundaryStartY, int fluidHeight) { - this.chunk = chunk; + private MantleCarveAccess(MantleLayer voids, int originX, int originZ, int[] surfaceFluidBoundaryStartY, int fluidHeight) { + this.voids = voids; + this.originX = originX; + this.originZ = originZ; this.surfaceFluidBoundaryStartY = surfaceFluidBoundaryStartY; this.fluidHeight = fluidHeight; } @Override public boolean isCarved(int localX, int y, int localZ) { - MatterSlice cavernSlice = resolveSlice(y >> 4); - if (cavernSlice == null) { - return false; - } - - MatterCavern cavern = cavernSlice.get(localX, y & 15, localZ); - return cavern != null && cavern.isCavern(); + return voids.get(originX + localX, y, originZ + localZ) != null; } @Override public void markCarved(int localX, int y, int localZ) { - chunk.getOrCreate(y >> 4).slice(MatterCavern.class).set(localX, y & 15, localZ, ORPHAN_CAVERN); - cachedSectionIndex = -1; - cachedSlice = null; + voids.set(originX + localX, y, originZ + localZ, CarvedVoid.OPEN); } @Override @@ -263,30 +238,6 @@ public final class CarveOrphanSweep { int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); return SurfaceFluidBoundaryPlan.protects(surfaceFluidBoundaryStartY, columnIndex, y, fluidHeight); } - - @Override - public boolean mayContainCarvedCells(int minY, int maxY) { - int minSection = Math.max(0, minY >> 4); - int maxSection = Math.min(chunk.sectionCount() - 1, maxY >> 4); - for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { - Matter section = chunk.get(sectionIndex); - if (section != null && section.getSlice(MatterCavern.class) != null) { - return true; - } - } - return false; - } - - private MatterSlice resolveSlice(int sectionIndex) { - if (sectionIndex == cachedSectionIndex) { - return cachedSlice; - } - - Matter section = sectionIndex >= 0 && sectionIndex < chunk.sectionCount() ? chunk.get(sectionIndex) : null; - cachedSlice = section == null ? null : section.getSlice(MatterCavern.class); - cachedSectionIndex = sectionIndex; - return cachedSlice; - } } private static final class SweepScratch { diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java index 6c78f1538..babf46536 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveAnchors.java @@ -20,9 +20,9 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.carve.CaveAnchorMode; import art.arcane.iris.modules.objects.CarvedSpace; -import art.arcane.iris.modules.objects.Cavern; import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.math.RNG; +import com.volmit.mantle.CarvedVoid; import com.volmit.resource.ResourceId; import com.volmit.world.BiomeSample; import com.volmit.world.TerrainSampler; @@ -76,7 +76,7 @@ final class CaveAnchors { int candidateY = anchorY(rng, candidateX, candidateZ, search); if (candidateY < 0 || biomeConflicts(candidateX, candidateY, candidateZ, expectedCaveBiome) - || !acceptsFluid(underwater, carved.cavernAt(candidateX, candidateY, candidateZ), candidateY, caveLavaHeight)) { + || !acceptsFluid(underwater, carved.voidAt(candidateX, candidateY, candidateZ), candidateY, caveLavaHeight)) { continue; } return new Anchor(candidateX, candidateY, candidateZ); @@ -84,14 +84,14 @@ final class CaveAnchors { return null; } - static boolean acceptsFluid(boolean underwater, Optional cavern, int y, int lavaHeight) { - if (cavern.isEmpty()) { + static boolean acceptsFluid(boolean underwater, Optional carvedVoid, int y, int lavaHeight) { + if (carvedVoid.isEmpty()) { return false; } - if (underwater || cavern.get().liquid() == Cavern.FORCED_AIR_LIQUID) { + if (underwater || carvedVoid.get().fill() == CarvedVoid.Fill.AIR) { return true; } - return cavern.get().air() && y > lavaHeight; + return carvedVoid.get().fill() == CarvedVoid.Fill.OPEN && y > lavaHeight; } /** One above the highest height an anchor may sit at, or 0 when none may. */ diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java index 912663a19..80042c2a7 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarveScratch.java @@ -18,9 +18,7 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; +import com.volmit.mantle.CarvedVoid; final class CaveCarveScratch { final int[] columnMaxY = new int[256]; @@ -64,9 +62,7 @@ final class CaveCarveScratch { int activeModuleCount; double[] verticalEdgeFade = new double[0]; double[] surfaceClosureThreshold = new double[0]; - MatterCavern[] matterByY = new MatterCavern[0]; - Matter[] sectionMatter = new Matter[0]; - MatterSlice[] sectionSlices = new MatterSlice[0]; + CarvedVoid[] voidByY = new CarvedVoid[0]; int adaptiveGeometryStep = -1; int adaptiveGeometryAxisCells = -1; boolean fullWeightsInitialized; diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java index 8ab9da2b0..9054e62e2 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveCarving.java @@ -18,13 +18,14 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.modules.carve.CaveProfile; import art.arcane.iris.engine.object.terrain.carving.CarvingResolver; import art.arcane.iris.engine.object.terrain.carving.DeclaredCaveProfiles; import art.arcane.iris.engine.object.terrain.carving.ResolvedCarvingEntry; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import com.volmit.config.Range; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import com.volmit.resource.ResourceId; import com.volmit.world.BiomeSample; import com.volmit.world.PackBiome; @@ -94,8 +95,8 @@ public class CaveCarving { this.upperDimensionCarving = upperDimensionCarving; } - /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code mantle}, reading the terrain around it from {@code terrain}. */ - public void carve(MatterMantle mantle, TerrainSampler terrain, int x, int z) { + /** Carves the caves of the chunk at chunk coordinates {@code x}, {@code z} into {@code voids}, reading the terrain around it from {@code terrain}. */ + public void carve(MantleLayer voids, TerrainSampler terrain, int x, int z) { BlendScratch blendScratch = BLEND_SCRATCH.get(); int[] chunkSurfaceHeights = prepareChunkSurfaceHeights(x, z, terrain, blendScratch.chunkSurfaceHeights); List weightedProfiles = resolveWeightedProfiles(x, z, terrain); @@ -112,17 +113,19 @@ public class CaveCarving { ); CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); for (WeightedProfile weightedProfile : weightedProfiles) { - carveProfile(weightedProfile, mantle, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); + carveProfile(weightedProfile, voids, x, z, chunkSurfaceHeights, surfaceFluidBoundaryStartY, fluidSupportPlan); } if (upperDimensionCarving && hasUpperDimension(terrain, x, z)) { - carveUpperTerrain(terrain, weightedProfiles, mantle, x, z, fluidSupportPlan); + carveUpperTerrain(terrain, weightedProfiles, voids, x, z, fluidSupportPlan); } - fluidSupportPlan.resolve(mantle.chunk(x, z)); + fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(x), PowerOfTwoCoordinates.chunkToBlock(z), world.height()); if (!weightedProfiles.isEmpty()) { CarveOrphanSweep.sweepChunk( - mantle.chunk(x, z), + voids, + PowerOfTwoCoordinates.chunkToBlock(x), + PowerOfTwoCoordinates.chunkToBlock(z), chunkSurfaceHeights, maxSurfaceBreakDepth(weightedProfiles), world.height() - 1, @@ -144,16 +147,16 @@ public class CaveCarving { return maxDepth; } - private void carveProfile(WeightedProfile weightedProfile, MatterMantle mantle, int cx, int cz, + private void carveProfile(WeightedProfile weightedProfile, MantleLayer voids, int cx, int cz, int[] chunkSurfaceHeights, int[] surfaceFluidBoundaryStartY, CaveFluidSupportPlan fluidSupportPlan) { IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, weightedProfile.worldYRange, chunkSurfaceHeights, surfaceFluidBoundaryStartY, null, fluidSupportPlan); } private void carveUpperTerrain(TerrainSampler terrain, List normalProfiles, - MatterMantle mantle, int cx, int cz, + MantleLayer voids, int cx, int cz, CaveFluidSupportPlan fluidSupportPlan) { int chunkHeight = world.height(); int worldMinHeight = world.minHeight(); @@ -198,7 +201,7 @@ public class CaveCarving { constrainedRange = upperYRange; } IrisCaveCarver3D carver = getCarver(weightedProfile.profile); - carver.carve(mantle, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, + carver.carve(voids, cx, cz, weightedProfile.columnWeights, MIN_WEIGHT, THRESHOLD_PENALTY, constrainedRange, ceilingSurfaceHeights, null, fullVerticalRange, fluidSupportPlan); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java new file mode 100644 index 000000000..201d4c7eb --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFloorMarking.java @@ -0,0 +1,120 @@ +/* + * 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.volmlib.util.math.PowerOfTwoCoordinates; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementTerrain; +import com.volmit.world.TerrainSampler; + +import java.util.BitSet; + +/** + * Marks the floors of the caves {@link CaveCarving} planned in a chunk, which the host's cave spawning reads: the lowest + * block of each vertical run of at least three carved blocks, one floor in sixteen. The runs are those the chunk stage + * cuts, minus the blocks it leaves alone: under a dimension stacked above that carving does not go through, and open voids + * the terrain holds fluid in. The roll is seed-derived and keyed by position alone, never random, because the markers + * persist in the mantle: the same seed marks the same floors on every run. + */ +public final class CaveFloorMarking { + static final String CAVE_FLOOR_MARKER = "cave_floor"; + private static final int CHUNK_SIZE = 16; + private static final int CHUNK_AREA = CHUNK_SIZE * CHUNK_SIZE; + private static final int MIN_RUN_LENGTH = 3; + private static final long FLOOR_MARKER_SALT = 0xC2B2AE3D27D4EB4FL; + private static final long ROLL_MASK = 15L; + private static final ThreadLocal COLUMNS = ThreadLocal.withInitial(() -> { + BitSet[] columns = new BitSet[CHUNK_AREA]; + for (int index = 0; index < CHUNK_AREA; index++) { + columns[index] = new BitSet(); + } + return columns; + }); + + private final CarveWorld world; + private final boolean upperDimensionCarving; + + public CaveFloorMarking(CarveWorld world, boolean upperDimensionCarving) { + this.world = world; + this.upperDimensionCarving = upperDimensionCarving; + } + + /** Marks the floors of the chunk at chunk coordinates {@code chunkX}, {@code chunkZ} in {@code placement}. */ + public void mark(MantleLayer voids, TerrainSampler terrain, PlacementTerrain placement, int chunkX, int chunkZ) { + int originX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + int originZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + BitSet[] carvedColumns = COLUMNS.get(); + fillCarvedColumns(carvedColumns, voids, terrain, originX, originZ); + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + markColumn(carvedColumns[columnIndex], placement, originX + PowerOfTwoCoordinates.unpackLocal16X(columnIndex), + originZ + (columnIndex & (CHUNK_SIZE - 1))); + } + } + + private void fillCarvedColumns(BitSet[] carvedColumns, MantleLayer voids, TerrainSampler terrain, int originX, int originZ) { + int[] surfaceHeights = new int[CHUNK_AREA]; + int[] upperSurfaceHeights = upperDimensionCarving || terrain.upperDimensionY(originX, originZ).isEmpty() ? null : new int[CHUNK_AREA]; + for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { + carvedColumns[columnIndex].clear(); + int worldX = originX + PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int worldZ = originZ + (columnIndex & (CHUNK_SIZE - 1)); + surfaceHeights[columnIndex] = terrain.surfaceHeight(worldX, worldZ); + if (upperSurfaceHeights != null) { + upperSurfaceHeights[columnIndex] = terrain.upperDimensionY(worldX, worldZ).getAsInt(); + } + } + + int fluidHeight = terrain.fluidHeight(); + voids.visit(new BlockBox(originX, 0, originZ, originX + CHUNK_SIZE, world.height(), originZ + CHUNK_SIZE), (x, y, z, carvedVoid) -> { + int columnIndex = PowerOfTwoCoordinates.packLocal16(x - originX, z - originZ); + if (y <= 0 || upperSurfaceHeights != null && y >= upperSurfaceHeights[columnIndex]) { + return; + } + boolean terrainHoldsFluid = y > surfaceHeights[columnIndex] && y <= fluidHeight; + if (carvedVoid.fill() == CarvedVoid.Fill.OPEN && terrainHoldsFluid) { + return; + } + carvedColumns[columnIndex].set(y); + }); + } + + private void markColumn(BitSet carvedColumn, PlacementTerrain placement, int worldX, int worldZ) { + int floor = carvedColumn.nextSetBit(0); + while (floor >= 0) { + int ceiling = carvedColumn.nextClearBit(floor) - 1; + if (ceiling - floor + 1 >= MIN_RUN_LENGTH && floorRoll(worldX, floor, worldZ)) { + placement.mark(new PlacedMarker.PackMarker(new BlockPosition(worldX, floor, worldZ), CAVE_FLOOR_MARKER)); + } + floor = carvedColumn.nextSetBit(ceiling + 1); + } + } + + /** One in sixteen, from a SplitMix64 finalizer over the carve seed, the position and a salt. */ + private boolean floorRoll(int x, int y, int z) { + long hash = (world.carveSeed() + FLOOR_MARKER_SALT) ^ art.arcane.volmlib.util.math.BlockPosition.toLong(x, y, z); + hash = (hash ^ (hash >>> 30)) * 0xBF58476D1CE4E5B9L; + hash = (hash ^ (hash >>> 27)) * 0x94D049BB133111EBL; + hash ^= hash >>> 31; + return (hash & ROLL_MASK) == 0L; + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java index ca98541ed..da3cebfad 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/CaveFluidSupportPlan.java @@ -1,6 +1,6 @@ /* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) + * 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 @@ -18,103 +18,73 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import java.util.BitSet; -import java.util.IdentityHashMap; -import java.util.Map; +/** The fluid voids a carver planned in one chunk, to be drained back to open voids where no solid cup holds them. */ final class CaveFluidSupportPlan { - private final IdentityHashMap groups = new IdentityHashMap<>(); + private static final int MIN_SUPPORTED_NEIGHBOURS = 4; + private static final int CHUNK_WIDTH = 16; + private static final int COLUMN_BITS = 8; + private static final int COLUMN_MASK = (1 << COLUMN_BITS) - 1; - void add(int localX, int y, int localZ, MatterCavern fluid, MatterCavern air) { - FluidCandidateGroup group = groups.computeIfAbsent(fluid, key -> new FluidCandidateGroup(fluid, air)); + private final BitSet fluidPositions = new BitSet(); + + void add(int localX, int y, int localZ) { int columnIndex = PowerOfTwoCoordinates.packLocal16(localX, localZ); - group.positions.set((y << 8) | columnIndex); + fluidPositions.set((y << COLUMN_BITS) | columnIndex); } - void resolve(MantleChunk chunk) { - if (chunk == null) { - groups.clear(); - return; - } - - for (Map.Entry entry : groups.entrySet()) { - FluidCandidateGroup group = entry.getValue(); - for (int position = group.positions.nextSetBit(0); position >= 0; position = group.positions.nextSetBit(position + 1)) { - int y = position >>> 8; - int columnIndex = position & 255; - int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); - int localZ = columnIndex & 15; - MatterCavern current = getCavern(chunk, localX, y, localZ); - if (current != group.fluid || hasCupSupport(chunk, localX, y, localZ)) { - continue; - } - - Matter section = chunk.get(y >> 4); - MatterSlice cavernSlice = section.getSlice(MatterCavern.class); - cavernSlice.set(localX, y & 15, localZ, group.air); + /** Turns every planned fluid void of the chunk at block origin {@code originX}, {@code originZ} that is no longer fluid or has no cup under it into an open void. */ + void resolve(MantleLayer voids, int originX, int originZ, int worldHeight) { + for (int position = fluidPositions.nextSetBit(0); position >= 0; position = fluidPositions.nextSetBit(position + 1)) { + int y = position >>> COLUMN_BITS; + int columnIndex = position & COLUMN_MASK; + int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); + int localZ = columnIndex & (CHUNK_WIDTH - 1); + int x = originX + localX; + int z = originZ + localZ; + if (voids.get(x, y, z) != CarvedVoid.FLUID || hasCupSupport(voids, originX, originZ, localX, y, localZ, worldHeight)) { + continue; } + voids.set(x, y, z, CarvedVoid.OPEN); } - groups.clear(); + fluidPositions.clear(); } - private static boolean hasCupSupport(MantleChunk chunk, int localX, int y, int localZ) { - if (localX <= 0 || localX >= 15 || localZ <= 0 || localZ >= 15 - || y <= 1 || !isSolid(chunk, localX, y - 1, localZ) - || !isSolid(chunk, localX, y - 2, localZ)) { + private static boolean hasCupSupport(MantleLayer voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) { + if (localX <= 0 || localX >= CHUNK_WIDTH - 1 || localZ <= 0 || localZ >= CHUNK_WIDTH - 1 + || y <= 1 || !isSolid(voids, originX, originZ, localX, y - 1, localZ, worldHeight) + || !isSolid(voids, originX, originZ, localX, y - 2, localZ, worldHeight)) { return false; } int support = 0; - if (isSolid(chunk, localX + 1, y, localZ)) { + if (isSolid(voids, originX, originZ, localX + 1, y, localZ, worldHeight)) { support++; } - if (isSolid(chunk, localX - 1, y, localZ)) { + if (isSolid(voids, originX, originZ, localX - 1, y, localZ, worldHeight)) { support++; } - if (isSolid(chunk, localX, y, localZ + 1)) { + if (isSolid(voids, originX, originZ, localX, y, localZ + 1, worldHeight)) { support++; } - if (isSolid(chunk, localX, y, localZ - 1)) { + if (isSolid(voids, originX, originZ, localX, y, localZ - 1, worldHeight)) { support++; } - if (isSolid(chunk, localX, y + 1, localZ)) { + if (isSolid(voids, originX, originZ, localX, y + 1, localZ, worldHeight)) { support++; } - return support >= 4; + return support >= MIN_SUPPORTED_NEIGHBOURS; } - private static boolean isSolid(MantleChunk chunk, int localX, int y, int localZ) { - if (localX < 0 || localX >= 16 || localZ < 0 || localZ >= 16) { + private static boolean isSolid(MantleLayer voids, int originX, int originZ, int localX, int y, int localZ, int worldHeight) { + if (localX < 0 || localX >= CHUNK_WIDTH || localZ < 0 || localZ >= CHUNK_WIDTH) { return false; } - MatterCavern cavern = getCavern(chunk, localX, y, localZ); - return cavern == null || !cavern.isCavern(); - } - - private static MatterCavern getCavern(MantleChunk chunk, int localX, int y, int localZ) { - Matter section = chunk.get(y >> 4); - if (section == null) { - return null; - } - - MatterSlice cavernSlice = section.getSlice(MatterCavern.class); - return cavernSlice == null ? null : cavernSlice.get(localX, y & 15, localZ); - } - - private static final class FluidCandidateGroup { - private final MatterCavern fluid; - private final MatterCavern air; - private final BitSet positions = new BitSet(); - - private FluidCandidateGroup(MatterCavern fluid, MatterCavern air) { - this.fluid = fluid; - this.air = air; - } + return y >= worldHeight || voids.get(originX + localX, y, originZ + localZ) == null; } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java index a2c5b881f..f59d5e366 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/IrisCaveCarver3D.java @@ -18,16 +18,13 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.carve.CaveFieldModule; import art.arcane.iris.modules.carve.CaveProfile; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.M; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterSlice; import com.volmit.config.Range; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import com.volmit.noise.NoiseSampler; import com.volmit.noise.NoiseStyle; import com.volmit.noise.StyledRange; @@ -37,10 +34,7 @@ import java.util.Arrays; import java.util.List; public class IrisCaveCarver3D { - private static final byte LIQUID_AIR = 0; - private static final byte LIQUID_FLUID = 1; - private static final byte LIQUID_LAVA = 2; - private static final byte LIQUID_FORCED_AIR = 3; + private static final int LOCAL_MASK = 15; private static final int ADAPTIVE_MIN_PLANE_COLUMNS = 16; private static final int ADAPTIVE_DEEP_SAMPLE_STEP = 8; private static final double ADAPTIVE_LOCAL_RANGE_SCALE = 0.125D; @@ -57,10 +51,6 @@ public class IrisCaveCarver3D { private final int lavaHeight; private final CaveFieldModuleState[] modules; private final double inverseNormalization; - private final MatterCavern carveAir; - private final MatterCavern carveFluid; - private final MatterCavern carveLava; - private final MatterCavern carveForcedAir; private final double normalizationFactor; private final double baseWeight; private final double detailWeight; @@ -81,10 +71,6 @@ public class IrisCaveCarver3D { public IrisCaveCarver3D(CarveWorld world, CaveProfile profile) { this.profile = profile; - this.carveAir = new MatterCavern(true, "", LIQUID_AIR); - this.carveFluid = new MatterCavern(true, "", LIQUID_FLUID); - this.carveLava = new MatterCavern(true, "", LIQUID_LAVA); - this.carveForcedAir = new MatterCavern(true, "", LIQUID_FORCED_AIR); List moduleStates = new ArrayList<>(); long carveSeed = world.carveSeed(); @@ -127,7 +113,7 @@ public class IrisCaveCarver3D { } public int carve( - MatterMantle mantle, + MantleLayer voids, int chunkX, int chunkZ, double[] columnWeights, @@ -136,11 +122,11 @@ public class IrisCaveCarver3D { Range worldYRange, int[] surfaceHeights ) { - return carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null); + return carve(voids, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null); } public int carve( - MatterMantle mantle, + MantleLayer voids, int chunkX, int chunkZ, double[] columnWeights, @@ -151,15 +137,15 @@ public class IrisCaveCarver3D { Range overrideVerticalRange ) { CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan(); - int carved = carve(mantle, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, + int carved = carve(voids, chunkX, chunkZ, columnWeights, minWeight, thresholdPenalty, worldYRange, surfaceHeights, null, overrideVerticalRange, fluidSupportPlan); - fluidSupportPlan.resolve(mantle.chunk(chunkX, chunkZ)); + fluidSupportPlan.resolve(voids, PowerOfTwoCoordinates.chunkToBlock(chunkX), PowerOfTwoCoordinates.chunkToBlock(chunkZ), worldHeight); return carved; } /** {@code surfaceHeights} are the rounded heights of the chunk's columns, packed as {@link PowerOfTwoCoordinates#packLocal16}. */ int carve( - MatterMantle mantle, + MantleLayer voids, int chunkX, int chunkZ, double[] columnWeights, @@ -205,11 +191,6 @@ public class IrisCaveCarver3D { return 0; } - MantleChunk chunk = mantle.chunk(chunkX, chunkZ); - if (chunk == null) { - return 0; - } - int x0 = PowerOfTwoCoordinates.chunkToBlock(chunkX); int z0 = PowerOfTwoCoordinates.chunkToBlock(chunkZ); int[] columnMaxY = scratch.columnMaxY; @@ -221,8 +202,7 @@ public class IrisCaveCarver3D { double[] clampedWeights = scratch.clampedColumnWeights; double[] verticalEdgeFade = prepareVerticalEdgeFadeTable(scratch, minY, maxY); prepareSurfaceClosureThresholdTable(scratch, minY, maxY); - MatterCavern[] matterByY = prepareMatterByYTable(scratch, minY, maxY); - prepareSectionCaches(scratch, minY, maxY); + CarvedVoid[] voidByY = prepareVoidByYTable(scratch, minY, maxY); // The threshold noise is constant for the carver, so it is built once (in the constructor) and the // min==max / flat-style short circuits are decided here, as Iris's styled range has always decided them. @@ -273,7 +253,7 @@ public class IrisCaveCarver3D { if (exactSampling) { if (adaptiveSampling) { carved = carvePassAdaptive( - chunk, + voids, x0, z0, minY, @@ -289,7 +269,7 @@ public class IrisCaveCarver3D { columnThreshold, clampedWeights, verticalEdgeFade, - matterByY, + voidByY, fluidRequiresFloor ? fluidSupportPlan : null, resolvedMinWeight, resolvedThresholdPenalty, @@ -298,7 +278,7 @@ public class IrisCaveCarver3D { ); } else { carved = carvePassExact( - chunk, + voids, x0, z0, minY, @@ -312,7 +292,7 @@ public class IrisCaveCarver3D { columnThreshold, clampedWeights, verticalEdgeFade, - matterByY, + voidByY, fluidRequiresFloor ? fluidSupportPlan : null, resolvedMinWeight, resolvedThresholdPenalty, @@ -323,7 +303,7 @@ public class IrisCaveCarver3D { } else { int latticeStep = sampleStep; carved = carvePassLattice( - chunk, + voids, x0, z0, minY, @@ -338,7 +318,7 @@ public class IrisCaveCarver3D { columnThreshold, clampedWeights, verticalEdgeFade, - matterByY, + voidByY, fluidRequiresFloor ? fluidSupportPlan : null, resolvedMinWeight, resolvedThresholdPenalty, @@ -347,7 +327,7 @@ public class IrisCaveCarver3D { ); if (carved == 0 && hasFallbackCandidates(columnMaxY, clampedWeights, minY, resolvedMinWeight)) { carved += carvePassFallback( - chunk, + voids, x0, z0, minY, @@ -362,7 +342,7 @@ public class IrisCaveCarver3D { columnThreshold, clampedWeights, verticalEdgeFade, - matterByY, + voidByY, fluidRequiresFloor ? fluidSupportPlan : null, resolvedMinWeight, resolvedThresholdPenalty, @@ -376,7 +356,7 @@ public class IrisCaveCarver3D { } private int carvePassExact( - MantleChunk chunk, + MantleLayer voids, int x0, int z0, int minY, @@ -390,7 +370,7 @@ public class IrisCaveCarver3D { double[] columnThreshold, double[] clampedWeights, double[] verticalEdgeFade, - MatterCavern[] matterByY, + CarvedVoid[] voidByY, CaveFluidSupportPlan fluidSupportPlan, double minWeight, double thresholdPenalty, @@ -430,7 +410,6 @@ public class IrisCaveCarver3D { for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); for (int y = sectionMinY; y <= sectionMaxY; y++) { int planeCount = 0; @@ -460,8 +439,7 @@ public class IrisCaveCarver3D { classifyDensityPlane(scratch, x0, z0, y, planeColumnIndices, planeThresholdLimit, planeCount, planeCarve); int fadeIndex = y - minY; - int localY = y & 15; - MatterCavern verticalMatter = matterByY[fadeIndex]; + CarvedVoid verticalVoid = voidByY[fadeIndex]; if (skipExistingCarved) { for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { @@ -472,14 +450,14 @@ public class IrisCaveCarver3D { int columnIndex = planeColumnIndices[planeIndex]; int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int localZ = columnIndex & 15; - if (cavernSlice.get(localX, localY, localZ) != null) { + if (voids.get(x0 + localX, y, z0 + localZ) != null) { continue; } double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, columnIndex, fluidMaxY, localThreshold); - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); carved++; } continue; @@ -494,9 +472,9 @@ public class IrisCaveCarver3D { int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int localZ = columnIndex & 15; double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, columnIndex, fluidMaxY, localThreshold); - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); carved++; } } @@ -506,7 +484,7 @@ public class IrisCaveCarver3D { } private int carvePassAdaptive( - MantleChunk chunk, + MantleLayer voids, int x0, int z0, int minY, @@ -522,7 +500,7 @@ public class IrisCaveCarver3D { double[] columnThreshold, double[] clampedWeights, double[] verticalEdgeFade, - MatterCavern[] matterByY, + CarvedVoid[] voidByY, CaveFluidSupportPlan fluidSupportPlan, double minWeight, double thresholdPenalty, @@ -568,7 +546,6 @@ public class IrisCaveCarver3D { for (int sectionIndex = minSection; sectionIndex <= maxSection; sectionIndex++) { int sectionMinY = Math.max(minY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex)); int sectionMaxY = Math.min(maxY, PowerOfTwoCoordinates.chunkToBlock(sectionIndex) + 15); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, sectionIndex); for (int y = sectionMinY; y <= sectionMaxY; y++) { int planeCount = 0; @@ -609,8 +586,7 @@ public class IrisCaveCarver3D { effectiveAdaptiveThresholdMargin ); int fadeIndex = y - minY; - int localY = y & 15; - MatterCavern verticalMatter = matterByY[fadeIndex]; + CarvedVoid verticalVoid = voidByY[fadeIndex]; if (skipExistingCarved) { for (int planeIndex = 0; planeIndex < planeCount; planeIndex++) { @@ -621,14 +597,14 @@ public class IrisCaveCarver3D { int columnIndex = planeColumnIndices[planeIndex]; int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int localZ = columnIndex & 15; - if (cavernSlice.get(localX, localY, localZ) != null) { + if (voids.get(x0 + localX, y, z0 + localZ) != null) { continue; } double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, columnIndex, fluidMaxY, localThreshold); - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); carved++; } continue; @@ -643,9 +619,9 @@ public class IrisCaveCarver3D { int localX = PowerOfTwoCoordinates.unpackLocal16X(columnIndex); int localZ = columnIndex & 15; double localThreshold = planeThresholdLimit[planeIndex] * inverseNormalization; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x0 + localX, y, z0 + localZ, + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x0 + localX, y, z0 + localZ, columnIndex, fluidMaxY, localThreshold); - writeCavern(cavernSlice, localX, y, localZ, matter, fluidSupportPlan); + writeVoid(voids, x0 + localX, y, z0 + localZ, carvedVoid, fluidSupportPlan); carved++; } } @@ -667,7 +643,7 @@ public class IrisCaveCarver3D { } private int carvePassLattice( - MantleChunk chunk, + MantleLayer voids, int x0, int z0, int minY, @@ -682,7 +658,7 @@ public class IrisCaveCarver3D { double[] columnThreshold, double[] clampedWeights, double[] verticalEdgeFade, - MatterCavern[] matterByY, + CarvedVoid[] voidByY, CaveFluidSupportPlan fluidSupportPlan, double minWeight, double thresholdPenalty, @@ -768,9 +744,7 @@ public class IrisCaveCarver3D { double density = sampleDensityOptimized(scratch, x, y, z); int stampMaxY = Math.min(maxY, y + 1); for (int yy = y; yy <= stampMaxY; yy++) { - MatterCavern verticalMatter = matterByY[yy - minY]; - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, PowerOfTwoCoordinates.floorDivPow2(yy, 4)); - int localY = yy & 15; + CarvedVoid verticalVoid = voidByY[yy - minY]; int fadeIndex = yy - minY; for (int columnIndex = 0; columnIndex < activeColumns; columnIndex++) { if (yy > tileTopY[columnIndex]) { @@ -795,17 +769,17 @@ public class IrisCaveCarver3D { int localZ = tileLocalZ[columnIndex]; int worldX = x0 + localX; int worldZ = z0 + localZ; - MatterCavern matter = resolveMatter(scratch, verticalMatter, worldX, yy, worldZ, + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, worldX, yy, worldZ, index, fluidMaxY, localThreshold); if (skipExistingCarved) { - if (cavernSlice.get(localX, localY, localZ) == null) { - writeCavern(cavernSlice, localX, yy, localZ, matter, fluidSupportPlan); + if (voids.get(worldX, yy, worldZ) == null) { + writeVoid(voids, worldX, yy, worldZ, carvedVoid, fluidSupportPlan); carved++; } continue; } - writeCavern(cavernSlice, localX, yy, localZ, matter, fluidSupportPlan); + writeVoid(voids, worldX, yy, worldZ, carvedVoid, fluidSupportPlan); carved++; } } @@ -817,7 +791,7 @@ public class IrisCaveCarver3D { } private int carvePassFallback( - MantleChunk chunk, + MantleLayer voids, int x0, int z0, int minY, @@ -832,7 +806,7 @@ public class IrisCaveCarver3D { double[] columnThreshold, double[] clampedWeights, double[] verticalEdgeFade, - MatterCavern[] matterByY, + CarvedVoid[] voidByY, CaveFluidSupportPlan fluidSupportPlan, double minWeight, double thresholdPenalty, @@ -877,20 +851,18 @@ public class IrisCaveCarver3D { if (density > localThreshold) { continue; } - MatterCavern verticalMatter = matterByY[yy - minY]; - MatterCavern matter = resolveMatter(scratch, verticalMatter, x, yy, z, + CarvedVoid verticalVoid = voidByY[yy - minY]; + CarvedVoid carvedVoid = resolveVoid(scratch, verticalVoid, x, yy, z, index, fluidMaxY, localThreshold); - MatterSlice cavernSlice = resolveCavernSlice(scratch, chunk, PowerOfTwoCoordinates.floorDivPow2(yy, 4)); - int localY = yy & 15; if (skipExistingCarved) { - if (cavernSlice.get(lx, localY, lz) == null) { - writeCavern(cavernSlice, lx, yy, lz, matter, fluidSupportPlan); + if (voids.get(x, yy, z) == null) { + writeVoid(voids, x, yy, z, carvedVoid, fluidSupportPlan); carved++; } continue; } - writeCavern(cavernSlice, lx, yy, lz, matter, fluidSupportPlan); + writeVoid(voids, x, yy, z, carvedVoid, fluidSupportPlan); carved++; } } @@ -2111,58 +2083,35 @@ public class IrisCaveCarver3D { return activeCount; } - private MatterSlice resolveCavernSlice(CaveCarveScratch scratch, MantleChunk chunk, int sectionIndex) { - @SuppressWarnings("unchecked") - MatterSlice cachedSlice = (MatterSlice) scratch.sectionSlices[sectionIndex]; - if (cachedSlice != null) { - return cachedSlice; - } - - Matter sectionMatter = scratch.sectionMatter[sectionIndex]; - if (sectionMatter == null) { - sectionMatter = chunk.getOrCreate(sectionIndex); - scratch.sectionMatter[sectionIndex] = sectionMatter; - } - - MatterSlice resolvedSlice = sectionMatter.slice(MatterCavern.class); - scratch.sectionSlices[sectionIndex] = resolvedSlice; - return resolvedSlice; - } - - private MatterCavern[] prepareMatterByYTable(CaveCarveScratch scratch, int minY, int maxY) { + private CarvedVoid[] prepareVoidByYTable(CaveCarveScratch scratch, int minY, int maxY) { int size = Math.max(0, maxY - minY + 1); - if (scratch.matterByY.length < size) { - scratch.matterByY = new MatterCavern[size]; + if (scratch.voidByY.length < size) { + scratch.voidByY = new CarvedVoid[size]; } - MatterCavern[] matterByY = scratch.matterByY; + CarvedVoid[] voidByY = scratch.voidByY; boolean allowLava = profile.allowLava(); for (int y = minY; y <= maxY; y++) { int offset = y - minY; - if (allowLava && y <= lavaHeight) { - matterByY[offset] = carveLava; + if (y > lavaHeight) { + voidByY[offset] = CarvedVoid.OPEN; continue; } - if (!allowLava && y <= lavaHeight) { - matterByY[offset] = carveForcedAir; - continue; - } - - matterByY[offset] = carveAir; + voidByY[offset] = allowLava ? CarvedVoid.LAVA : CarvedVoid.AIR; } - return matterByY; + return voidByY; } - private MatterCavern resolveMatter(CaveCarveScratch scratch, MatterCavern verticalMatter, int x, int y, int z, - int columnIndex, int[] fluidMaxY, double localThreshold) { - if (verticalMatter != carveLava + private CarvedVoid resolveVoid(CaveCarveScratch scratch, CarvedVoid verticalVoid, int x, int y, int z, + int columnIndex, int[] fluidMaxY, double localThreshold) { + if (verticalVoid != CarvedVoid.LAVA && y <= fluidMaxY[columnIndex] && isAquiferCandidate(scratch, x, y, z, localThreshold)) { - return carveFluid; + return CarvedVoid.FLUID; } - return verticalMatter; + return verticalVoid; } private boolean isAquiferCandidate(CaveCarveScratch scratch, int x, int y, int z, double localThreshold) { @@ -2212,27 +2161,10 @@ public class IrisCaveCarver3D { return sampleDensityOptimized(scratch, x, y, z) > threshold; } - private void writeCavern(MatterSlice cavernSlice, int localX, int y, int localZ, - MatterCavern matter, CaveFluidSupportPlan fluidSupportPlan) { - cavernSlice.set(localX, y & 15, localZ, matter); - if (fluidSupportPlan != null && matter == carveFluid) { - fluidSupportPlan.add(localX, y, localZ, carveFluid, carveAir); - } - } - - private void prepareSectionCaches(CaveCarveScratch scratch, int minY, int maxY) { - int minSection = Math.max(0, PowerOfTwoCoordinates.floorDivPow2(minY, 4)); - int maxSection = Math.max(minSection, PowerOfTwoCoordinates.floorDivPow2(maxY, 4)); - int requiredSections = maxSection + 1; - if (scratch.sectionMatter.length < requiredSections) { - scratch.sectionMatter = new Matter[requiredSections]; - scratch.sectionSlices = new MatterSlice[requiredSections]; - return; - } - - for (int section = minSection; section <= maxSection; section++) { - scratch.sectionMatter[section] = null; - scratch.sectionSlices[section] = null; + private void writeVoid(MantleLayer voids, int x, int y, int z, CarvedVoid carvedVoid, CaveFluidSupportPlan fluidSupportPlan) { + voids.set(x, y, z, carvedVoid); + if (fluidSupportPlan != null && carvedVoid == CarvedVoid.FLUID) { + fluidSupportPlan.add(x & LOCAL_MASK, y, z & LOCAL_MASK); } } diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java index 09eb22f83..ce81407be 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/ObjectChunk.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectRun; @@ -62,7 +61,7 @@ final class ObjectChunk { this.world = context.world(); this.terrain = context.placementTerrain(); this.worldHeight = context.terrain().bounds().maxY(); - this.carved = new CarvedSpace(context.extension(MatterMantle.class).orElseThrow(), worldHeight); + this.carved = new CarvedSpace(context.mantle().carved(), context.mantle().bounds()); this.blocks = world.resources().blocks(); this.log = log; } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java index d1db8d7de..79f8808c2 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveModule.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine.modifier; import art.arcane.iris.builtin.IrisSeedPurposes; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.modules.carve.CarvingBiomeSettings; import art.arcane.iris.modules.carve.CarvingEnabledSettings; import art.arcane.iris.modules.carve.CarvingSettings; @@ -31,12 +30,15 @@ import art.arcane.iris.modules.carve.UpperDimensionCarvingSettings; import art.arcane.iris.modules.terrain.TerrainPalettes; import art.arcane.iris.engine.mantle.components.CarveWorld; import art.arcane.iris.engine.mantle.components.CaveCarving; +import art.arcane.iris.engine.mantle.components.CaveFloorMarking; import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; import com.volmit.generation.ChunkContext; import com.volmit.hunk.Hunk; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; @@ -83,14 +85,19 @@ public final class CarveModule implements IrisModule { if (!carves(context)) { return; } - MatterMantle mantle = context.extension(MatterMantle.class).orElseThrow(); - caveCarving(context).carve(mantle, context.terrain(), context.chunkX(), context.chunkZ()); + MantleLayer voids = context.mantle().carved(); + caveCarving(context).carve(voids, context.terrain(), context.chunkX(), context.chunkZ()); + caveFloorMarking(context).mark(voids, context.terrain(), context.placementTerrain(), context.chunkX(), context.chunkZ()); } private static void applyCaves(ChunkStageContext context) { - MatterMantle mantle = context.extension(MatterMantle.class).orElseThrow(); Hunk blocks = context.blocks(); - caveApplying(context).apply(mantle, context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context)); + caveApplying(context).apply(context.mantle().carved(), context.terrain(), context.chunkX(), context.chunkZ(), blocks, CaveDressing.of(context)); + } + + private static CaveFloorMarking caveFloorMarking(ChunkContext context) { + return context.world().state(CaveFloorMarking.class, generating -> new CaveFloorMarking(carveWorld(generating, context.terrain()), + upperDimensionCarving(context))); } private static CaveCarving caveCarving(ChunkContext context) { diff --git a/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java b/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java index 8b036ebc7..18e21c943 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CarveWallBuffer.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.modifier; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; -import art.arcane.volmlib.util.matter.MatterCavern; +import com.volmit.mantle.CarvedVoid; import java.util.Arrays; @@ -28,7 +28,7 @@ final class CarveWallBuffer { private static final double LOAD_FACTOR = 0.75D; private int[] keys; - private MatterCavern[] values; + private CarvedVoid[] values; private int mask; private int resizeAt; private int size; @@ -42,12 +42,12 @@ final class CarveWallBuffer { keys = new int[capacity]; Arrays.fill(keys, EMPTY_KEY); - values = new MatterCavern[capacity]; + values = new CarvedVoid[capacity]; mask = capacity - 1; resizeAt = Math.max(1, (int) (capacity * LOAD_FACTOR)); } - void put(int x, int y, int z, MatterCavern value) { + void put(int x, int y, int z, CarvedVoid value) { int key = pack(x, y, z); int index = mix(key) & mask; @@ -72,7 +72,7 @@ final class CarveWallBuffer { } } - MatterCavern get(int x, int y, int z) { + CarvedVoid get(int x, int y, int z) { int key = pack(x, y, z); int index = mix(key) & mask; while (true) { @@ -94,9 +94,9 @@ final class CarveWallBuffer { continue; } - MatterCavern cavern = values[index]; - if (cavern != null) { - consumer.accept(unpackX(key), unpackY(key), unpackZ(key), cavern); + CarvedVoid carvedVoid = values[index]; + if (carvedVoid != null) { + consumer.accept(unpackX(key), unpackY(key), unpackZ(key), carvedVoid); } } } @@ -109,25 +109,25 @@ final class CarveWallBuffer { private void resize() { int[] oldKeys = keys; - MatterCavern[] oldValues = values; + CarvedVoid[] oldValues = values; int nextCapacity = oldKeys.length << 1; keys = new int[nextCapacity]; Arrays.fill(keys, EMPTY_KEY); - values = new MatterCavern[nextCapacity]; + values = new CarvedVoid[nextCapacity]; mask = nextCapacity - 1; resizeAt = Math.max(1, (int) (nextCapacity * LOAD_FACTOR)); size = 0; for (int index = 0; index < oldKeys.length; index++) { int key = oldKeys[index]; - MatterCavern value = oldValues[index]; + CarvedVoid value = oldValues[index]; if (key != EMPTY_KEY && value != null) { reinsert(key, value); } } } - private void reinsert(int key, MatterCavern value) { + private void reinsert(int key, CarvedVoid value) { int index = mix(key) & mask; while (keys[index] != EMPTY_KEY) { index = (index + 1) & mask; @@ -161,6 +161,6 @@ final class CarveWallBuffer { @FunctionalInterface interface Consumer { - void accept(int x, int y, int z, MatterCavern cavern); + void accept(int x, int y, int z, CarvedVoid carvedVoid); } } diff --git a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java index 9b72022d2..d63226fa8 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java +++ b/src/main/java/art/arcane/iris/engine/modifier/CaveApplying.java @@ -18,20 +18,17 @@ package art.arcane.iris.engine.modifier; -import art.arcane.iris.builtin.MatterMantle; import art.arcane.iris.builtin.decorant.DecorationPart; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.volmlib.util.math.PowerOfTwoCoordinates; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterMarker; -import art.arcane.volmlib.util.matter.slices.MarkerMatter; import art.arcane.iris.engine.mantle.components.CarveWorld; import com.volmit.block.BlockRegistry; import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; import com.volmit.hunk.Hunk; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; @@ -47,18 +44,14 @@ import java.util.Map; * One per world, holding the carve stream's random. */ public class CaveApplying { - private static final byte LIQUID_FLUID = 1; - private static final byte LIQUID_FORCED_AIR = 3; private static final ThreadLocal SCRATCH = ThreadLocal.withInitial(IrisCarveScratch::new); private static final int CAVE_BIOME_BLEND_RADIUS = 3; private static final int CAVE_BIOME_BLEND_CENTER_WEIGHT = 4; private static final int CAVE_BIOME_BLEND_TOTAL_WEIGHT = 8; private static final int CAVE_BIOME_CACHE_SIZE = 2048; + private static final int CHUNK_SIZE = 16; private static final int CHUNK_AREA = 256; private static final int LAYER_DEPTH = 3; - private static final long CEILING_MARKER_SALT = 0x9E3779B97F4A7C15L; - private static final long FLOOR_MARKER_SALT = 0xC2B2AE3D27D4EB4FL; - private static final MatterCavern BASIC_CAVERN = new MatterCavern(true, "", (byte) 0); private final CarveWorld world; private final PackResources resources; @@ -82,27 +75,23 @@ public class CaveApplying { /** * Applies the caves to the chunk at chunk coordinates {@code x}, {@code z}, whose blocks are {@code output}; the caves are in - * {@code mantle}, {@code terrain} gives the heights and cave biomes around the chunk and {@code dressing} what its caves' walls, - * floors and ceilings get. + * {@code voids}, which reads one block beyond the chunk to wall the caves that cross its border, {@code terrain} gives the + * heights and cave biomes around the chunk and {@code dressing} what its caves' walls, floors and ceilings get. */ - public void apply(MatterMantle mantle, TerrainSampler terrain, int x, int z, Hunk output, CaveDressing dressing) { - MantleChunk mantleChunk = mantle.chunk(x, z); - if (mantleChunk == null) { - return; - } - new Application(mantle, mantleChunk, terrain, x, z, output, dressing).run(); + public void apply(MantleLayer voids, TerrainSampler terrain, int x, int z, Hunk output, CaveDressing dressing) { + new Application(voids, terrain, x, z, output, dressing).run(); } - static boolean hasExplicitCarveIntent(MatterCavern cavern) { - return cavern != null && (isFluidIntent(cavern) || cavern.isLava() || cavern.getLiquid() == LIQUID_FORCED_AIR); + static boolean hasExplicitCarveIntent(CarvedVoid carvedVoid) { + return carvedVoid != null && carvedVoid.fill() != CarvedVoid.Fill.OPEN; } - static boolean isFluidIntent(MatterCavern cavern) { - return cavern != null && cavern.getLiquid() == LIQUID_FLUID; + static boolean isFluidIntent(CarvedVoid carvedVoid) { + return carvedVoid != null && carvedVoid.fill() == CarvedVoid.Fill.FLUID; } - static boolean shouldPreserveExistingFluid(MatterCavern cavern, boolean existingIsFluid) { - return existingIsFluid && !hasExplicitCarveIntent(cavern); + static boolean shouldPreserveExistingFluid(CarvedVoid carvedVoid, boolean existingIsFluid) { + return existingIsFluid && !hasExplicitCarveIntent(carvedVoid); } static boolean usesDefaultLava(int caveLavaHeight, int y) { @@ -113,17 +102,16 @@ public class CaveApplying { return surfaceIsOre && !belowIsSolid; } - static BlockState resolveExplicitCarveState(MatterCavern cavern, BlockState fluid, BlockState lava, BlockState air) { - if (cavern == null) { + static BlockState resolveExplicitCarveState(CarvedVoid carvedVoid, BlockState fluid, BlockState lava, BlockState air) { + if (carvedVoid == null) { return null; } - if (isFluidIntent(cavern)) { - return fluid; - } - if (cavern.isLava()) { - return lava; - } - return cavern.getLiquid() == LIQUID_FORCED_AIR ? air : null; + return switch (carvedVoid.fill()) { + case FLUID -> fluid; + case LAVA -> lava; + case AIR -> air; + case OPEN -> null; + }; } static boolean canReplaceCaveFloorLayer(Hunk output, int x, int y, int z, BlockState layer, CaveBlockClasses classes) { @@ -143,24 +131,26 @@ public class CaveApplying { /** One chunk's application: the chunk's blocks, mantle and the caches its passes share. */ final class Application { - private final MatterMantle mantle; - private final MantleChunk mantleChunk; + private final MantleLayer voids; private final TerrainSampler terrain; private final int chunkX; private final int chunkZ; + private final int chunkBlockX; + private final int chunkBlockZ; private final Hunk output; private final CaveDressing dressing; private final CaveBlockClasses classes = new CaveBlockClasses(blocks); private final CaveBiomeCache caveBiomeCache = new CaveBiomeCache(CAVE_BIOME_CACHE_SIZE); private final IrisCarveScratch scratch = SCRATCH.get(); - Application(MatterMantle mantle, MantleChunk mantleChunk, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output, + Application(MantleLayer voids, TerrainSampler terrain, int chunkX, int chunkZ, Hunk output, CaveDressing dressing) { - this.mantle = mantle; - this.mantleChunk = mantleChunk; + this.voids = voids; this.terrain = terrain; this.chunkX = chunkX; this.chunkZ = chunkZ; + this.chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(chunkX); + this.chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); this.output = output; this.dressing = dressing; } @@ -171,9 +161,7 @@ public class CaveApplying { CarveColumnMask[] columnMasks = scratch.columnMasks; CarveColumnMask[] boundaryMasks = scratch.boundaryMasks; int[] surfaceHeights = scratch.surfaceHeights; - Map customBiomeCache = scratch.customBiomeCache; - int chunkBlockX = PowerOfTwoCoordinates.chunkToBlock(chunkX); - int chunkBlockZ = PowerOfTwoCoordinates.chunkToBlock(chunkZ); + Map customBiomeCache = scratch.customBiomeCache; boolean protectUpper = !upperDimensionCarving && terrain.upperDimensionY(chunkBlockX, chunkBlockZ).isPresent(); int[] upperSurfaceHeights = protectUpper ? scratch.getOrCreateUpperSurfaceHeights() : null; for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) { @@ -189,17 +177,14 @@ public class CaveApplying { int worldHeightSpan = world.height(); int caveLavaHeight = world.lavaHeight(); - mantleChunk.iterate(MatterCavern.class, (xx, yy, zz, cavern) -> { - if (cavern == null) { + BlockBox ownColumns = new BlockBox(chunkBlockX, 0, chunkBlockZ, chunkBlockX + CHUNK_SIZE, worldHeightSpan, chunkBlockZ + CHUNK_SIZE); + voids.visit(ownColumns, (xx, yy, zz, carvedVoid) -> { + if (yy <= 0) { return; } - if (yy >= worldHeightSpan || yy <= 0) { - return; - } - - int rx = xx & 15; - int rz = zz & 15; + int rx = xx - chunkBlockX; + int rz = zz - chunkBlockZ; int columnIndex = PowerOfTwoCoordinates.packLocal16(rx, rz); if (upperSurfaceHeights != null && yy >= upperSurfaceHeights[columnIndex]) { @@ -207,15 +192,15 @@ public class CaveApplying { } BlockState current = output.get(rx, yy, rz); - boolean explicitCarveIntent = hasExplicitCarveIntent(cavern); + boolean explicitCarveIntent = hasExplicitCarveIntent(carvedVoid); - if (shouldPreserveExistingFluid(cavern, classes.isFluid(current))) { + if (shouldPreserveExistingFluid(carvedVoid, classes.isFluid(current))) { return; } columnMasks[columnIndex].add(yy); - if (!cavern.getCustomBiome().isEmpty()) { + if (carvedVoid.biome().isPresent()) { scratch.customCaveBiomePresent = true; } @@ -225,8 +210,8 @@ public class CaveApplying { if (explicitCarveIntent) { // Only a fluid cavern consumes the fluid sample, so never take it per voxel. - BlockState fluid = isFluidIntent(cavern) ? dressing.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; - BlockState carved = resolveExplicitCarveState(cavern, fluid, lava, caveAir); + BlockState fluid = isFluidIntent(carvedVoid) ? dressing.fluidAt(chunkBlockX + rx, chunkBlockZ + rz) : null; + BlockState carved = resolveExplicitCarveState(carvedVoid, fluid, lava, caveAir); output.set(rx, yy, rz, carved == null ? plainAir : carved); } else if (usesDefaultLava(caveLavaHeight, yy)) { output.set(rx, yy, rz, lava); @@ -241,13 +226,12 @@ public class CaveApplying { } addCrossChunkBoundaryWalls(walls, boundaryMasks, surfaceHeights); - walls.forEach((rx, yy, rz, cavern) -> { + walls.forEach((rx, yy, rz, carvedVoid) -> { int worldX = rx + chunkBlockX; int worldZ = rz + chunkBlockZ; - String customBiome = cavern.getCustomBiome(); - ResourceId biome = customBiome.isEmpty() + ResourceId biome = carvedVoid.biome().isEmpty() ? resolveCaveBiome(worldX, yy, worldZ) - : resolveCustomBiome(customBiomeCache, customBiome); + : resolveCustomBiome(customBiomeCache, carvedVoid.biome().get()); if (biome != null) { BlockState data = dressing.wall(biome, rng, worldX, yy, worldZ); @@ -304,16 +288,16 @@ public class CaveApplying { int yy = columnMask.nextSetBit(0); while (yy >= 0) { if (rz < 15 && !columnMasks[columnIndex + 1].contains(yy)) { - walls.put(rx, yy, rz + 1, BASIC_CAVERN); + walls.put(rx, yy, rz + 1, CarvedVoid.OPEN); } if (rx < 15 && !columnMasks[columnIndex + 16].contains(yy)) { - walls.put(rx + 1, yy, rz, BASIC_CAVERN); + walls.put(rx + 1, yy, rz, CarvedVoid.OPEN); } if (rz > 0 && !columnMasks[columnIndex - 1].contains(yy)) { - walls.put(rx, yy, rz - 1, BASIC_CAVERN); + walls.put(rx, yy, rz - 1, CarvedVoid.OPEN); } if (rx > 0 && !columnMasks[columnIndex - 16].contains(yy)) { - walls.put(rx - 1, yy, rz, BASIC_CAVERN); + walls.put(rx - 1, yy, rz, CarvedVoid.OPEN); } yy = columnMask.nextSetBit(yy + 1); } @@ -331,19 +315,19 @@ public class CaveApplying { int rz = columnIndex & 15; int yy = columnMask.nextSetBit(0); while (yy >= 0) { - MatterCavern cavern = mantleChunk.get(rx, yy, rz, MatterCavern.class); - if (cavern != null) { - if (rz < 15 && mantleChunk.get(rx, yy, rz + 1, MatterCavern.class) == null) { - walls.put(rx, yy, rz + 1, cavern); + CarvedVoid carvedVoid = ownVoid(rx, yy, rz); + if (carvedVoid != null) { + if (rz < 15 && ownVoid(rx, yy, rz + 1) == null) { + walls.put(rx, yy, rz + 1, carvedVoid); } - if (rx < 15 && mantleChunk.get(rx + 1, yy, rz, MatterCavern.class) == null) { - walls.put(rx + 1, yy, rz, cavern); + if (rx < 15 && ownVoid(rx + 1, yy, rz) == null) { + walls.put(rx + 1, yy, rz, carvedVoid); } - if (rz > 0 && mantleChunk.get(rx, yy, rz - 1, MatterCavern.class) == null) { - walls.put(rx, yy, rz - 1, cavern); + if (rz > 0 && ownVoid(rx, yy, rz - 1) == null) { + walls.put(rx, yy, rz - 1, carvedVoid); } - if (rx > 0 && mantleChunk.get(rx - 1, yy, rz, MatterCavern.class) == null) { - walls.put(rx - 1, yy, rz, cavern); + if (rx > 0 && ownVoid(rx - 1, yy, rz) == null) { + walls.put(rx - 1, yy, rz, carvedVoid); } } yy = columnMask.nextSetBit(yy + 1); @@ -363,39 +347,27 @@ public class CaveApplying { return; } - MantleChunk west = mantle.loadedChunk(chunkX - 1, chunkZ); - MantleChunk east = mantle.loadedChunk(chunkX + 1, chunkZ); - MantleChunk north = mantle.loadedChunk(chunkX, chunkZ - 1); - MantleChunk south = mantle.loadedChunk(chunkX, chunkZ + 1); - if (west == null && east == null && north == null && south == null) { - return; - } - + int westBlockX = chunkBlockX - 1; + int eastBlockX = chunkBlockX + CHUNK_SIZE; + int northBlockZ = chunkBlockZ - 1; + int southBlockZ = chunkBlockZ + CHUNK_SIZE; for (int yy = 1; yy <= maxY; yy++) { - for (int offset = 0; offset < 16; offset++) { - if (west != null) { - tryAddBoundaryWall(west, walls, boundaryMasks, 0, yy, offset, 15, offset); - } - if (east != null) { - tryAddBoundaryWall(east, walls, boundaryMasks, 15, yy, offset, 0, offset); - } - if (north != null) { - tryAddBoundaryWall(north, walls, boundaryMasks, offset, yy, 0, offset, 15); - } - if (south != null) { - tryAddBoundaryWall(south, walls, boundaryMasks, offset, yy, 15, offset, 0); - } + for (int offset = 0; offset < CHUNK_SIZE; offset++) { + tryAddBoundaryWall(walls, boundaryMasks, 0, yy, offset, westBlockX, chunkBlockZ + offset); + tryAddBoundaryWall(walls, boundaryMasks, CHUNK_SIZE - 1, yy, offset, eastBlockX, chunkBlockZ + offset); + tryAddBoundaryWall(walls, boundaryMasks, offset, yy, 0, chunkBlockX + offset, northBlockZ); + tryAddBoundaryWall(walls, boundaryMasks, offset, yy, CHUNK_SIZE - 1, chunkBlockX + offset, southBlockZ); } } } - private void tryAddBoundaryWall(MantleChunk neighborChunk, CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, - int localX, int yy, int localZ, int neighborX, int neighborZ) { - if (mantleChunk.get(localX, yy, localZ, MatterCavern.class) != null) { + private void tryAddBoundaryWall(CarveWallBuffer walls, CarveColumnMask[] boundaryMasks, + int localX, int yy, int localZ, int neighborBlockX, int neighborBlockZ) { + if (ownVoid(localX, yy, localZ) != null) { return; } - MatterCavern neighbor = neighborChunk.get(neighborX, yy, neighborZ, MatterCavern.class); + CarvedVoid neighbor = voids.get(neighborBlockX, yy, neighborBlockZ); if (neighbor == null) { return; } @@ -405,7 +377,7 @@ public class CaveApplying { boundaryMasks[columnIndex].add(yy); } - private void processColumnFromMask(CarveColumnMask columnMask, int columnIndex, Map customBiomeCache) { + private void processColumnFromMask(CarveColumnMask columnMask, int columnIndex, Map customBiomeCache) { if (columnMask == null || columnMask.isEmpty()) { return; } @@ -448,7 +420,7 @@ public class CaveApplying { } private void processBoundaryColumnFromMask(CarveColumnMask boundaryMask, CarveWallBuffer walls, int columnIndex, - Map customBiomeCache) { + Map customBiomeCache) { int firstHeight = boundaryMask.nextSetBit(0); if (firstHeight < 0) { return; @@ -477,7 +449,7 @@ public class CaveApplying { } private void paintBoundaryZone(CarveWallBuffer walls, int rx, int rz, int worldX, int worldZ, int zoneFloor, int zoneCeiling, - Map customBiomeCache) { + Map customBiomeCache) { ResourceId floorBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneFloor, rz), worldX, zoneFloor, worldZ, customBiomeCache); ResourceId ceilingBiome = resolveCaveBoundaryBiome(walls.get(rx, zoneCeiling, rz), worldX, zoneCeiling, worldZ, customBiomeCache); if (floorBiome == null && ceilingBiome == null) { @@ -527,19 +499,7 @@ public class CaveApplying { } } - /** - * 1-in-16 marker roll from a SplitMix64 finalizer over (carve seed, block position, salt). - * Deterministic per seed and position, thread-order independent, allocation free. - */ - private boolean markerRoll(int x, int y, int z, long salt) { - long h = (world.carveSeed() + salt) ^ BlockPosition.toLong(x, y, z); - h = (h ^ (h >>> 30)) * 0xBF58476D1CE4E5B9L; - h = (h ^ (h >>> 27)) * 0x94D049BB133111EBL; - h ^= h >>> 31; - return (h & 15L) == 0L; - } - - private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map customBiomeCache) { + private void processZone(CaveZone zone, int rx, int rz, int xx, int zz, Map customBiomeCache) { int maxY = output.height(); if (zone.ceiling + 1 < maxY && classes.isDecorant(output.get(rx, zone.ceiling + 1, rz))) { @@ -550,17 +510,6 @@ public class CaveApplying { output.set(rx, zone.ceiling, rz, caveAir); } - // Seed-derived and position-keyed, never Math.random(): these markers persist into the - // mantle and drive cave spawning, so the same seed must stamp the same markers on - // every run and every platform. Inline mix, no allocation on this hot path. - if (markerRoll(xx, zone.ceiling, zz, CEILING_MARKER_SALT)) { - setMarker(rx, zone.ceiling, rz, MarkerMatter.CAVE_CEILING); - } - - if (markerRoll(xx, zone.floor, zz, FLOOR_MARKER_SALT)) { - setMarker(rx, zone.floor, rz, MarkerMatter.CAVE_FLOOR); - } - ResourceId floorBiome = resolveCaveBoundaryBiome(rx, zone.floor, rz, xx, zz, customBiomeCache); ResourceId ceilingBiome = resolveCaveBoundaryBiome(rx, zone.ceiling, rz, xx, zz, customBiomeCache); if (floorBiome == null && ceilingBiome == null) { @@ -586,30 +535,21 @@ public class CaveApplying { } } - private void setMarker(int localX, int y, int localZ, MatterMarker marker) { - Matter section = mantleChunk.getOrCreate(y >> 4); - section.slice(MatterMarker.class).set(localX, y & 15, localZ, marker); + ResourceId resolveCaveBoundaryBiome(int x, int y, int z, int worldX, int worldZ, Map customBiomeCache) { + return resolveCaveBoundaryBiome(ownVoid(x, y, z), worldX, y, worldZ, customBiomeCache); } - ResourceId resolveCaveBoundaryBiome(int x, int y, int z, int worldX, int worldZ, Map customBiomeCache) { - return resolveCaveBoundaryBiome(cavernIfPresent(x, y, z), worldX, y, worldZ, customBiomeCache); - } - - private MatterCavern cavernIfPresent(int x, int y, int z) { - int section = y >> 4; - if (y < 0 || !mantleChunk.exists(section)) { + /** The void at a block of this chunk; null where nothing is carved, and above or below the dimension. */ + private CarvedVoid ownVoid(int localX, int y, int localZ) { + if (y < 0 || y >= world.height()) { return null; } - Matter matter = mantleChunk.get(section); - if (matter == null || !matter.hasSlice(MatterCavern.class)) { - return null; - } - return matter.getSlice(MatterCavern.class).get(x & 15, y & 15, z & 15); + return voids.get(chunkBlockX + localX, y, chunkBlockZ + localZ); } - ResourceId resolveCaveBoundaryBiome(MatterCavern cavern, int worldX, int y, int worldZ, Map customBiomeCache) { - if (cavern != null && !cavern.getCustomBiome().isEmpty()) { - return resolveCustomBiome(customBiomeCache, cavern.getCustomBiome()); + ResourceId resolveCaveBoundaryBiome(CarvedVoid carvedVoid, int worldX, int y, int worldZ, Map customBiomeCache) { + if (carvedVoid != null && carvedVoid.biome().isPresent()) { + return resolveCustomBiome(customBiomeCache, carvedVoid.biome().get()); } return resolveCaveBiome(worldX, y, worldZ); } @@ -660,9 +600,8 @@ public class CaveApplying { return resolvedBiome; } - /** The id of the pack's biome with this key; null when the pack has none or it cannot be loaded. */ - private ResourceId existingBiomeId(String key) { - ResourceId id = resources.idOf(key); + /** The pack's biome with this id; null when the pack has none or it cannot be loaded. */ + private ResourceId existingBiomeId(ResourceId id) { try { return resources.find(PackResources.BIOMES, id).isPresent() ? id : null; } catch (IllegalStateException unreadable) { @@ -670,7 +609,7 @@ public class CaveApplying { } } - private ResourceId resolveCustomBiome(Map customBiomeCache, String customBiome) { + private ResourceId resolveCustomBiome(Map customBiomeCache, ResourceId customBiome) { if (customBiomeCache.containsKey(customBiome)) { return customBiomeCache.get(customBiome); } diff --git a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java index 21859bc8a..dc55fbd55 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java +++ b/src/main/java/art/arcane/iris/engine/modifier/IrisCarveScratch.java @@ -28,7 +28,7 @@ final class IrisCarveScratch { final CarveColumnMask[] boundaryMasks = new CarveColumnMask[256]; final int[] surfaceHeights = new int[256]; final CarveWallBuffer walls = new CarveWallBuffer(512); - final Map customBiomeCache = new HashMap<>(); + final Map customBiomeCache = new HashMap<>(); int[] upperSurfaceHeights; boolean customCaveBiomePresent; diff --git a/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java b/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java index a48f2fa49..286f6c075 100644 --- a/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java +++ b/src/main/java/art/arcane/iris/modules/objects/CarvedSpace.java @@ -18,11 +18,9 @@ package art.arcane.iris.modules.objects; -import art.arcane.iris.builtin.MatterMantle; -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.MatterSlice; +import com.volmit.geometry.BlockBox; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import java.util.Optional; @@ -31,84 +29,36 @@ import java.util.Optional; * are above the dimension's bottom; outside the mantle the invocation reaches nothing is carved. */ public final class CarvedSpace { - private static final int CHUNK_SHIFT = 4; - private static final int SECTION_SHIFT = 4; - private static final int SECTION_HEIGHT = 16; - private static final int LOCAL_MASK = 15; - private static final byte CARVED = 1; + private final MantleLayer voids; + private final BlockBox reach; - private final MatterMantle mantle; - private final int worldHeight; - - public CarvedSpace(MatterMantle mantle, int worldHeight) { - this.mantle = mantle; - this.worldHeight = worldHeight; + public CarvedSpace(MantleLayer voids, BlockBox reach) { + this.voids = voids; + this.reach = reach; } /** Whether the position is carved. */ public boolean isCarved(int x, int y, int z) { - return cavernData(x, y, z) != null; + return voidAt(x, y, z).isPresent(); } /** Whether each height from 0 up to {@code height} is carved at the column, 1 for carved and 0 for not. */ public byte[] column(int x, int z, int height) { - int cappedHeight = Math.min(Math.max(height, 0), worldHeight); + int cappedHeight = Math.min(Math.max(height, 0), reach.maxY()); byte[] carvedColumn = new byte[cappedHeight]; - if (cappedHeight <= 0) { - return carvedColumn; - } - MantleChunk chunk = mantle.chunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); - if (chunk == null) { - return carvedColumn; - } - int localX = x & LOCAL_MASK; - int localZ = z & LOCAL_MASK; - int lastSection = (cappedHeight - 1) >> SECTION_SHIFT; - for (int section = 0; section <= lastSection; section++) { - MatterSlice slice = cavernSlice(chunk, section); - if (slice == null) { - continue; - } - int sectionBaseY = section << SECTION_SHIFT; - int sectionMaxY = Math.min(cappedHeight, sectionBaseY + SECTION_HEIGHT); - for (int y = sectionBaseY; y < sectionMaxY; y++) { - if (slice.get(localX, y & LOCAL_MASK, localZ) != null) { - carvedColumn[y] = CARVED; - } + for (int y = 0; y < cappedHeight; y++) { + if (reach.contains(x, y, z) && voids.get(x, y, z) != null) { + carvedColumn[y] = 1; } } return carvedColumn; } /** The void at the position; empty where nothing was carved. */ - public Optional cavernAt(int x, int y, int z) { - MatterCavern cavern = cavernData(x, y, z); - if (cavern == null || !cavern.isCavern()) { + public Optional voidAt(int x, int y, int z) { + if (!reach.contains(x, y, z)) { return Optional.empty(); } - return Optional.of(new Cavern(cavern.isAir(), cavern.getLiquid())); - } - - private MatterCavern cavernData(int x, int y, int z) { - if (y < 0 || y >= worldHeight) { - return null; - } - MantleChunk chunk = mantle.chunk(x >> CHUNK_SHIFT, z >> CHUNK_SHIFT); - if (chunk == null) { - return null; - } - MatterSlice slice = cavernSlice(chunk, y >> SECTION_SHIFT); - return slice == null ? null : slice.get(x & LOCAL_MASK, y & LOCAL_MASK, z & LOCAL_MASK); - } - - private static MatterSlice cavernSlice(MantleChunk chunk, int section) { - if (!chunk.exists(section)) { - return null; - } - Matter matter = chunk.get(section); - if (matter == null || !matter.hasSlice(MatterCavern.class)) { - return null; - } - return matter.getSlice(MatterCavern.class); + return Optional.ofNullable(voids.get(x, y, z)); } } diff --git a/src/main/java/art/arcane/iris/modules/objects/Cavern.java b/src/main/java/art/arcane/iris/modules/objects/Cavern.java deleted file mode 100644 index 032ee8011..000000000 --- a/src/main/java/art/arcane/iris/modules/objects/Cavern.java +++ /dev/null @@ -1,29 +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.modules.objects; - -/** - * A carved void of the mantle, as the cave carver left it. - * - * @param air whether the void holds air - * @param liquid the carver's liquid code for the void; {@link #FORCED_AIR_LIQUID} means air that stays air - */ -public record Cavern(boolean air, byte liquid) { - public static final byte FORCED_AIR_LIQUID = 3; -} From 769a29ce83ea0267f9c3b3c14eb70329bc3f9a21 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 12:54:19 +0100 Subject: [PATCH 135/139] Register the spawn cooldown book as a saved key SpawnModule registers SpawnCooldownBook.SAVED in setup, as the api now requires, and the key uses ResourceId and StorageCodec. --- .../arcane/iris/engine/spawn/SpawnCooldownBook.java | 11 ++++++----- .../art/arcane/iris/engine/spawn/SpawnModule.java | 1 + 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java index 081b4f1bc..6514e19e1 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnCooldownBook.java @@ -19,9 +19,10 @@ package art.arcane.iris.engine.spawn; import art.arcane.volmlib.util.cache.CacheKey; -import com.volmit.data.Codec; +import com.volmit.data.SavedKey; +import com.volmit.data.StorageCodec; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; -import com.volmit.world.SavedKey; import java.io.DataInput; import java.io.DataOutput; @@ -38,7 +39,7 @@ import java.util.function.ToLongFunction; * rates hold across restarts. Spawners count by the key the pack names them by. Safe for concurrent use. */ final class SpawnCooldownBook { - static final SavedKey SAVED = new SavedKey<>("iris:spawn/cooldowns", SpawnCooldownBook.class, + static final SavedKey SAVED = new SavedKey<>(ResourceId.parse("iris:spawn/cooldowns"), SpawnCooldownBook.class, codec(System::currentTimeMillis), () -> new SpawnCooldownBook(System::currentTimeMillis)); private static final int FORMAT_VERSION = 1; @@ -57,7 +58,7 @@ final class SpawnCooldownBook { } /** How {@link #SAVED} is stored: the books read by this codec count time with {@code clockMilliseconds}. */ - static Codec codec(LongSupplier clockMilliseconds) { + static StorageCodec codec(LongSupplier clockMilliseconds) { return new BookCodec(clockMilliseconds); } @@ -111,7 +112,7 @@ final class SpawnCooldownBook { return firedAt == null || clockMilliseconds.getAsLong() - firedAt > intervalMilliseconds; } - private record BookCodec(LongSupplier clockMilliseconds) implements Codec { + private record BookCodec(LongSupplier clockMilliseconds) implements StorageCodec { @Override public int version() { return FORMAT_VERSION; diff --git a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java index dc9174b3a..9aafb7a16 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java +++ b/src/main/java/art/arcane/iris/engine/spawn/SpawnModule.java @@ -47,6 +47,7 @@ public final class SpawnModule implements IrisModule { registry.registerSettings(SpawnerSettings.class); registry.registerSettings(EffectSettings.class); SpawnResources.kinds().forEach(registry::registerResourceKind); + registry.registerSaved(SpawnCooldownBook.SAVED); registry.registerService(EntitySpawns.class, new EntitySpawning()); registry.registerService(AmbientEffects.class, new AmbientEffecting()); } From cd03fb0c0aec6199be76a9c928b9e9125649c8d5 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 12:55:46 +0100 Subject: [PATCH 136/139] Ask the carved layer instead of Mantle.isCarved DepositPlacer tests carved().get(x, y, z) for null, as the api no longer has Mantle.isCarved. --- .../art/arcane/iris/engine/modifier/DepositPlacer.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java index 1fd4657fd..a4f464d2d 100644 --- a/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java +++ b/src/main/java/art/arcane/iris/engine/modifier/DepositPlacer.java @@ -36,7 +36,8 @@ import com.volmit.config.FeatureSettings; import com.volmit.config.Level; import com.volmit.config.SettingsStack; import com.volmit.hunk.Hunk; -import com.volmit.mantle.Mantle; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.MantleLayer; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.stage.ChunkStageContext; @@ -119,7 +120,7 @@ final class DepositPlacer { private final Hunk blocks; private final TerrainSampler terrain; private final FeatureSettings settings; - private final Mantle mantle; + private final MantleLayer carvedVoids; private final int originX; private final int originZ; private final int worldHeight; @@ -134,7 +135,7 @@ final class DepositPlacer { this.blocks = context.blocks(); this.terrain = context.terrain(); this.settings = context.settings(); - this.mantle = context.mantle(); + this.carvedVoids = context.mantle().carved(); this.originX = context.originX(); this.originZ = context.originZ(); this.worldHeight = blocks.height(); @@ -248,7 +249,7 @@ final class DepositPlacer { continue; } - if (!mantle.isCarved(originX + nx, ny, originZ + nz)) { + if (carvedVoids.get(originX + nx, ny, originZ + nz) == null) { BlockState ore = clump.blocks().get(j); BlockState remapped = remapped(nx, ny, nz, ore); BlockState finalBlock = remapped != null From d4704817a54a3957a743ea4ead63290dec5dd2de Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 14:28:49 +0100 Subject: [PATCH 137/139] Point the structure key list at /iris module structure list --- .../art/arcane/iris/builtin/structure/StructureSettings.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java index ac9b13d61..82c13a4de 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java @@ -37,7 +37,7 @@ import java.util.List; * generate are moved and fitted, how often structure sets start, and whether installed data packs may replace the * platform's own definitions. IrisApi types only. */ -@Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris structure list ' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") +@Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris module structure list' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") @Feature(id = "iris:structure", name = "Structures", key = "importedStructures", targets = Level.DIMENSION) public final class StructureSettings implements IrisFeature { @MinItems(1) From 6d18d510763f0d2954f3b57a3990625210c6ea13 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 14:34:26 +0100 Subject: [PATCH 138/139] Drop @MinItems from the options whose empty list means none 70 options carried @MinItems(1) but default to an empty list, and packs write [] for them, such as the cave profile's modules or a decorator's blacklist. Only the three palettes that default to a block keep it: PaletteSpec.palette, PaletteLayer.palette and Decorator.palette. The loader enforces @MinItems now. --- .../art/arcane/iris/builtin/blocks/ObjectReplace.java | 2 -- .../arcane/iris/builtin/decorant/DecorantSettings.java | 2 -- .../java/art/arcane/iris/builtin/decorant/Decorator.java | 3 --- .../java/art/arcane/iris/builtin/loot/LootEntry.java | 5 ----- .../java/art/arcane/iris/builtin/loot/LootTable.java | 2 -- .../java/art/arcane/iris/builtin/loot/ObjectLoot.java | 2 -- .../art/arcane/iris/builtin/loot/ObjectVanillaLoot.java | 2 -- .../art/arcane/iris/builtin/objects/HeightmapNoise.java | 2 -- .../art/arcane/iris/builtin/objects/ObjectPlacement.java | 9 --------- .../art/arcane/iris/builtin/objects/ObjectSettings.java | 2 -- .../art/arcane/iris/builtin/objects/TreeOverride.java | 3 --- .../art/arcane/iris/builtin/spawn/EffectCommands.java | 2 -- .../art/arcane/iris/builtin/spawn/EntityDefinition.java | 4 ---- .../art/arcane/iris/builtin/spawn/PlacementMarker.java | 2 -- .../java/art/arcane/iris/builtin/spawn/SpawnCommand.java | 2 -- .../java/art/arcane/iris/builtin/spawn/SpawnMarker.java | 2 -- src/main/java/art/arcane/iris/builtin/spawn/Spawner.java | 3 --- .../iris/builtin/structure/StructureAdjustment.java | 2 -- .../iris/builtin/structure/StructurePlacement.java | 4 ---- .../builtin/structure/StructurePlacementSettings.java | 2 -- .../arcane/iris/builtin/structure/StructureSettings.java | 5 ----- .../engine/procedural/part/ProceduralDecoration.java | 2 -- .../iris/engine/procedural/part/ProceduralMaterial.java | 2 -- .../iris/engine/procedural/part/ProceduralObject.java | 4 ---- .../iris/engine/procedural/part/ProceduralPart.java | 2 -- .../art/arcane/iris/modules/carve/CarvingSettings.java | 2 -- .../java/art/arcane/iris/modules/carve/CaveProfile.java | 2 -- .../arcane/iris/modules/deposit/DepositGenerator.java | 5 ----- .../iris/modules/deposit/DepositVariantSettings.java | 2 -- .../arcane/iris/modules/floating/FloatingChildBiome.java | 6 ------ .../iris/modules/floating/FloatingChildSettings.java | 2 -- .../java/art/arcane/iris/modules/loot/BlockDrop.java | 3 --- .../art/arcane/iris/modules/loot/BlockDropSettings.java | 2 -- .../art/arcane/iris/modules/spawn/EffectSettings.java | 2 -- .../art/arcane/iris/modules/spawn/SpawnerSettings.java | 2 -- .../art/arcane/iris/modules/terrain/OreSettings.java | 2 -- .../vanillafeatures/ImportedFeaturesSettings.java | 4 ---- 37 files changed, 106 deletions(-) diff --git a/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java b/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java index b93ef154e..bc7fc4a56 100644 --- a/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java +++ b/src/main/java/art/arcane/iris/builtin/blocks/ObjectReplace.java @@ -22,7 +22,6 @@ import com.volmit.block.BlockSpec; import com.volmit.block.PaletteSpec; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -34,7 +33,6 @@ import java.util.List; @Snippet("iris/blocks/object-block-replacer") @Desc("Find and replace object materials") public final class ObjectReplace { - @MinItems(1) @Required @Desc("Find this block") private List find = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java index b83376f62..32a99697e 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/DecorantSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -34,7 +33,6 @@ import java.util.List; @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") @Feature(id = "iris:decorant", name = "Decorators", key = "decorators", root = "decorators", targets = Level.BIOME) public final class DecorantSettings implements IrisFeature { - @MinItems(1) @Desc("Decorators are used for things like tall grass, bisected flowers, and even kelp or cactus (random heights)") private List decorators = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java index 13228e44b..4515ece32 100644 --- a/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java +++ b/src/main/java/art/arcane/iris/builtin/decorant/Decorator.java @@ -52,11 +52,9 @@ public final class Decorator { @Desc("Forced the surface block of this decorant to be the specified block. Assumes forcePlace.") private BlockSpec forceBlock; - @MinItems(1) @Desc("When set, the decorator can only place onto any of these blocks.") private List whitelist; - @MinItems(1) @Desc("When set, the decorator will never place onto any of these blocks.") private List blacklist; @@ -102,7 +100,6 @@ public final class Decorator { @Desc("The palette of blocks to pick from when this decorator needs to place.") private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); - @MinItems(1) @Desc("The palette of blocks used at the very top of a 'stackMax' of higher than 1. For example, bamboo tops.") private List topPalette = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java b/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java index 1f31eed44..bd1649c1a 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootEntry.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.loot; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; @@ -72,19 +71,15 @@ public final class LootEntry { @Desc("Set this to true to prevent it from being broken") private boolean unbreakable = false; - @MinItems(1) @Desc("The item flags to add") private List itemFlags = List.of(); - @MinItems(1) @Desc("Apply enchantments to this item") private List enchantments = List.of(); - @MinItems(1) @Desc("Apply attribute modifiers to this item") private List attributes = List.of(); - @MinItems(1) @Desc("Add lore to this item") private List lore = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/loot/LootTable.java b/src/main/java/art/arcane/iris/builtin/loot/LootTable.java index 5c495b3db..a2ac13151 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/LootTable.java +++ b/src/main/java/art/arcane/iris/builtin/loot/LootTable.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.loot; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; @@ -56,7 +55,6 @@ public final class LootTable { @Desc("The maximum amount of tries to generate loot, from 1 to 256") private int maxTries = 10; - @MinItems(1) @Desc("The loot in this table") private List loot = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java index 25461bbf4..6a869e548 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectLoot.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.loot; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.ResourceRef; @@ -32,7 +31,6 @@ import java.util.List; @Snippet("iris/loot/object-loot") @Desc("Represents loot within this object") public final class ObjectLoot implements ObjectLootEntry { - @MinItems(1) @Desc("The list of blocks this loot table should apply to") private List filter = List.of(); @Desc("Exactly match the block data or not") diff --git a/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java index 5d1db49da..7af357045 100644 --- a/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java +++ b/src/main/java/art/arcane/iris/builtin/loot/ObjectVanillaLoot.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.loot; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; @@ -33,7 +32,6 @@ import java.util.List; @Snippet("iris/loot/object-vanilla-loot") @Desc("Represents vanilla loot within this object") public final class ObjectVanillaLoot implements ObjectLootEntry { - @MinItems(1) @Desc("The list of blocks this loot table should apply to") private List filter = List.of(); @Desc("Exactly match the block data or not") diff --git a/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java b/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java index 5db32494e..c4b7857b7 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java +++ b/src/main/java/art/arcane/iris/builtin/objects/HeightmapNoise.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.objects; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -67,7 +66,6 @@ public final class HeightmapNoise { @MinNumber(1) @Desc("Multiple octaves for multple generators of changing zooms added together") private int octaves = 1; - @MinItems(1) @Desc("Apply a child noise generator to fracture the input coordinates of this generator") private List fracture = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java index 4ffb1f5cc..db0040d1a 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectPlacement.java @@ -42,7 +42,6 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.ResourceRef; @@ -75,7 +74,6 @@ public final class ObjectPlacement { private static final int DEFAULT_SURFACE_SUPPORT_DEPTH = 2; @Required - @MinItems(1) @ResourceRef(GeneratedObject.class) @Desc("List of objects to place") private List place = List.of(); @@ -116,7 +114,6 @@ public final class ObjectPlacement { @MinNumber(0) @Desc("When bore is enabled, expand max-y of the cuboid it removes") private int boreExtendMaxY = 0; - @MinItems(1) @Desc("Add markers to blocks in this object") private List markers = List.of(); @MaxNumber(64) @@ -159,29 +156,23 @@ public final class ObjectPlacement { private NoiseStyle warp = NoiseStyle.of(NoiseStyle.FLAT); @Desc("The placement mode") private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - @MinItems(1) @Desc("Find and replace blocks") private List edit = List.of(); @Desc("Translate this object's placement") private ObjectTranslate translate = new ObjectTranslate(); @Desc("Scale Objects") private ObjectScale scale = new ObjectScale(); - @MinItems(1) @Desc("The loot tables to apply to these objects") private List loot = List.of(); - @MinItems(1) @Desc("The vanilla loot tables to apply to these objects") private List vanillaLoot = List.of(); @Desc("Whether the given loot tables override any and all other loot tables available in the dimension, region or biome.") private boolean overrideGlobalLoot = false; - @MinItems(1) @Desc("This object / these objects override the following trees when they grow...") private List trees = List.of(); - @MinItems(1) @ResourceRef(GeneratedObject.class) @Desc("List of objects to this object is allowed to collied with") private List allowedCollisions = List.of(); - @MinItems(1) @ResourceRef(GeneratedObject.class) @Desc("List of objects to this object is forbidden to collied with") private List forbiddenCollisions = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java b/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java index a88ddef01..a5a420060 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java +++ b/src/main/java/art/arcane/iris/builtin/objects/ObjectSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -34,7 +33,6 @@ import java.util.List; @Desc("Objects define what schematics (iob files) iris will place here") @Feature(id = "iris:objects", name = "Objects", key = "objects", root = "objects", targets = {Level.REGION, Level.BIOME}) public final class ObjectSettings implements IrisFeature { - @MinItems(1) @Desc("Objects define what schematics (iob files) iris will place here") private List objects = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java b/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java index a7d6a5baa..584c1eb87 100644 --- a/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java +++ b/src/main/java/art/arcane/iris/builtin/objects/TreeOverride.java @@ -19,7 +19,6 @@ package art.arcane.iris.builtin.objects; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -31,12 +30,10 @@ import java.util.List; @Desc("Tree replace options for this object placer") public final class TreeOverride { @Required - @MinItems(1) @Desc("The types of trees overwritten by this object") private List treeTypes = List.of(); @Required - @MinItems(1) @Desc("The size of the square of saplings this applies to (2 means a 2 * 2 sapling area)") private List sizes = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java b/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java index e8a9a0c90..0bf953bfd 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EffectCommands.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -32,7 +31,6 @@ import java.util.List; @Desc("Represents a casting location for a command") public final class EffectCommands { @Required - @MinItems(1) @Desc("Run commands, at the exact location of the player") private List rawCommands = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java b/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java index a1258af7d..8429dffc2 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/EntityDefinition.java @@ -22,7 +22,6 @@ import art.arcane.iris.builtin.loot.ItemAttributeModifier; import art.arcane.iris.builtin.loot.LootEntry; import art.arcane.iris.builtin.loot.LootSettings; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.Ref; import com.volmit.config.Reference; import com.volmit.config.Required; @@ -89,11 +88,9 @@ public final class EntityDefinition { @Desc("Entity off hand equipment") private LootEntry offHand = null; - @MinItems(1) @Desc("Make other entities ride this entity") private List passengers = List.of(); - @MinItems(1) @Desc("Attribute modifiers for this entity") private List attributes = List.of(); @@ -131,7 +128,6 @@ public final class EntityDefinition { @Desc("Set to true if you want to apply all of the settings here to the mob, even though an external plugin has already done so.") private boolean applySettingsToCustomMobAnyways = false; - @MinItems(1) @Desc("Run raw commands when this entity is spawned. Use {x}, {y}, and {z} for location. /summon pig {x} {y} {z}") private List rawCommands = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java index ce9906674..a1b7d1ee2 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/PlacementMarker.java @@ -21,7 +21,6 @@ package art.arcane.iris.builtin.spawn; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.ResourceRef; @@ -34,7 +33,6 @@ import java.util.List; @Snippet("iris/spawn/object-marker") @Desc("Find blocks to mark") public final class PlacementMarker { - @MinItems(1) @Required @Desc("Find block types to mark") private List mark = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java index 03960400e..77aebce99 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnCommand.java @@ -19,7 +19,6 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -30,7 +29,6 @@ import java.util.List; @Desc("Represents a set of Iris commands") public final class SpawnCommand { @Required - @MinItems(1) @Desc("List of commands. Iris replaces {x} {y} and {z} with the location of the entity spawn") private List commands = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java index 249b8fb5a..048699ad8 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/SpawnMarker.java @@ -19,7 +19,6 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.ResourceRef; import java.util.Collections; @@ -30,7 +29,6 @@ import java.util.List; public final class SpawnMarker { @Desc("A list of spawners to add to anywhere this marker is.") @ResourceRef(Spawner.class) - @MinItems(1) private List spawners = List.of(); @Desc("Remove this marker when the block it's assigned to is changed.") diff --git a/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java b/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java index e688df757..e7850f2bd 100644 --- a/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java +++ b/src/main/java/art/arcane/iris/builtin/spawn/Spawner.java @@ -19,7 +19,6 @@ package art.arcane.iris.builtin.spawn; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.Range; import java.util.Collections; @@ -28,11 +27,9 @@ import java.util.List; /** A spawner of the pack, one file of {@code spawners/}: which entities appear where, when and how often. */ @Desc("Represents an entity spawn during initial chunk generation") public final class Spawner { - @MinItems(1) @Desc("The entity spawns to add") private List spawns = List.of(); - @MinItems(1) @Desc("The entity spawns to add initially. EXECUTES PER CHUNK!") private List initialSpawns = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java b/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java index 0a214cb93..63efe0662 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureAdjustment.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.structure; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; @@ -31,7 +30,6 @@ import java.util.Optional; /** One entry of {@link StructureSettings#adjustments()}: how the platform's own starts of the structures it matches are moved and fitted. */ @Desc("A per-structure adjustment applied to vanilla, mod, and datapack structures that still generate natively (those NOT suppressed by an Iris 'structures' placement). Vertical shifts move the structure start, pieces, bounds, and jigsaw metadata together before references and placement. Intersecting trees are cleared automatically inside structure piece envelopes; optional postprocessing can build palette-driven foundation columns.") public final class StructureAdjustment { - @MinItems(1) @Ref(Reference.STRUCTURE_PREFIX) @Desc("Structure keys this adjustment applies to, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' adjusts every village variant and 'minecraft:ruined_portal' adjusts every ruined portal. Empty matches nothing.") private List match = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java index 88678e308..edcaadd59 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacement.java @@ -20,7 +20,6 @@ package art.arcane.iris.builtin.structure; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.ResourceRef; import com.volmit.world.PackBiome; @@ -36,12 +35,10 @@ import java.util.Optional; */ @Desc("Attaches structures to a biome, region or dimension and controls where and how often they generate. This is independent of a structure's own native generation, so you can add custom placements in tandem with native generation or instead of it.") public final class StructurePlacement { - @MinItems(1) @IrisStructureRef @Desc("Editable Iris assembly resources offered by this placement. Leave empty when nativeStructures supplies the source.") private List structures = List.of(); - @MinItems(1) @Desc("Live registered vanilla, datapack, and modded structures offered by this placement. Minecraft runs their native generator directly, independent of normal biome or dimension eligibility.") private List nativeStructures = List.of(); @@ -95,7 +92,6 @@ public final class StructurePlacement { @Desc("Vertical anchor policy. LEGACY preserves the underground boolean. Cave modes search existing carved-space data and implicitly behave as underground placements.") private StructureAnchorMode anchor = StructureAnchorMode.LEGACY; - @MinItems(1) @ResourceRef(PackBiome.class) @Desc("Optional cave-biome allowlist for cave anchor modes. Empty accepts the cave biome resolved at the selected anchor. Entries match by load key, including prefix matches.") private List caveBiomes = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java index 18f450be1..1929d370c 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructurePlacementSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -35,7 +34,6 @@ import java.util.List; @Feature(id = "iris:structure/placements", name = "Structure placements", key = "structures", root = "placements", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class StructurePlacementSettings implements IrisFeature { - @MinItems(1) @Desc("Iris structure placements, each independent of the others.") private List placements = List.of(); diff --git a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java index 82c13a4de..28c180f18 100644 --- a/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java +++ b/src/main/java/art/arcane/iris/builtin/structure/StructureSettings.java @@ -23,7 +23,6 @@ import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; @@ -40,12 +39,10 @@ import java.util.List; @Desc("Controls native vanilla, mod, and ingested datapack structure generation for this dimension. Every registered structure generates through its native placement unless its key matches 'disabled', equals a key in 'disabledExact', or a viable dimension-level Iris placement explicitly replaces its source. Family matching uses namespace, slash, or underscore boundaries, while exact matching compares normalized complete keys only. Run '/iris module structure list' to dump every valid key. Only affects newly generated chunks and is separate from Iris structure placements.") @Feature(id = "iris:structure", name = "Structures", key = "importedStructures", targets = Level.DIMENSION) public final class StructureSettings implements IrisFeature { - @MinItems(1) @Ref(Reference.STRUCTURE_PREFIX) @Desc("Structure keys to deny explicitly, e.g. 'minecraft:stronghold'. A namespace:path prefix also matches, so 'minecraft:village' disables every village variant and 'minecraft:ruined_portal' disables every ruined portal. Every key not matched here remains enabled.") private List disabled = List.of(); - @MinItems(1) @Ref(Reference.STRUCTURE) @Desc("Exact structure keys to deny after trimming and case normalization. Unlike 'disabled', entries never match key families, so 'minecraft:ruined_portal' does not disable 'minecraft:ruined_portal_nether'.") private List disabledExact = List.of(); @@ -58,11 +55,9 @@ public final class StructureSettings implements IrisFeature { @Desc("Controls whether ingested datapacks may replace minecraft-namespaced structure definitions, sets, pools, and templates. When false, those overrides are stripped from installed datapack copies so vanilla definitions stay intact. Non-minecraft structures from datapacks and mods remain governed by disabled because namespace alone cannot identify their origin. Resolved globally across loaded packs: if any dimension sets this false, minecraft-namespaced overrides are stripped from every installed datapack copy.") private boolean datapackOverrides = true; - @MinItems(1) @Desc("Exact registered structure-set frequency overrides for native generation. The last entry for a normalized structure-set key wins. These do not convert native structures into Iris placements and affect only newly generated chunks.") private List frequencyOverrides = List.of(); - @MinItems(1) @Desc("Per-structure adjustments applied to vanilla, mod, and datapack structures that still generate natively. Vertical shifts from every matching entry stack. A matching preserveSourceY option disables Iris burial repositioning for that structure. The last matching entry with stilt settings controls foundation columns, and likewise for terrain and yBand settings. A structure suppressed by an Iris placement is unaffected.") private List adjustments = List.of(); diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java index 1cd6223ba..1910823b5 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralDecoration.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.procedural.part; import com.volmit.block.PaletteSpec; -import com.volmit.config.MinItems; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; @@ -37,7 +36,6 @@ public final class ProceduralDecoration { @Desc("A noise palette to place.") private PaletteSpec palette; - @MinItems(1) @Desc("The roles to decorate. Empty decorates every block.") private List on = List.of(); diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java index a21611c28..8c65d50fa 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralMaterial.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.procedural.part; import com.volmit.block.PaletteSpec; -import com.volmit.config.MinItems; import com.volmit.config.Desc; import com.volmit.config.MinNumber; import com.volmit.config.Ref; @@ -45,7 +44,6 @@ public final class ProceduralMaterial { @Desc("If above 0, the palette changes every this many blocks of height, for strata.") private int bands = 0; - @MinItems(1) @Desc("Swaps for blocks that meet conditions; the first rule that applies wins.") private List rules = List.of(); diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java index 34f231309..8e2721dd8 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralObject.java @@ -17,7 +17,6 @@ */ package art.arcane.iris.engine.procedural.part; -import com.volmit.config.MinItems; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; @@ -36,15 +35,12 @@ public final class ProceduralObject { private long seed = 1337; - @MinItems(1) @Desc("The blocks of each role. A part whose role has no material uses the first one.") private List materials = List.of(); - @MinItems(1) @Desc("The parts the object grows from, each starting at the object's base.") private List parts = List.of(); - @MinItems(1) @Desc("Blocks placed against the finished object, such as vines, moss or fruit.") private List decorations = List.of(); diff --git a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java index 814e67fd9..869e7aa91 100644 --- a/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java +++ b/src/main/java/art/arcane/iris/engine/procedural/part/ProceduralPart.java @@ -17,7 +17,6 @@ */ package art.arcane.iris.engine.procedural.part; -import com.volmit.config.MinItems; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; @@ -69,7 +68,6 @@ public final class ProceduralPart { @Desc("Copies of a part placed around this spot.") private PartCluster cluster; - @MinItems(1) @Desc("The parts that grow from this one.") private List children = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java b/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java index c929a1204..04a5f235f 100644 --- a/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java +++ b/src/main/java/art/arcane/iris/modules/carve/CarvingSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; @@ -40,7 +39,6 @@ import java.util.Set; @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") @Feature(id = "iris:carve/bands", name = "Cave biome bands", key = "carving", root = "entries", targets = Level.DIMENSION) public final class CarvingSettings implements IrisFeature, LinkedBiomes { - @MinItems(1) @Desc("Dimension-level cave biome carving overrides with absolute world Y ranges") private List entries = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java b/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java index d0b895920..4f57b7879 100644 --- a/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java +++ b/src/main/java/art/arcane/iris/modules/carve/CaveProfile.java @@ -26,7 +26,6 @@ import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Range; import com.volmit.config.Snippet; @@ -141,7 +140,6 @@ public final class CaveProfile implements IrisFeature { @Desc("Minimum depth below terrain surface required for cave-only object anchor placement.") private int objectMinDepthBelowSurface = 6; - @MinItems(1) @Desc("Additional layered cave-density modules.") private List modules = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java b/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java index c28f8d4f0..dcc45f779 100644 --- a/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositGenerator.java @@ -21,7 +21,6 @@ package art.arcane.iris.modules.deposit; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -105,7 +104,6 @@ public final class DepositGenerator { private double discardChanceOnAirExposure = 0; @Required - @MinItems(1) @Desc("The palette of blocks to be used in this deposit generator. Each entry is picked uniformly; the per-entry weight field is ignored here.") private List palette = List.of(); @@ -114,18 +112,15 @@ public final class DepositGenerator { @Desc("Ore varience is how many different objects clumps iris will create") private int varience = 3; - @MinItems(1) @Desc("Optional block ids this deposit may replace. An empty list retains Iris's any-solid behavior.") private List replaceableBlocks = List.of(); @Desc("Chooses whether includedBiomes and excludedBiomes inspect the surface biome or the cave biome at the deposit origin.") private DepositBiomeScope biomeScope = DepositBiomeScope.CAVE; - @MinItems(1) @Desc("Optional Iris biome keys or vanilla derivative ids allowed for this deposit.") private List includedBiomes = List.of(); - @MinItems(1) @Desc("Optional Iris biome keys or vanilla derivative ids denied for this deposit.") private List excludedBiomes = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java b/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java index 5a3e9c4c7..45a751f9c 100644 --- a/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java +++ b/src/main/java/art/arcane/iris/modules/deposit/DepositVariantSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -35,7 +34,6 @@ import java.util.List; @Feature(id = "iris:deposit/variants", name = "Deposit variants", key = "depositVariants", root = "variants", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class DepositVariantSettings implements IrisFeature { - @MinItems(1) @Desc("Deposit ore remap rules. Each entry declares a vertical band and a source->replacement block id map. Applied biome first, then region, then dimension; first matching rule wins.") private List variants = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java b/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java index 15c1e0717..a0dd2ecd4 100644 --- a/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingChildBiome.java @@ -22,7 +22,6 @@ import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.terrain.PaletteLayer; import com.volmit.config.Desc; import com.volmit.config.MaxNumber; -import com.volmit.config.MinItems; import com.volmit.config.MinNumber; import com.volmit.config.Ref; import com.volmit.config.Reference; @@ -147,7 +146,6 @@ public final class FloatingChildBiome { @Desc("Controls the material palette near the island underside. DEPTH keeps the old top-down depth behavior. MIRROR_TOP uses the target biome's shallow/top palette from the underside upward. CUSTOM uses bottomPalette near the underside while keeping the target biome palette near the top.") private FloatingBottomPaletteMode bottomPaletteMode = FloatingBottomPaletteMode.DEPTH; - @MinItems(1) @Desc("Custom palette layers used near the underside when bottomPaletteMode=CUSTOM. The layer format is the same as normal biome layers.") private List bottomPalette = List.of(); @@ -193,11 +191,9 @@ public final class FloatingChildBiome { @Desc("Uniform shrink factor applied to every object placed on this floating island (inherited, extra, and free-floating). 1.0 = native size, 0.5 = half size, 0.25 = quarter. Useful for making small floating biomes feel believable.") private double objectShrinkFactor = 1.0; - @MinItems(1) @Desc("Additional object placements anchored to the island top.") private List extraObjects = List.of(); - @MinItems(1) @Desc("Additional object placements that float freely in air, independent of the island. Forced to ObjectPlaceMode.FLOATING.") private List floatingObjects = List.of(); @@ -210,11 +206,9 @@ public final class FloatingChildBiome { @Desc("Controls how bottomObjectOverrides are combined. INHERIT_ONLY (default) = no bottom objects placed (there is no inherited bottom set). MERGE = same as REPLACE for bottom (no inherited source). REPLACE = uses bottomObjectOverrides list only.") private OverrideMode bottomObjectMode = OverrideMode.INHERIT_ONLY; - @MinItems(1) @Desc("Object placements that override or supplement the inherited surface objects on the island TOP. Behaviour depends on topObjectMode. INHERIT_ONLY = this list is ignored. MERGE = appended after inherited. REPLACE = used instead of inherited.") private List topObjectOverrides = List.of(); - @MinItems(1) @Desc("Object placements anchored to the island BOTTOM face. Each entry is auto-inverted 180 degrees around the X axis and placed flush against the lowest solid face of the island, so objects appear to hang upside-down from the underside. WARNING: directional blocks (stairs, doors, slabs) will not render correctly when flipped — use non-directional content (logs, leaves, stone, mycelium, ice, glass) for bottom placements.") private List bottomObjectOverrides = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java b/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java index 4b794a640..4d0cb58a9 100644 --- a/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java +++ b/src/main/java/art/arcane/iris/modules/floating/FloatingChildSettings.java @@ -23,7 +23,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; @@ -42,7 +41,6 @@ import java.util.Set; @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") @Feature(id = "iris:floating/children", name = "Floating child biomes", key = "floatingChildBiomes", root = "children", targets = Level.BIOME) public final class FloatingChildSettings implements IrisFeature, LinkedBiomes { - @MinItems(1) @Desc("Floating child biomes that procedurally generate above this biome's terrain. Each entry references a target biome whose layers, decorators, and objects drive the floating island's visual design, while the config here drives size, shape, altitude, rarity, and water level. Multiple entries are supported and selected by rarity per column unless mergeFloatingChildBiomes is enabled.") private List children = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java b/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java index d79933f74..7555c1477 100644 --- a/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java +++ b/src/main/java/art/arcane/iris/modules/loot/BlockDrop.java @@ -21,7 +21,6 @@ package art.arcane.iris.modules.loot; import art.arcane.iris.builtin.loot.LootEntry; import com.volmit.block.BlockSpec; import com.volmit.config.Desc; -import com.volmit.config.MinItems; import com.volmit.config.Required; import com.volmit.config.Snippet; @@ -32,14 +31,12 @@ import java.util.List; @Desc("Represents a block drop list") public final class BlockDrop { @Required - @MinItems(1) @Desc("The blocks that drop loot") private List blocks = List.of(); @Desc("If exact blocks is set to true, minecraft:barrel[axis=x] will only drop for that axis. When exact is false (default) any barrel will drop the defined drops.") private boolean exactBlocks = false; - @MinItems(1) @Desc("Add in specific items to drop") private List drops = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java b/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java index 87623b317..d8bff017b 100644 --- a/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java +++ b/src/main/java/art/arcane/iris/modules/loot/BlockDropSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -35,7 +34,6 @@ import java.util.List; @Desc("Define custom block drops for this area") @Feature(id = "iris:loot/drops", name = "Block drops", key = "blockDrops", root = "drops", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class BlockDropSettings implements IrisFeature { - @MinItems(1) @Desc("Define custom block drops for this area") private List drops = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java b/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java index 71ba8ca72..d8b545f50 100644 --- a/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java +++ b/src/main/java/art/arcane/iris/modules/spawn/EffectSettings.java @@ -23,7 +23,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -35,7 +34,6 @@ import java.util.List; @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player. All of these effects are played via packets so two players won't see/hear each others effects.\nDue to performance reasons, effects will play arround the player even if where the effect was played is no longer in the biome the player is in.") @Feature(id = "iris:spawn/effects", name = "Effects", key = "effects", root = "effects", targets = {Level.REGION, Level.BIOME}) public final class EffectSettings implements IrisFeature { - @MinItems(1) @Desc("Effects are ambient effects such as potion effects, random sounds, or even particles around each player.") private List effects = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java b/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java index c33a32c7d..2b7921c03 100644 --- a/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java +++ b/src/main/java/art/arcane/iris/modules/spawn/SpawnerSettings.java @@ -23,7 +23,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import com.volmit.config.ResourceRef; import java.util.Collections; @@ -36,7 +35,6 @@ import java.util.List; @Desc("Entity spawners that fire in this area") @Feature(id = "iris:spawn", name = "Entity spawners", key = "entitySpawners", root = "spawners", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class SpawnerSettings implements IrisFeature { - @MinItems(1) @ResourceRef(Spawner.class) @Desc("Entity spawners to add to this area") private List spawners = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java b/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java index 256c9cae4..47fd2fde0 100644 --- a/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java +++ b/src/main/java/art/arcane/iris/modules/terrain/OreSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import java.util.Collections; import java.util.List; @@ -35,7 +34,6 @@ import java.util.List; @Desc("Collection of ores to be generated") @Feature(id = "iris:terrain/ores", name = "Ores", key = "ores", root = "generators", targets = {Level.DIMENSION, Level.REGION, Level.BIOME}) public final class OreSettings implements IrisFeature { - @MinItems(1) @Desc("Collection of ores to be generated") private List generators = List.of(); diff --git a/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java b/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java index 69ee50b1c..45d40f88f 100644 --- a/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java +++ b/src/main/java/art/arcane/iris/modules/vanillafeatures/ImportedFeaturesSettings.java @@ -22,7 +22,6 @@ import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; -import com.volmit.config.MinItems; import com.volmit.vanilla.DecorationStep; import java.util.Collections; @@ -39,15 +38,12 @@ public final class ImportedFeaturesSettings implements IrisFeature { @Desc("Master switch. False (the default) means no native placed feature generates and chunk output is identical to a pack without this block at all. True runs the vanilla decoration feature pass over Iris terrain.") private boolean enabled = false; - @MinItems(1) @Desc("Placed feature keys to deny explicitly, e.g. 'minecraft:ore_diamond'. A namespace:path prefix also matches, so 'minecraft:ore' denies every vanilla ore and 'minecraft:trees' denies every tree placement. Every key not matched here generates while 'enabled' is true.") private List disabled = List.of(); - @MinItems(1) @Desc("Restrict feature generation to these decoration steps only. Empty (the default) means every step is eligible. Use this to import ores without importing vegetation: set it to UNDERGROUND_ORES.") private List steps = List.of(); - @MinItems(1) @Desc("Decoration steps to deny. Applied after 'steps', so a step listed here never generates even if 'steps' allows it. VEGETAL_DECORATION is the usual entry for packs that grow their own trees.") private List disabledSteps = List.of(); From 27b0036450ec91080d2c9d9dffeb1dfdc7ac60e8 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 14:34:26 +0100 Subject: [PATCH 139/139] Stop skipping the cave_ceiling marker in entity spawning No stage writes that marker any more; only cave_floor is left. --- src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java index 805a80fde..41d185490 100644 --- a/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java +++ b/src/main/java/art/arcane/iris/engine/spawn/EntitySpawning.java @@ -60,7 +60,6 @@ public final class EntitySpawning implements EntitySpawns { private static final int BLOCKS_TO_CHUNK_CENTRE = 8; private static final int CHUNK_SIZE = 16; private static final String CAVE_FLOOR_MARKER = "cave_floor"; - private static final String CAVE_CEILING_MARKER = "cave_ceiling"; private static final int AIR_ABOVE_MARKER = 1; private static final long COOLDOWN_CLEANUP_INTERVAL_MILLISECONDS = 60_000L; @@ -96,7 +95,7 @@ public final class EntitySpawning implements EntitySpawns { @Override public Optional marker(PackWorld world, ResourceId tag) { - if (tag.path().equals(CAVE_FLOOR_MARKER) || tag.path().equals(CAVE_CEILING_MARKER)) { + if (tag.path().equals(CAVE_FLOOR_MARKER)) { return Optional.empty(); } SpawnMarker marker = SpawnResources.marker(world.resources(), tag.path());